1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use std::{fmt::Display, hash::Hash, ops::Deref};
use serde::{Deserialize, Serialize};
macro_rules! string_coherent {
($wrapper:ty) => {
impl Deref for $wrapper {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Hash for $wrapper {
fn hash<H>(&self, hasher: &mut H)
where
H: std::hash::Hasher,
{
self.0.hash(hasher)
}
}
impl From<&str> for $wrapper {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl From<String> for $wrapper {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<$wrapper> for String {
fn from(value: $wrapper) -> Self {
value.0
}
}
impl PartialEq<String> for $wrapper {
fn eq(&self, other: &String) -> bool {
&self.0 == other
}
}
impl PartialEq<$wrapper> for String {
fn eq(&self, other: &$wrapper) -> bool {
self == &other.0
}
}
impl Display for $wrapper {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.0, f)
}
}
impl AsRef<[u8]> for $wrapper {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
};
}
#[repr(transparent)]
#[derive(Default, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct Did(pub String);
string_coherent!(Did);
#[repr(transparent)]
#[derive(Default, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct Jwt(pub String);
string_coherent!(Jwt);
#[repr(transparent)]
#[derive(Default, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct Mnemonic(pub String);
#[cfg(test)]
mod tests {
use libipld_cbor::DagCborCodec;
use noosphere_storage::{block_deserialize, block_serialize};
use serde::{Deserialize, Serialize};
use crate::data::Did;
#[test]
fn it_serializes_a_did_transparently_as_a_string() {
#[derive(Serialize, Deserialize)]
struct FooDid {
foo: Did,
}
#[derive(Serialize, Deserialize)]
struct FooString {
foo: String,
}
let string_value = String::from("foobar");
let (did_cid, did_block) = block_serialize::<DagCborCodec, _>(&FooDid {
foo: Did(string_value.clone()),
})
.unwrap();
let (string_cid, string_block) = block_serialize::<DagCborCodec, _>(&FooString {
foo: string_value.clone(),
})
.unwrap();
assert_eq!(did_cid, string_cid);
assert_eq!(did_block, string_block);
let did_from_string = block_deserialize::<DagCborCodec, FooDid>(&string_block).unwrap();
let string_from_did = block_deserialize::<DagCborCodec, FooString>(&did_block).unwrap();
assert_eq!(did_from_string.foo, Did(string_value.clone()));
assert_eq!(string_from_did.foo, string_value);
}
}