1+ //! `UUIDv4` Type.
2+ use std:: fmt:: { Display , Formatter } ;
3+
4+ use super :: { decode_cbor_uuid, INVALID_UUID } ;
5+
6+ /// Type representing a `UUIDv4`.
7+ #[ derive( Copy , Clone , Debug , PartialEq , PartialOrd , serde:: Deserialize ) ]
8+ #[ serde( from = "uuid::Uuid" ) ]
9+ pub struct UuidV4 {
10+ /// UUID
11+ uuid : uuid:: Uuid ,
12+ }
13+
14+ impl UuidV4 {
15+ /// Version for `UUIDv4`.
16+ const UUID_VERSION_NUMBER : usize = 4 ;
17+
18+ /// Generates a zeroed out `UUIDv4` that can never be valid.
19+ pub fn invalid ( ) -> Self {
20+ Self { uuid : INVALID_UUID }
21+ }
22+
23+ /// Check if this is a valid `UUIDv4`.
24+ pub fn is_valid ( & self ) -> bool {
25+ self . uuid != INVALID_UUID && self . uuid . get_version_num ( ) == Self :: UUID_VERSION_NUMBER
26+ }
27+
28+ /// Returns the `uuid::Uuid` type.
29+ #[ must_use]
30+ pub fn uuid ( & self ) -> uuid:: Uuid {
31+ self . uuid
32+ }
33+ }
34+
35+ impl Display for UuidV4 {
36+ fn fmt ( & self , f : & mut Formatter < ' _ > ) -> Result < ( ) , std:: fmt:: Error > {
37+ write ! ( f, "{}" , self . uuid)
38+ }
39+ }
40+
41+ impl TryFrom < & coset:: cbor:: Value > for UuidV4 {
42+ type Error = anyhow:: Error ;
43+
44+ fn try_from ( cbor_value : & coset:: cbor:: Value ) -> Result < Self , Self :: Error > {
45+ match decode_cbor_uuid ( cbor_value) {
46+ Ok ( uuid) => {
47+ if uuid. get_version_num ( ) == Self :: UUID_VERSION_NUMBER {
48+ Ok ( Self { uuid } )
49+ } else {
50+ anyhow:: bail!( "UUID {uuid} is not `v{}`" , Self :: UUID_VERSION_NUMBER ) ;
51+ }
52+ } ,
53+ Err ( e) => {
54+ anyhow:: bail!( "Invalid UUID. Error: {e}" ) ;
55+ } ,
56+ }
57+ }
58+ }
59+
60+ /// Returns a `UUIDv4` from `uuid::Uuid`.
61+ ///
62+ /// NOTE: This does not guarantee that the `UUID` is valid.
63+ impl From < uuid:: Uuid > for UuidV4 {
64+ fn from ( uuid : uuid:: Uuid ) -> Self {
65+ Self { uuid }
66+ }
67+ }
0 commit comments