2 using System
.Runtime
.InteropServices
;
4 namespace System
.Security
.Cryptography
6 partial class RandomNumberGenerator
8 public static void Fill (Span
<byte> data
)
13 internal static unsafe void FillSpan (Span
<byte> data
)
15 if (data
.Length
> 0) {
16 fixed (byte* ptr
= data
) Interop
.GetRandomBytes (ptr
, data
.Length
);
20 public virtual void GetBytes(Span
<byte> data
)
22 byte[] array
= ArrayPool
<byte>.Shared
.Rent(data
.Length
);
25 GetBytes(array
, 0, data
.Length
);
26 new ReadOnlySpan
<byte>(array
, 0, data
.Length
).CopyTo(data
);
30 Array
.Clear(array
, 0, data
.Length
);
31 ArrayPool
<byte>.Shared
.Return(array
);
35 public virtual void GetNonZeroBytes(Span
<byte> data
)
37 byte[] array
= ArrayPool
<byte>.Shared
.Rent(data
.Length
);
40 // NOTE: There is no GetNonZeroBytes(byte[], int, int) overload, so this call
41 // may end up retrieving more data than was intended, if the array pool
42 // gives back a larger array than was actually needed.
43 GetNonZeroBytes(array
);
44 new ReadOnlySpan
<byte>(array
, 0, data
.Length
).CopyTo(data
);
48 Array
.Clear(array
, 0, data
.Length
);
49 ArrayPool
<byte>.Shared
.Return(array
);
53 public static int GetInt32(int fromInclusive
, int toExclusive
)
55 if (fromInclusive
>= toExclusive
)
56 throw new ArgumentException(SR
.Argument_InvalidRandomRange
);
58 // The total possible range is [0, 4,294,967,295).
59 // Subtract one to account for zero being an actual possibility.
60 uint range
= (uint)toExclusive
- (uint)fromInclusive
- 1;
62 // If there is only one possible choice, nothing random will actually happen, so return
63 // the only possibility.
69 // Create a mask for the bits that we care about for the range. The other bits will be
78 Span
<uint> resultSpan
= stackalloc uint[1];
83 FillSpan(MemoryMarshal
.AsBytes(resultSpan
));
84 result
= mask
& resultSpan
[0];
86 while (result
> range
);
88 return (int)result
+ fromInclusive
;
91 public static int GetInt32(int toExclusive
)
94 throw new ArgumentOutOfRangeException(nameof(toExclusive
), SR
.ArgumentOutOfRange_NeedPosNum
);
96 return GetInt32(0, toExclusive
);