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