Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid surrogates when generating char using Standard distribution #519

Merged
merged 2 commits into from Jun 21, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 14 additions & 8 deletions src/distributions/other.rs
Expand Up @@ -44,15 +44,21 @@ pub struct Alphanumeric;
impl Distribution<char> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
let range = Uniform::new(0u32, 0x11_0000);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Could we make this new(0u32, char::MAX as u32)? More explicit about what we're doing

Copy link
Member

Choose a reason for hiding this comment

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

This line is being removed. But I don't think this is a good idea; you're off by 1 (should be inclusive) and if char::MAX were ever to change we don't know now whether we should use the whole range (minus the existing gap). So better just to use local constants as in the current implementation.

loop {
match char::from_u32(range.sample(rng)) {
Some(c) => return c,
// About 0.2% of numbers in the range 0..0x110000 are invalid
// codepoints (surrogates).
None => {}
}
// A valid `char` is either in the interval `[0, 0xD800)` or
// `(0xDFFF, 0x11_0000)`. All `char`s must therefore be in
// `[0, 0x11_0000)` but not in the "gap" `[0xD800, 0xDFFF]` which is
// reserved for surrogates. This is the size of that gap.
const GAP_SIZE: u32 = 0xDFFF - 0xD800 + 1;

// Uniform::new(0, 0x11_0000 - GAP_SIZE) can also be used but it
// seemed slower.
let range = Uniform::new(GAP_SIZE, 0x11_0000);

let mut n = range.sample(rng);
if n <= 0xDFFF {
n -= GAP_SIZE;
}
unsafe { char::from_u32_unchecked(n) }
}
}

Expand Down