Skip to content

matklad's dream fastrand #40

@matklad

Description

@matklad

I love fastrand, it's the closest to the ideal prng crate for me, but it is annoyingly not quite there. As I've been thinking about this today, I decided to write my thoughts down. This is very explicitly not a proposal for a change -- I think there's just a difference in values between what fastrand is, and what I want from my idiosyncratic crate. Still, might be interesting for someone. Or maybe one day I'll fork more_opinionated_fastrand or something :)

The overall theme is "remove magic, it's ok if the user needs to write some code themselves if that leads to greater clarity".

So, the list of not-suggested changes:

  • remove interior mutability, the user can wrap in the Cell if they need two.
  • bias creation API towards requiring a seed
#[derive(Debug, PartialEq, Eq)]
pub struct Rng { s: u64 }

impl Rng {
    pub fn new(seed: u64) -> Rng {
        Rng { s: seed }
    }
    #[cfg(feature = "std")]
    pub fn from_entropy() -> Rng {
        Rng::new(random_seed())
    }
    pub fn seed(&self) -> u64 {
        self.s
    }
}

/// get me a random without getrandom
#[cfg(feature = "std")]
fn random_seed() -> u64 {
    std::hash::Hasher::finish(&std::hash::BuildHasher::build_hasher(
        &std::collections::hash_map::RandomState::new(),
    ))
}
  • remove magical Clone, it should either not exist, or create an identical Copy
  • remove Default
  • remove thread-local and global API, to bias towards using seed and passing rng explicitly. Again, the user can wrap the thing into a thread local if they need to.
  • fn u32(impl RangeBounds) -> fn u32(); fn u32_range(impl RangeBounds). .. just looks weird at the call-site
  • fn bool() for a unbiased coint flip, fn bool_ratio(num: u32, denom: u32) for num/denom biased flip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions