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
use crate::BytesMut;
#[derive(Default)]
pub struct Writer {
writer: BytesMut,
}
impl Writer {
#[inline]
pub fn write<B: ToBytes>(&mut self, bytes: B) {
self.writer.extend_from_slice(bytes.to_bytes());
}
pub fn take(&mut self) -> BytesMut {
self.writer.split_to(self.writer.len())
}
pub fn pos(&self) -> usize {
self.writer.len()
}
pub fn get_slice(&self, start_pos: usize, end_pos: usize) -> &[u8] {
&self.writer[start_pos..end_pos]
}
}
pub trait ToBytes {
fn to_bytes(&self) -> &[u8];
}
impl ToBytes for &str {
fn to_bytes(&self) -> &[u8] {
self.as_bytes()
}
}
impl ToBytes for &String {
fn to_bytes(&self) -> &[u8] {
self.as_bytes()
}
}
impl ToBytes for &[u8] {
fn to_bytes(&self) -> &[u8] {
self
}
}
impl ToBytes for BytesMut {
fn to_bytes(&self) -> &[u8] {
self.as_ref()
}
}
impl std::fmt::Write for Writer {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.write(s.as_bytes());
Ok(())
}
fn write_char(&mut self, c: char) -> std::fmt::Result {
let mut chars = [0u8; 4];
let s = c.encode_utf8(&mut chars);
self.write(s.as_bytes());
Ok(())
}
}
impl<const N: usize> ToBytes for &[u8; N] {
fn to_bytes(&self) -> &[u8] {
*self
}
}