1 | #[cfg (feature = "std" )] |
2 | use std::io::Write; |
3 | |
4 | use crate::error::Result; |
5 | |
6 | #[inline (always)] |
7 | #[cold ] |
8 | pub const fn cold() {} |
9 | |
10 | #[inline (always)] |
11 | #[allow (unused)] |
12 | pub const fn likely(b: bool) -> bool { |
13 | if !b { |
14 | cold(); |
15 | } |
16 | b |
17 | } |
18 | |
19 | #[inline (always)] |
20 | pub const fn unlikely(b: bool) -> bool { |
21 | if b { |
22 | cold(); |
23 | } |
24 | b |
25 | } |
26 | |
27 | pub trait Writer: Sized { |
28 | fn write_one(self, v: u8) -> Result<Self>; |
29 | fn write_many(self, v: &[u8]) -> Result<Self>; |
30 | fn capacity(&self) -> usize; |
31 | } |
32 | |
33 | pub struct BytesMut<'a>(&'a mut [u8]); |
34 | |
35 | impl<'a> BytesMut<'a> { |
36 | pub fn new(buf: &'a mut [u8]) -> Self { |
37 | Self(buf) |
38 | } |
39 | |
40 | #[inline ] |
41 | pub fn write_one(self, v: u8) -> Self { |
42 | if let Some((first, tail)) = self.0.split_first_mut() { |
43 | *first = v; |
44 | Self(tail) |
45 | } else { |
46 | unreachable!() |
47 | } |
48 | } |
49 | |
50 | #[inline ] |
51 | pub fn write_many(self, v: &[u8]) -> Self { |
52 | if v.len() <= self.0.len() { |
53 | let (head, tail) = self.0.split_at_mut(v.len()); |
54 | head.copy_from_slice(v); |
55 | Self(tail) |
56 | } else { |
57 | unreachable!() |
58 | } |
59 | } |
60 | } |
61 | |
62 | impl<'a> Writer for BytesMut<'a> { |
63 | #[inline ] |
64 | fn write_one(self, v: u8) -> Result<Self> { |
65 | Ok(BytesMut::write_one(self, v)) |
66 | } |
67 | |
68 | #[inline ] |
69 | fn write_many(self, v: &[u8]) -> Result<Self> { |
70 | Ok(BytesMut::write_many(self, v)) |
71 | } |
72 | |
73 | #[inline ] |
74 | fn capacity(&self) -> usize { |
75 | self.0.len() |
76 | } |
77 | } |
78 | |
79 | #[cfg (feature = "std" )] |
80 | pub struct GenericWriter<W> { |
81 | writer: W, |
82 | n_written: usize, |
83 | } |
84 | |
85 | #[cfg (feature = "std" )] |
86 | impl<W: Write> GenericWriter<W> { |
87 | pub const fn new(writer: W) -> Self { |
88 | Self { writer, n_written: 0 } |
89 | } |
90 | } |
91 | |
92 | #[cfg (feature = "std" )] |
93 | impl<W: Write> Writer for GenericWriter<W> { |
94 | fn write_one(mut self, v: u8) -> Result<Self> { |
95 | self.n_written += 1; |
96 | self.writer.write_all(&[v]).map(|_| self).map_err(op:Into::into) |
97 | } |
98 | |
99 | fn write_many(mut self, v: &[u8]) -> Result<Self> { |
100 | self.n_written += v.len(); |
101 | self.writer.write_all(v).map(|_| self).map_err(op:Into::into) |
102 | } |
103 | |
104 | fn capacity(&self) -> usize { |
105 | usize::MAX - self.n_written |
106 | } |
107 | } |
108 | |