const_hex/buffer.rs
1use crate::{byte2hex, imp};
2use core::fmt;
3use core::slice;
4use core::str;
5
6#[cfg(feature = "alloc")]
7#[allow(unused_imports)]
8use alloc::{string::String, vec::Vec};
9
10/// A correctly sized stack allocation for the formatted bytes to be written
11/// into.
12///
13/// `N` is the amount of bytes of the input, while `PREFIX` specifies whether
14/// the "0x" prefix is prepended to the output.
15///
16/// Note that this buffer will contain only the prefix, if specified, and null
17/// ('\0') bytes before any formatting is done.
18///
19/// # Examples
20///
21/// ```
22/// let mut buffer = const_hex::Buffer::<4>::new();
23/// let printed = buffer.format(b"1234");
24/// assert_eq!(printed, "31323334");
25/// ```
26#[must_use]
27#[repr(C)]
28#[derive(Clone)]
29pub struct Buffer<const N: usize, const PREFIX: bool = false> {
30 // Workaround for Rust issue #76560:
31 // https://github.com/rust-lang/rust/issues/76560
32 // This would ideally be `[u8; (N + PREFIX as usize) * 2]`
33 prefix: [u8; 2],
34 bytes: [[u8; 2]; N],
35}
36
37impl<const N: usize, const PREFIX: bool> Default for Buffer<N, PREFIX> {
38 #[inline]
39 fn default() -> Self {
40 Self::new()
41 }
42}
43
44impl<const N: usize, const PREFIX: bool> fmt::Debug for Buffer<N, PREFIX> {
45 #[inline]
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.debug_tuple("Buffer").field(&self.as_str()).finish()
48 }
49}
50
51impl<const N: usize, const PREFIX: bool> Buffer<N, PREFIX> {
52 /// The length of the buffer in bytes.
53 pub const LEN: usize = (N + PREFIX as usize) * 2;
54
55 const ASSERT_SIZE: () = assert!(core::mem::size_of::<Self>() == 2 + N * 2, "invalid size");
56 const ASSERT_ALIGNMENT: () = assert!(core::mem::align_of::<Self>() == 1, "invalid alignment");
57
58 /// This is a cheap operation; you don't need to worry about reusing buffers
59 /// for efficiency.
60 #[inline]
61 pub const fn new() -> Self {
62 let () = Self::ASSERT_SIZE;
63 let () = Self::ASSERT_ALIGNMENT;
64 Self {
65 prefix: if PREFIX { [b'0', b'x'] } else { [0, 0] },
66 bytes: [[0; 2]; N],
67 }
68 }
69
70 /// Print an array of bytes into this buffer.
71 #[inline]
72 pub const fn const_format(self, array: &[u8; N]) -> Self {
73 self.const_format_inner::<false>(array)
74 }
75
76 /// Print an array of bytes into this buffer.
77 #[inline]
78 pub const fn const_format_upper(self, array: &[u8; N]) -> Self {
79 self.const_format_inner::<true>(array)
80 }
81
82 /// Same as `encode_to_slice_inner`, but const-stable.
83 const fn const_format_inner<const UPPER: bool>(mut self, array: &[u8; N]) -> Self {
84 let mut i = 0;
85 while i < N {
86 let (high, low) = byte2hex::<UPPER>(array[i]);
87 self.bytes[i][0] = high;
88 self.bytes[i][1] = low;
89 i += 1;
90 }
91 self
92 }
93
94 /// Print an array of bytes into this buffer and return a reference to its
95 /// *lower* hex string representation within the buffer.
96 #[inline]
97 pub fn format(&mut self, array: &[u8; N]) -> &mut str {
98 // length of array is guaranteed to be N.
99 self.format_inner::<false>(array)
100 }
101
102 /// Print an array of bytes into this buffer and return a reference to its
103 /// *upper* hex string representation within the buffer.
104 #[inline]
105 pub fn format_upper(&mut self, array: &[u8; N]) -> &mut str {
106 // length of array is guaranteed to be N.
107 self.format_inner::<true>(array)
108 }
109
110 /// Print a slice of bytes into this buffer and return a reference to its
111 /// *lower* hex string representation within the buffer.
112 ///
113 /// # Panics
114 ///
115 /// If the slice is not exactly `N` bytes long.
116 #[track_caller]
117 #[inline]
118 pub fn format_slice<T: AsRef<[u8]>>(&mut self, slice: T) -> &mut str {
119 self.format_slice_inner::<false>(slice.as_ref())
120 }
121
122 /// Print a slice of bytes into this buffer and return a reference to its
123 /// *upper* hex string representation within the buffer.
124 ///
125 /// # Panics
126 ///
127 /// If the slice is not exactly `N` bytes long.
128 #[track_caller]
129 #[inline]
130 pub fn format_slice_upper<T: AsRef<[u8]>>(&mut self, slice: T) -> &mut str {
131 self.format_slice_inner::<true>(slice.as_ref())
132 }
133
134 // Checks length
135 #[track_caller]
136 fn format_slice_inner<const UPPER: bool>(&mut self, slice: &[u8]) -> &mut str {
137 assert_eq!(slice.len(), N, "length mismatch");
138 self.format_inner::<UPPER>(slice)
139 }
140
141 // Doesn't check length
142 #[inline]
143 fn format_inner<const UPPER: bool>(&mut self, input: &[u8]) -> &mut str {
144 // SAFETY: Length was checked previously;
145 // we only write only ASCII bytes.
146 unsafe {
147 let buf = self.as_mut_bytes();
148 let output = buf.as_mut_ptr().add(PREFIX as usize * 2);
149 imp::encode::<UPPER>(input, output);
150 str::from_utf8_unchecked_mut(buf)
151 }
152 }
153
154 /// Copies `self` into a new owned `String`.
155 #[cfg(feature = "alloc")]
156 #[inline]
157 #[allow(clippy::inherent_to_string)] // this is intentional
158 pub fn to_string(&self) -> String {
159 // SAFETY: The buffer always contains valid UTF-8.
160 unsafe { String::from_utf8_unchecked(self.as_bytes().to_vec()) }
161 }
162
163 /// Returns a reference to the underlying bytes casted to a string slice.
164 #[inline]
165 pub const fn as_str(&self) -> &str {
166 // SAFETY: The buffer always contains valid UTF-8.
167 unsafe { str::from_utf8_unchecked(self.as_bytes()) }
168 }
169
170 /// Returns a mutable reference to the underlying bytes casted to a string
171 /// slice.
172 #[inline]
173 pub fn as_mut_str(&mut self) -> &mut str {
174 // SAFETY: The buffer always contains valid UTF-8.
175 unsafe { str::from_utf8_unchecked_mut(self.as_mut_bytes()) }
176 }
177
178 /// Copies `self` into a new `Vec`.
179 #[cfg(feature = "alloc")]
180 #[inline]
181 pub fn to_vec(&self) -> Vec<u8> {
182 self.as_bytes().to_vec()
183 }
184
185 /// Returns a reference the underlying stack-allocated byte array.
186 ///
187 /// # Panics
188 ///
189 /// If `LEN` does not equal `Self::LEN`.
190 ///
191 /// This is panic is evaluated at compile-time if the `nightly` feature
192 /// is enabled, as inline `const` blocks are currently unstable.
193 ///
194 /// See Rust tracking issue [#76001](https://github.com/rust-lang/rust/issues/76001).
195 #[inline]
196 pub const fn as_byte_array<const LEN: usize>(&self) -> &[u8; LEN] {
197 maybe_const_assert!(LEN == Self::LEN, "`LEN` must be equal to `Self::LEN`");
198 // SAFETY: [u16; N] is layout-compatible with [u8; N * 2].
199 unsafe { &*self.as_ptr().cast::<[u8; LEN]>() }
200 }
201
202 /// Returns a mutable reference the underlying stack-allocated byte array.
203 ///
204 /// # Panics
205 ///
206 /// If `LEN` does not equal `Self::LEN`.
207 ///
208 /// See [`as_byte_array`](Buffer::as_byte_array) for more information.
209 #[inline]
210 pub fn as_mut_byte_array<const LEN: usize>(&mut self) -> &mut [u8; LEN] {
211 maybe_const_assert!(LEN == Self::LEN, "`LEN` must be equal to `Self::LEN`");
212 // SAFETY: [u16; N] is layout-compatible with [u8; N * 2].
213 unsafe { &mut *self.as_mut_ptr().cast::<[u8; LEN]>() }
214 }
215
216 /// Returns a reference to the underlying bytes.
217 #[inline]
218 pub const fn as_bytes(&self) -> &[u8] {
219 // SAFETY: [u16; N] is layout-compatible with [u8; N * 2].
220 unsafe { slice::from_raw_parts(self.as_ptr(), Self::LEN) }
221 }
222
223 /// Returns a mutable reference to the underlying bytes.
224 ///
225 /// # Safety
226 ///
227 /// The caller must ensure that the content of the slice is valid UTF-8
228 /// before the borrow ends and the underlying `str` is used.
229 ///
230 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
231 #[inline]
232 pub unsafe fn as_mut_bytes(&mut self) -> &mut [u8] {
233 // SAFETY: [u16; N] is layout-compatible with [u8; N * 2].
234 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), Self::LEN) }
235 }
236
237 /// Returns a mutable reference to the underlying buffer, excluding the prefix.
238 ///
239 /// # Safety
240 ///
241 /// See [`as_mut_bytes`](Buffer::as_mut_bytes).
242 #[inline]
243 pub unsafe fn buffer(&mut self) -> &mut [u8] {
244 unsafe { slice::from_raw_parts_mut(self.bytes.as_mut_ptr().cast(), N * 2) }
245 }
246
247 /// Returns a raw pointer to the buffer.
248 ///
249 /// The caller must ensure that the buffer outlives the pointer this
250 /// function returns, or else it will end up pointing to garbage.
251 #[inline]
252 pub const fn as_ptr(&self) -> *const u8 {
253 unsafe { (self as *const Self).cast::<u8>().add(!PREFIX as usize * 2) }
254 }
255
256 /// Returns an unsafe mutable pointer to the slice's buffer.
257 ///
258 /// The caller must ensure that the slice outlives the pointer this
259 /// function returns, or else it will end up pointing to garbage.
260 #[inline]
261 pub fn as_mut_ptr(&mut self) -> *mut u8 {
262 unsafe { (self as *mut Self).cast::<u8>().add(!PREFIX as usize * 2) }
263 }
264}