arbitrary/foreign/core/
char.rs

1use crate::{Arbitrary, Result, Unstructured};
2
3impl<'a> Arbitrary<'a> for char {
4    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
5        // The highest unicode code point is 0x11_FFFF
6        const CHAR_END: u32 = 0x11_0000;
7        // The size of the surrogate blocks
8        const SURROGATES_START: u32 = 0xD800;
9        let mut c = <u32 as Arbitrary<'a>>::arbitrary(u)? % CHAR_END;
10        if let Some(c) = char::from_u32(c) {
11            Ok(c)
12        } else {
13            // We found a surrogate, wrap and try again
14            c -= SURROGATES_START;
15            Ok(char::from_u32(c)
16                .expect("Generated character should be valid! This is a bug in arbitrary-rs"))
17        }
18    }
19
20    #[inline]
21    fn size_hint(depth: usize) -> (usize, Option<usize>) {
22        <u32 as Arbitrary<'a>>::size_hint(depth)
23    }
24}