forked from Sovos-Compliance/convey-public-libs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
uThreadSafeXorShiftRandom.pas
70 lines (57 loc) · 1.71 KB
/
uThreadSafeXorShiftRandom.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
{ Thread-safe Xorshift+ generator by Saito and Matsumoto }
unit uThreadSafeXorShiftRandom;
interface
function Random : Int64; overload;
function Random(const Range : Int64) : Int64; overload;
procedure Randomize;
procedure SetRandSeed(ALowPart, AHighPart : Int64);
implementation
uses
Windows, SysUtils;
resourcestring
SHighPartAndLowPartOfRandSeedCantBeEqual = 'HighPart and LowPart of RandSeed can''t be equal';
var
RandSeed : array[0..1] of Int64;
{$IFDEF VER180}
function InterlockedCompareExchange64(var Destination: Int64; Exchange: Int64; Comparand: Int64): Int64; stdcall; external kernel32 name 'InterlockedCompareExchange64';
{$EXTERNALSYM InterlockedCompareExchange64}
{$ENDIF}
function Random : Int64; overload;
var
x, y : Int64;
begin
repeat
x := RandSeed[0];
y := RandSeed[1];
until (x <> y) and (InterlockedCompareExchange64(RandSeed[0], y, x) = x);
x := x xor (x shl 23);
x := x xor (x shr 17);
x := x xor (y xor (y shr 26));
RandSeed[1] := x;
Result := x + y;
end;
function Random(const Range : Int64) : Int64; overload;
begin
Result := abs(uThreadSafeXorShiftRandom.Random) mod Range;
end;
procedure Randomize;
var
x, y : Int64;
begin
System.Randomize;
repeat
x := RandSeed[0];
y := RandSeed[1];
until (x <> y) and (InterlockedCompareExchange64(RandSeed[0], Int64(System.Random(MaxInt)) or (Int64(System.Random(MaxInt)) shl 32), x) = x);
RandSeed[1] := Int64(System.Random(MaxInt)) or (Int64(System.Random(MaxInt)) shl 32);
end;
procedure SetRandSeed(ALowPart, AHighPart : Int64);
begin
if ALowPart = AHighPart then
raise Exception.Create(SHighPartAndLowPartOfRandSeedCantBeEqual);
end;
initialization
RandSeed[0] := 1;
RandSeed[1] := 2;
Randomize;
end.