40 lines
1.0 KiB
C#
40 lines
1.0 KiB
C#
using System;
|
|
|
|
namespace VMdemo.Simulation
|
|
{
|
|
public class AddressGenerator
|
|
{
|
|
public const int DefaultSeed = 12345;
|
|
|
|
private readonly int _vaBits;
|
|
private readonly ulong _vaMask;
|
|
private readonly Random _random;
|
|
private readonly byte[] _buffer = new byte[8];
|
|
|
|
public AddressGenerator(int vaBits, int? seed = null)
|
|
{
|
|
if (vaBits != 32 && vaBits != 48 && vaBits != 64)
|
|
{
|
|
throw new ArgumentOutOfRangeException(nameof(vaBits), "vaBits 仅支持 32、48、64。");
|
|
}
|
|
|
|
_vaBits = vaBits;
|
|
_vaMask = vaBits == 64 ? ulong.MaxValue : (1UL << vaBits) - 1UL;
|
|
_random = new Random(seed ?? DefaultSeed);
|
|
}
|
|
|
|
public ulong MaxVirtualAddress => _vaMask;
|
|
|
|
public ulong NextVirtualAddress()
|
|
{
|
|
return NextRawUlong() & _vaMask;
|
|
}
|
|
|
|
private ulong NextRawUlong()
|
|
{
|
|
_random.NextBytes(_buffer);
|
|
return BitConverter.ToUInt64(_buffer, 0);
|
|
}
|
|
}
|
|
}
|