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
use multihash::{encode, Hash};
use rust_base58::ToBase58;
use serde::Serialize;
use serde_json;
use std::fmt;
#[derive(PartialOrd, PartialEq, Eq, Ord, Clone, Debug, Serialize, Deserialize, Default, Hash)]
pub struct HashString(String);
impl fmt::Display for HashString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<String> for HashString {
fn from(s: String) -> HashString {
HashString(s)
}
}
impl From<HashString> for String {
fn from(h: HashString) -> String {
h.0
}
}
impl<'a> From<&'a str> for HashString {
fn from(s: &str) -> HashString {
HashString::from(s.to_string())
}
}
impl HashString {
pub fn new() -> HashString {
HashString("".to_string())
}
pub fn encode_from_bytes(bytes: &[u8], hash_type: Hash) -> HashString {
HashString::from(encode(hash_type, bytes).unwrap().to_base58())
}
pub fn encode_from_str(s: &str, hash_type: Hash) -> HashString {
HashString::encode_from_bytes(s.as_bytes(), hash_type)
}
pub fn encode_from_serializable<S: Serialize>(s: S, hash_type: Hash) -> HashString {
HashString::encode_from_str(&serde_json::to_string(&s).unwrap(), hash_type)
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use cas::content::AddressableContent;
use entry::{test_entry, test_entry_address};
use multihash::Hash;
pub fn test_hash() -> HashString {
test_entry().address()
}
#[test]
fn to_string_test() {
assert_eq!(test_hash().to_string(), test_entry_address().to_string(),)
}
#[test]
fn from_string_test() {
assert_eq!(HashString::new(), HashString::from("".to_string()),);
assert_eq!(
test_hash(),
HashString::from(test_entry().address().to_string()),
);
}
#[test]
fn from_str_test() {
assert_eq!(HashString::new(), HashString::from(""));
assert_eq!(test_hash(), HashString::from(test_entry().address()),);
}
#[test]
fn bytes_to_b58_known_golang() {
assert_eq!(
HashString::encode_from_bytes(b"test data", Hash::SHA2256).to_string(),
"QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqh2"
)
}
#[test]
fn str_to_b58_hash_known_golang() {
assert_eq!(
HashString::encode_from_str("test data", Hash::SHA2256).to_string(),
"QmY8Mzg9F69e5P9AoQPYat655HEhc1TVGs11tmfNSzkqh2"
);
}
#[test]
fn can_serialize_to_b58_hash() {
#[derive(Serialize)]
struct Foo {
foo: u8,
};
assert_eq!(
"Qme7Bu4NVYMtpsRtb7e4yyhcbE1zdB9PsrKTdosaqF3Bu3",
HashString::encode_from_serializable(Foo { foo: 5 }, Hash::SHA2256).to_string(),
);
}
}