compact_str/features/
arbitrary.rs

1//! Implements the [`arbitrary::Arbitrary`] trait for [`CompactString`]
2
3use arbitrary::{Arbitrary, Result, Unstructured};
4
5use crate::CompactString;
6
7#[cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))]
8impl<'a> Arbitrary<'a> for CompactString {
9    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
10        <&str as Arbitrary>::arbitrary(u).map(CompactString::new)
11    }
12
13    fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self> {
14        <&str as Arbitrary>::arbitrary_take_rest(u).map(CompactString::new)
15    }
16
17    #[inline]
18    fn size_hint(depth: usize) -> (usize, Option<usize>) {
19        <&str as Arbitrary>::size_hint(depth)
20    }
21}
22
23#[cfg(test)]
24mod test {
25    use arbitrary::{Arbitrary, Unstructured};
26
27    use crate::CompactString;
28
29    #[test]
30    fn arbitrary_sanity() {
31        let mut data = Unstructured::new(&[42; 50]);
32        let compact = CompactString::arbitrary(&mut data).expect("generate a CompactString");
33
34        // we don't really care what the content of the CompactString is, just that one's generated
35        assert!(!compact.is_empty());
36    }
37
38    #[test]
39    fn arbitrary_inlines_strings() {
40        let mut data = Unstructured::new(&[42; 20]);
41        let compact = CompactString::arbitrary(&mut data).expect("generate a CompactString");
42
43        // running this manually, we generate the string "**"
44        assert!(!compact.is_heap_allocated());
45    }
46}