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
pub fn tag(value: &str) -> Option<[u8; 32]> {
if value.len().gt(&32) {
return None;
}
let mut _tag = [0_u8; 32];
for (idx, b) in value.as_bytes().iter().enumerate() {
_tag[idx] = *b;
}
Some(_tag)
}
pub fn tag_to_str(data: &[u8; 32]) -> String {
let mut value = String::with_capacity(32);
data.iter().for_each(|b| {
let b = *b;
if b != 0 {
value.push(b as char);
}
});
value
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tag() {
let tag_msg = "tulip".to_string();
let _want_tag_msg = String::from("tulip\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}");
let mut too_big_tag = String::with_capacity(100);
for _ in 0..100 {
too_big_tag.push('a');
}
assert!(tag(&too_big_tag).is_none());
let tag_bytes = tag(&tag_msg).unwrap();
let got_tag_msg = tag_to_str(&tag_bytes);
assert_eq!(got_tag_msg, tag_msg);
}
}