bsn1/buffer/
mod.rs

1// Copyright 2021-2024 Shin Yoshida
2//
3// "GPL-3.0-only"
4//
5// This is part of BSN1
6//
7// BSN1 is free software: you can redistribute it and/or modify it under the terms of the
8// GNU General Public License as published by the Free Software Foundation, version 3.
9//
10// BSN1 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
11// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12// General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License along with this program. If
15// not, see <https://www.gnu.org/licenses/>.
16
17#[cfg(target_endian = "little")]
18mod little_endian;
19#[cfg(target_endian = "little")]
20use little_endian as endian;
21
22#[cfg(any(target_endian = "big"))]
23mod universal_endian;
24#[cfg(any(target_endian = "big"))]
25use universal_endian as endian;
26
27type Inner = endian::Buffer;
28
29#[cfg(test)]
30mod tests;
31
32use std::borrow::Borrow;
33use std::cmp::Ordering;
34use std::fmt;
35use std::hash::{Hash, Hasher};
36use std::io::Write;
37use std::ops::{Deref, DerefMut, Index, IndexMut};
38
39#[doc(hidden)]
40#[derive(Clone)]
41pub struct Buffer(Inner);
42
43impl From<&[u8]> for Buffer {
44    fn from(slice: &[u8]) -> Self {
45        let mut buf = Self::with_capacity(slice.len());
46        unsafe { buf.extend_from_slice(slice) };
47        buf
48    }
49}
50
51impl<const N: usize> From<&[u8; N]> for Buffer {
52    fn from(slice: &[u8; N]) -> Self {
53        Self::from(&slice[..])
54    }
55}
56
57impl From<Vec<u8>> for Buffer {
58    fn from(vec: Vec<u8>) -> Self {
59        Self::from_vec(vec)
60    }
61}
62
63impl Buffer {
64    pub const fn new() -> Self {
65        Self(Inner::new())
66    }
67
68    pub fn with_capacity(cap: usize) -> Self {
69        Self(Inner::with_capacity(cap))
70    }
71
72    fn from_vec(vals: Vec<u8>) -> Self {
73        Self(Inner::from_vec(vals))
74    }
75
76    /// # Safety
77    ///
78    /// The behaviour is undefined if the length will exceeds the capacity.
79    pub unsafe fn push(&mut self, v: u8) {
80        self.0.push(v);
81    }
82
83    /// # Safety
84    ///
85    /// The behaviour is undefined if the length will exceeds the capacity.
86    pub unsafe fn extend_from_slice(&mut self, vals: &[u8]) {
87        self.0.extend_from_slice(vals);
88    }
89
90    pub const fn len(&self) -> usize {
91        self.0.len()
92    }
93
94    pub fn capacity(&self) -> usize {
95        self.0.capacity()
96    }
97
98    pub fn reserve(&mut self, additional: usize) {
99        self.0.reserve(additional);
100    }
101
102    pub unsafe fn set_len(&mut self, len: usize) {
103        debug_assert!(len <= self.capacity());
104        self.0.set_len(len);
105    }
106
107    pub fn as_ptr(&self) -> *const u8 {
108        self.0.as_ptr()
109    }
110
111    pub fn as_mut_ptr(&mut self) -> *mut u8 {
112        self.0.as_mut_ptr()
113    }
114
115    pub fn as_slice(&self) -> &[u8] {
116        self.0.as_slice()
117    }
118
119    pub fn as_mut_slice(&mut self) -> &mut [u8] {
120        self.0.as_mut_slice()
121    }
122
123    pub fn into_vec(self) -> Vec<u8> {
124        self.0.into_vec()
125    }
126}
127
128impl Borrow<[u8]> for Buffer {
129    fn borrow(&self) -> &[u8] {
130        self.as_slice()
131    }
132}
133
134impl fmt::Debug for Buffer {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        let contents = self.as_slice();
137        f.debug_tuple("Buffer").field(&contents).finish()
138    }
139}
140
141impl Deref for Buffer {
142    type Target = [u8];
143
144    fn deref(&self) -> &Self::Target {
145        self.as_slice()
146    }
147}
148
149impl DerefMut for Buffer {
150    fn deref_mut(&mut self) -> &mut Self::Target {
151        self.as_mut_slice()
152    }
153}
154
155impl Hash for Buffer {
156    fn hash<H: Hasher>(&self, state: &mut H) {
157        self.as_slice().hash(state);
158    }
159}
160
161impl Index<usize> for Buffer {
162    type Output = u8;
163
164    fn index(&self, index: usize) -> &Self::Output {
165        &self.as_slice()[index]
166    }
167}
168
169impl IndexMut<usize> for Buffer {
170    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
171        &mut self.as_mut_slice()[index]
172    }
173}
174
175impl<T> PartialEq<T> for Buffer
176where
177    T: Borrow<[u8]>,
178{
179    fn eq(&self, other: &T) -> bool {
180        self.as_slice() == other.borrow()
181    }
182}
183
184impl Eq for Buffer {}
185
186impl<T> PartialOrd<T> for Buffer
187where
188    T: Borrow<[u8]>,
189{
190    fn partial_cmp(&self, other: &T) -> Option<Ordering> {
191        self.as_slice().partial_cmp(other.borrow())
192    }
193}
194
195impl Ord for Buffer {
196    fn cmp(&self, other: &Self) -> Ordering {
197        self.as_slice().cmp(other.as_slice())
198    }
199}
200
201impl Write for Buffer {
202    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
203        self.reserve(buf.len());
204        unsafe { self.extend_from_slice(buf) };
205        Ok(buf.len())
206    }
207
208    fn flush(&mut self) -> std::io::Result<()> {
209        Ok(())
210    }
211}