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
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct Bytes {
pub raw: Vec<u8>,
}
impl Default for Bytes {
fn default() -> Self {
Self::new(vec![])
}
}
impl Bytes {
pub fn new(raw: Vec<u8>) -> Self {
Self { raw }
}
pub fn as_raw(&self) -> &Vec<u8> {
&self.raw
}
pub fn into_raw(self) -> Vec<u8> {
self.raw
}
pub fn set_raw(&mut self, raw: Vec<u8>) {
self.raw = raw
}
pub fn push(&mut self, item: u8) {
self.raw.push(item);
}
pub fn empty() -> Self {
Self::new(vec![])
}
pub fn as_str_lossy(&self) -> Result<&str, std::str::Utf8Error> {
std::str::from_utf8(self.as_raw())
}
pub fn to_string_lossy(&self) -> String {
String::from_utf8_lossy(self.as_raw()).into_owned()
}
pub fn to_string(&self) -> Result<String, std::string::FromUtf8Error> {
String::from_utf8(self.as_raw().to_vec())
}
pub fn into_string(self) -> Result<String, std::string::FromUtf8Error> {
String::from_utf8(self.into_raw())
}
pub fn is_valid_utf8(&self) -> bool {
std::str::from_utf8(self.as_raw()).is_ok()
}
pub fn is_empty(&self) -> bool {
self.as_raw().is_empty()
}
pub fn len(&self) -> usize {
self.as_raw().len()
}
pub fn clear(&mut self) {
self.set_raw(vec![])
}
}
impl std::ops::Index<usize> for Bytes {
type Output = u8;
fn index(&self, index: usize) -> &Self::Output {
self.raw.index(index)
}
}
#[test]
fn test_new() {
let bytes = Bytes::new(vec![1, 2, 3]);
drop(bytes);
}
#[test]
fn test_as_raw() {
let bytes = Bytes::new(vec![1, 2, 3]);
assert_eq!(bytes.as_raw(), &vec![1, 2, 3])
}
#[test]
fn test_into_raw() {
let bytes = Bytes::new(vec![1, 2, 3]);
assert_eq!(bytes.into_raw(), vec![1, 2, 3])
}
#[test]
fn test_set_raw() {
let mut bytes = Bytes::new(vec![1, 2, 3]);
bytes.set_raw(vec![4, 5, 6]);
assert_eq!(bytes.as_raw(), &vec![4, 5, 6])
}
#[test]
fn test_push() {
let mut bytes = Bytes::default();
for i in 0..10 {
bytes.push(i);
}
assert_eq!(bytes.as_raw(), &vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
}