www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - saving std.random RNG state

reply harfel <dadapapa gmail.com> writes:
I am looking for a way to serialize/deserialize the state of the 
std.random.Random number generator, ideally using orange 
(https://github.com/jacob-carlborg/orange) or another 
serialization library. From looking at the module source code, I 
understand how to seed a random number generator with the state 
of another, but I do find a way to access the RNG's state, since 
it is hidden away in a private attribute. What is the recommended 
solution for this? Thanks in advance!
Dec 17 2018
parent reply Neia Neutuladh <neia ikeran.org> writes:
On Mon, 17 Dec 2018 22:20:54 +0000, harfel wrote:
 I am looking for a way to serialize/deserialize the state of the
 std.random.Random number generator, ideally using orange
 (https://github.com/jacob-carlborg/orange) or another serialization
 library. From looking at the module source code, I understand how to
 seed a random number generator with the state of another, but I do find
 a way to access the RNG's state, since it is hidden away in a private
 attribute. What is the recommended solution for this? Thanks in advance!
The .tupleof field allows you to access private members. This behavior might eventually change, but probably not without a long deprecation period. If the struct stores everything by value: cast(ubyte[])&rng[0..1]; If you have typeinfo available, you can check if the thing has pointers with `(typeof(rng).flags & 1) == 0`. There's probably an equivalent in std.traits that works at compile time.
Dec 17 2018
parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 12/17/18 8:18 PM, Neia Neutuladh wrote:
 On Mon, 17 Dec 2018 22:20:54 +0000, harfel wrote:
 I am looking for a way to serialize/deserialize the state of the
 std.random.Random number generator, ideally using orange
 (https://github.com/jacob-carlborg/orange) or another serialization
 library. From looking at the module source code, I understand how to
 seed a random number generator with the state of another, but I do find
 a way to access the RNG's state, since it is hidden away in a private
 attribute. What is the recommended solution for this? Thanks in advance!
The .tupleof field allows you to access private members. This behavior might eventually change, but probably not without a long deprecation period. If the struct stores everything by value: cast(ubyte[])&rng[0..1]; If you have typeinfo available, you can check if the thing has pointers with `(typeof(rng).flags & 1) == 0`. There's probably an equivalent in std.traits that works at compile time.
std.traits.hasIndirections https://dlang.org/phobos/std_traits.html#hasIndirections In terms of storing the state, I find generally just using the same seed is best, but I can see use cases for storing the state for usage elsewhere. I don't see a better way than using a ubyte[] cast. -Steve
Dec 18 2018