We have getrandom at home

289 points SpudnikV

In today's post about What "sucks" about Rust, a lot of people echoed a frustration that the standard library doesn't give them easy access to entropy. I commented an easy way that it actually does, but I realize not a lot of people will see a comment that deeply nested, far fewer than the number of people who would actually be glad to see it.

This is all you need to get to get a u64 with the same quality of entropy \[1\] you get for map seeding. (playground)

fn rand64() -> u64 {
    RandomState::new().build_hasher().finish()
}

If you need a lot of these, it'll be better to seed the hasher only once, advance it by writing a bit of junk, and finish() whenever you need a number out. It should still be faster than a system call each time. In a way it's basically what a default rand source would do, except that the algorithm is sip instead of chacha.

By the way, I learned this trick from Go, which is in a similar situation of having a private entropy API easily accessible through a public map hashing API. (playground)

func rand64() uint64 {
    return new(maphash.Hash).Sum64()
}

​

\[1\] Though the full seed takes 2x u64, that has nothing to do with the quality, it's just how much sip needs.