Skip to content

Conversation

@dhardy
Copy link
Member

@dhardy dhardy commented Jan 1, 2021

@newpavlov review?

If all goes well I'll release this plus the new rand patch (#1081) in a couple of days.

Copy link
Member

@newpavlov newpavlov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! A slightly more efficient version can look like this:

// We use PCG32 to generate a u32 sequence, and copy to the seed
fn pcg32(state: &mut u64) -> [u8; 4] {
    const MUL: u64 = 6364136223846793005;
    const INC: u64 = 11634580027462260723;

    // We advance the state first (to get away from the input value,
    // in case it has low Hamming Weight).
    *state = state.wrapping_mul(MUL).wrapping_add(INC);
    let state = *state;

    // Use PCG output function with to_le to generate x:
    let xorshifted = (((state >> 18) ^ state) >> 27) as u32;
    let rot = (state >> 59) as u32;
    let x = xorshifted.rotate_right(rot);
    x.to_le_bytes()
}

let mut seed = Self::Seed::default();
let mut iter = seed.as_mut().chunks_exact_mut(4);
for chunk in &mut iter {
    chunk.copy_from_slice(&pcg32(&mut state));
}
let rem = iter.into_remainder();
if !rem.is_empty() {
    rem.copy_from_slice(&pcg32(&mut state)[..rem.len()]);
}

@dhardy
Copy link
Member Author

dhardy commented Jan 1, 2021

I suspect the above relies on inlining to be more optimal, thus increases code size. Is the optimisation important here? Seeding is not usually frequent.

@newpavlov
Copy link
Member

pcg32 takes less than 10 instructions. Considering that compiler usually will unroll the loop, such hypothetical increase does not really matter. Plus most (if not all?) seeds are multiple of 4 bytes, so the last if will be removed by compiler. Compiler may optimize out unnecessary slicing in the chunks_mut-based loop for such seeds as well, so I would say that choosing between them is a matter of taste.

@dhardy
Copy link
Member Author

dhardy commented Jan 2, 2021

I can buy that argument 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants