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
use crate::{cbor_encodable::CBOREncodable, CBORDecodable, decode_error::DecodeError, CBORCodable};
use super::{cbor::CBOR, varint::{EncodeVarInt, MajorType}, hex::{hex_to_data, data_to_hex}};
#[derive(Clone)]
pub struct Bytes(Vec<u8>);
impl Bytes {
pub fn from_data<T>(data: T) -> Bytes where T: AsRef<[u8]> {
Bytes(data.as_ref().to_owned())
}
pub fn from_hex<T>(hex: T) -> Bytes where T: AsRef<str> {
Bytes(hex_to_data(hex))
}
pub fn data(&self) -> &Vec<u8> {
&self.0
}
pub fn hex(&self) -> String {
data_to_hex(self.data())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl CBOREncodable for Bytes {
fn cbor(&self) -> CBOR {
CBOR::Bytes(self.to_owned())
}
fn cbor_data(&self) -> Vec<u8> {
let a = &self.0;
let mut buf = a.len().encode_varint(MajorType::Bytes);
for b in a {
buf.push(*b);
}
buf
}
}
impl CBORDecodable for Bytes {
fn from_cbor(cbor: &CBOR) -> Result<Box<Self>, crate::decode_error::DecodeError> {
match cbor {
CBOR::Bytes(data) => Ok(Box::new(data.clone())),
_ => Err(DecodeError::WrongType),
}
}
}
impl CBORCodable for Bytes { }
impl PartialEq for Bytes {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl std::fmt::Debug for Bytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&data_to_hex(&self.0))
}
}
impl std::fmt::Display for Bytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("h'")?;
f.write_str(&data_to_hex(&self.0))?;
f.write_str("'")
}
}