arbitrary/foreign/core/
char.rs

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