Skip to main content

uuid/external/
arbitrary_support.rs

1use crate::{non_nil::NonNilUuid, Builder, Uuid};
2
3use arbitrary::{Arbitrary, Unstructured};
4
5impl Arbitrary<'_> for Uuid {
6    fn arbitrary(u: &mut Unstructured<'_>) -> arbitrary::Result<Self> {
7        let b = u
8            .bytes(16)?
9            .try_into()
10            .map_err(|_| arbitrary::Error::NotEnoughData)?;
11
12        Ok(Builder::from_random_bytes(b).into_uuid())
13    }
14
15    fn size_hint(_: usize) -> (usize, Option<usize>) {
16        (16, Some(16))
17    }
18}
19impl arbitrary::Arbitrary<'_> for NonNilUuid {
20    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
21        let uuid = Uuid::arbitrary(u)?;
22        Self::try_from(uuid).map_err(|_| arbitrary::Error::IncorrectFormat)
23    }
24
25    fn size_hint(_: usize) -> (usize, Option<usize>) {
26        (16, Some(16))
27    }
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33
34    use crate::{Variant, Version};
35
36    #[test]
37    fn test_arbitrary() {
38        let mut bytes = Unstructured::new(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
39
40        let uuid = Uuid::arbitrary(&mut bytes).unwrap();
41
42        assert_eq!(Some(Version::Random), uuid.get_version());
43        assert_eq!(Variant::RFC4122, uuid.get_variant());
44    }
45
46    #[test]
47    fn test_arbitrary_empty() {
48        let mut bytes = Unstructured::new(&[]);
49
50        // Ensure we don't panic when building an arbitrary `Uuid`
51        let uuid = Uuid::arbitrary(&mut bytes);
52
53        assert!(uuid.is_err());
54    }
55
56    #[test]
57    fn test_arbitrary_non_nil() {
58        let mut bytes = Unstructured::new(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
59
60        let non_nil_uuid = NonNilUuid::arbitrary(&mut bytes).unwrap();
61        let uuid: Uuid = non_nil_uuid.into();
62
63        assert_eq!(Some(Version::Random), uuid.get_version());
64        assert_eq!(Variant::RFC4122, uuid.get_variant());
65        assert!(!uuid.is_nil());
66    }
67}