-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathbytes.rs
More file actions
114 lines (93 loc) · 2.21 KB
/
bytes.rs
File metadata and controls
114 lines (93 loc) · 2.21 KB
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
use sea_streamer::Buffer;
use std::str::Utf8Error;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
/// Blob of Bytes. Right now it is backed by a `Vec<u8>`.
///
/// But if this becomes a bottleneck we should back it with a custom allocator.
pub struct Bytes(Vec<u8>);
impl Default for Bytes {
fn default() -> Self {
Self::new()
}
}
impl Bytes {
pub fn new() -> Self {
Self(Default::default())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, i: usize) -> u8 {
self.0[i]
}
pub fn slice(&self, p: usize, q: usize) -> &[u8] {
&self.0[p..q]
}
pub fn push_byte(&mut self, byte: u8) {
self.0.push(byte);
}
pub fn push_bytes(&mut self, mut bytes: Self) {
self.0.append(&mut bytes.0);
}
pub fn push_slice(&mut self, bytes: &[u8]) {
self.0.extend_from_slice(bytes);
}
pub fn push_string(&mut self, string: String) {
self.0.append(&mut string.into_bytes());
}
pub fn push_str(&mut self, str: &str) {
self.0.extend_from_slice(str.as_bytes());
}
pub fn clear(&mut self) {
self.0.clear();
}
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub fn into_bytes(self) -> Vec<u8> {
self.0
}
}
impl From<Vec<u8>> for Bytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
macro_rules! impl_into_bytes {
($ty: ty) => {
impl From<$ty> for Bytes {
fn from(v: $ty) -> Self {
v.to_ne_bytes().to_vec().into()
}
}
};
}
impl_into_bytes!(u8);
impl_into_bytes!(i8);
impl_into_bytes!(u16);
impl_into_bytes!(i16);
impl_into_bytes!(u32);
impl_into_bytes!(i32);
impl_into_bytes!(u64);
impl_into_bytes!(i64);
impl_into_bytes!(u128);
impl_into_bytes!(i128);
impl_into_bytes!(usize);
impl_into_bytes!(isize);
impl_into_bytes!(f32);
impl_into_bytes!(f64);
impl Buffer for Bytes {
fn size(&self) -> usize {
self.0.len()
}
fn into_bytes(self) -> Vec<u8> {
self.0
}
fn as_bytes(&self) -> &[u8] {
&self.0
}
fn as_str(&self) -> Result<&str, Utf8Error> {
std::str::from_utf8(&self.0)
}
}