ledger_models/fintekkers/wrappers/models/utils/
uuid_wrapper.rs1use std::fmt;
2
3use crate::fintekkers::wrappers::models::utils::errors::Error;
4use crate::fintekkers::models::util::UuidProto;
5use uuid::Uuid;
6
7pub struct UUIDWrapper {
8 proto: UuidProto,
9}
10
11impl UUIDWrapper {
12 pub fn new(proto: UuidProto) -> Self {
13 UUIDWrapper { proto }
14 }
15
16 pub fn new_random() -> Self {
17 let tmp_uuid = Uuid::new_v4();
18
19 UUIDWrapper {
20 proto: UuidProto {
21 raw_uuid: tmp_uuid.into_bytes().into(),
22 },
23 }
24 }
25
26 pub fn as_uuid(&self) -> Uuid {
27 Uuid::try_from(self).unwrap()
28 }
29}
30
31
32impl TryFrom<&str> for UUIDWrapper {
33 type Error = Error;
34 fn try_from(value: &str) -> Result<UUIDWrapper, Error> {
35 let tmp_uuid = Uuid::parse_str(value)
36 .map_err(|_| Error::UuidError)?;
37
38 Ok(UUIDWrapper {
39 proto: UuidProto {
40 raw_uuid: tmp_uuid.into_bytes().into(),
41 },
42 })
43 }
44}
45
46impl From<UUIDWrapper> for UuidProto {
47 fn from(wrapper:UUIDWrapper) -> UuidProto {
48 wrapper.proto
49 }
50}
51
52impl From<Vec<u8>> for UUIDWrapper {
53 fn from(value: Vec<u8>) -> Self {
54 UUIDWrapper {
55 proto: UuidProto { raw_uuid: value },
56 }
57 }
58}
59
60impl TryFrom<&UUIDWrapper> for Uuid {
61 type Error = Error;
62 fn try_from(wrapper: &UUIDWrapper) -> Result<Uuid, Error> {
63 Uuid::from_slice(&wrapper.proto.raw_uuid).map_err(|_| Error::UuidError)
64 }
65}
66
67impl fmt::Display for UUIDWrapper {
68 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
69 let tmp_uuid: Uuid = self.try_into().map_err(|_| fmt::Error)?;
70
71 fmt.write_str(&tmp_uuid.to_string())?;
72
73 Ok(())
74 }
75}
76
77#[cfg(test)]
78mod test {
79 use std::str::FromStr;
80 use super::*;
81 use uuid::Uuid;
82
83 #[test]
84 fn test_uuid_to_proto_and_back() {
85 let input_array = [217, 98, 253, 240, 51, 225, 77, 157, 153, 155, 126, 195, 80, 240, 203, 119];
86 let input = Vec::from(input_array);
87
88 let uuid = Uuid::from_slice(&input).unwrap();
89 let uuid_str = uuid.to_string();
90 println!("{}", uuid_str);
91
92 let uuid2 = Uuid::from_str(&"d962fdf0-33e1-4d9d-999b-7ec350f0cb77").unwrap();
93 let uuid2_str = uuid2.to_string();
94 println!("{}", uuid2_str);
95
96 let output_bytes = uuid2.into_bytes().to_vec();
97 assert_eq!(input, output_bytes);
98
99 let random = UUIDWrapper::new_random();
100 let random_str = random.to_string();
101
102 let copy_of_random: Uuid = Uuid::try_from(&random).expect("failed conversion");
103
104 assert_eq!(random_str, copy_of_random.to_string())
105 }
106}