Skip to content

Add Random Span-based APIs #22804

@stephentoub

Description

@stephentoub

Separated out of https://github.com/dotnet/corefx/issues/21281 for tracking purposes.

  • Implement in System.Private.CoreLib in coreclr (corert shares the same file)
  • Expose from System.Runtime.Extensions contract in corefx
  • Add tests to System.Runtime.Extensions tests in corefx
namespace System
{
    public class Random
    {
        public virtual void NextBytes(Span<byte> buffer);}
}

Implementation should be in terms of Next(). The NextBytes(byte[]) base method is implemented in terms of InternalSample, but NextBytes(Span<byte>) shouldn't be implemented in terms of that, as it's not public and thus an existing derived type couldn't have overridden it, and thus the new virtual wouldn't pick up existing behaviors. It also shouldn't be in terms of NextBytes(byte[]), as that would require allocating/copying an array, largely defeating the purpose of the method (at least for the base class). But since Next() on the base class just delegates to InternalSample(), Next() is a reasonable thing to base the implementation on, e.g.

public virtual void NextBytes(Span<byte> buffer)
{
    for (int i = 0; i < buffer.Length; i++)
    {
        buffer[i] = (byte)(Next() & 0xFF);
    }
}

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions