generalise shared prng functionality to interfaces

This commit is contained in:
a dinosaur 2024-08-23 09:13:42 +10:00
parent 39d46da7f7
commit efd9905f5b
3 changed files with 29 additions and 7 deletions

View File

@ -1,5 +1,6 @@
public struct PCG32Random: RandomProvider {
public struct PCG32Random: RandomProvider, RandomStateAccess {
public typealias Output = UInt32
public typealias StateType = (UInt64, UInt64)
public static var min: UInt32 { .min }
public static var max: UInt32 { .max }
@ -19,12 +20,12 @@ public struct PCG32Random: RandomProvider {
self._inc = 0xDA3E39CB94B95BDB
}
public init(seed: UInt64, sequence: UInt64) {
public init(state: (UInt64, UInt64)) {
self.init()
self.seed(state: _state, sequence: sequence)
self.reset(state: state.0, sequence: state.1)
}
public mutating func seed(state: UInt64, sequence: UInt64) {
public mutating func reset(state: UInt64, sequence: UInt64) {
self._state = 0
self._inc = sequence << 1 | 0x1
_ = next()

View File

@ -6,3 +6,18 @@ public protocol RandomProvider {
mutating func next() -> Output
}
public protocol RandomSeedable {
associatedtype SeedType: FixedWidthInteger
init(seed: SeedType)
mutating func seed(_ value: SeedType)
}
public protocol RandomStateAccess {
associatedtype StateType
var state: StateType { get set }
init(state: StateType)
}

View File

@ -1,5 +1,7 @@
struct Xoroshiro128Plus: RandomProvider {
struct Xoroshiro128Plus: RandomProvider, RandomSeedable, RandomStateAccess {
public typealias Output = UInt64
public typealias SeedType = UInt64
public typealias StateType = (UInt64, UInt64)
static public var min: UInt64 { .min }
static public var max: UInt64 { .max }
@ -36,8 +38,10 @@ struct Xoroshiro128Plus: RandomProvider {
}
}
struct Xoroshiro128PlusPlus: RandomProvider {
struct Xoroshiro128PlusPlus: RandomProvider, RandomSeedable, RandomStateAccess {
public typealias Output = UInt64
public typealias SeedType = UInt64
public typealias StateType = (UInt64, UInt64)
static public var min: UInt64 { .min }
static public var max: UInt64 { .max }
@ -74,8 +78,10 @@ struct Xoroshiro128PlusPlus: RandomProvider {
}
}
struct Xoroshiro128StarStar: RandomProvider {
struct Xoroshiro128StarStar: RandomProvider, RandomSeedable, RandomStateAccess {
public typealias Output = UInt64
public typealias SeedType = UInt64
public typealias StateType = (UInt64, UInt64)
static public var min: UInt64 { .min }
static public var max: UInt64 { .max }