smol-rs / fastrand

A simple and fast random number generator
Apache License 2.0
409 stars 35 forks source link

Remove Internal Mutability #31

Closed DE0CH closed 1 year ago

DE0CH commented 2 years ago

I am thinking if we can remove the internal mutability in Rng(Cell<u64>) by just using Rng<u64> and implementing methods with fn ...(&mut self). This behaviour is more consistent with the rand crate and it also makes more logical sense because an rng mutates as you use it.

This change will definitely need a major version bump.

notgull commented 2 years ago

What would be the use case for this? I enjoy being able to use an RNG from a shared reference

DE0CH commented 2 years ago

I was thinking of racing condition in concurrent thread, but the Cell prevents you from sharing an rng between threads. Now I can't think of any case where refactoring this would be beneficial. Perhaps there are some edge cases where only one mutable borrow rule can detect some bugs but I can't think of any. One minor usefulness is that it makes it clear to the user that calling .u64(..) twice will not give you the same result.

fogti commented 2 years ago

A case where removing the interior mutability would be beneficial is when it is intended to share a Rng across threads, e.g. #26, that is, when someone wants to use a different interior-mutability abstraction, which is e.g. thread safe, or uses atomics instead.

notgull commented 2 years ago

The use case in #26 is pretty tempting, now that I think about it. I could implement this (it would also let this crate by no_std).