bc_ur/
ur_codable.rs

1use crate::{ UREncodable, URDecodable };
2
3/// A type that can be encoded to and decoded from a UR.
4pub trait URCodable {}
5
6impl<T> URCodable for T where T: UREncodable + URDecodable {}
7
8#[cfg(test)]
9mod tests {
10    use dcbor::prelude::*;
11    use super::*;
12
13    #[derive(Debug, PartialEq)]
14    struct Test {
15        s: String,
16    }
17
18    impl Test {
19        fn new(s: &str) -> Self {
20            Self { s: s.to_string() }
21        }
22    }
23
24    impl CBORTagged for Test {
25        fn cbor_tags() -> Vec<Tag> {
26            vec![Tag::new(24, "leaf")]
27        }
28    }
29
30    impl From<Test> for CBOR {
31        // This ensures that asking for the CBOR for this type will always
32        // return a tagged CBOR value.
33        fn from(value: Test) -> Self {
34            value.tagged_cbor()
35        }
36    }
37
38    impl CBORTaggedEncodable for Test {
39        // This is the core of the CBOR encoding for this type. It is the
40        // untagged CBOR encoding.
41        fn untagged_cbor(&self) -> CBOR {
42            self.s.clone().into()
43        }
44    }
45
46    impl TryFrom<CBOR> for Test {
47        type Error = dcbor::Error;
48
49        // This ensures that asking for the CBOR for this type will always
50        // expect a tagged CBOR value.
51        fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
52            Self::from_tagged_cbor(cbor)
53        }
54    }
55
56    impl CBORTaggedDecodable for Test {
57        // This is the core of the CBOR decoding for this type. It is the
58        // untagged CBOR decoding.
59        fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
60            let s: String = cbor.try_into()?;
61            Ok(Self::new(&s))
62        }
63    }
64
65    #[test]
66    fn test_ur_codable() {
67        let test = Test::new("test");
68        let ur = test.ur();
69        let ur_string = ur.string();
70        assert_eq!(ur_string, "ur:leaf/iejyihjkjygupyltla");
71        let test2 = Test::from_ur_string(ur_string).unwrap();
72        assert_eq!(test.s, test2.s);
73    }
74}