hadris-fixed 2.0.0

Fixed-capacity byte and text types for no-std applications
Documentation
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Fixed-capacity byte and text types for `no_std` applications.

#![no_std]
#![deny(missing_docs)]

#[cfg(any(feature = "alloc", test))]
extern crate alloc;

use core::fmt;
use core::marker::PhantomData;
use core::ops::Range;

/// The fixed-capacity buffer cannot hold the requested data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CapacityError;

impl fmt::Display for CapacityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("fixed-capacity buffer is full")
    }
}

impl core::error::Error for CapacityError {}

/// Stack-allocated arbitrary bytes with a fixed maximum capacity.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct FixedBytes<const N: usize> {
    data: [u8; N],
    len: usize,
}

impl<const N: usize> FixedBytes<N> {
    /// Creates an empty buffer.
    pub const fn new() -> Self {
        Self {
            data: [0; N],
            len: 0,
        }
    }

    /// Compatibility name for [`new`](Self::new).
    pub const fn empty() -> Self {
        Self::new()
    }

    /// Creates a zero-filled buffer with an initialized length.
    ///
    /// # Panics
    /// Panics when `size` exceeds the capacity.
    pub const fn with_size(size: usize) -> Self {
        assert!(size <= N);
        Self {
            data: [0; N],
            len: size,
        }
    }

    /// Returns the number of initialized bytes.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns whether the buffer contains no initialized bytes.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the maximum number of bytes the buffer can hold.
    pub const fn capacity(&self) -> usize {
        N
    }

    /// Returns the number of bytes that can still be appended.
    pub const fn remaining_capacity(&self) -> usize {
        N - self.len
    }

    /// Returns the initialized portion of the buffer.
    pub fn as_bytes(&self) -> &[u8] {
        &self.data[..self.len]
    }

    /// Returns the initialized portion of the buffer mutably.
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.data[..self.len]
    }

    /// Interprets the initialized bytes as UTF-8.
    pub fn try_as_str(&self) -> Result<&str, core::str::Utf8Error> {
        core::str::from_utf8(self.as_bytes())
    }

    /// Returns the initialized bytes as UTF-8.
    ///
    /// # Panics
    /// Panics if the buffer does not contain valid UTF-8.
    pub fn as_str(&self) -> &str {
        self.try_as_str()
            .expect("FixedBytes contains invalid UTF-8")
    }

    /// Removes all initialized bytes.
    pub fn clear(&mut self) {
        self.len = 0;
    }

    /// Shortens the initialized portion to `new_len`.
    ///
    /// # Panics
    /// Panics if `new_len` exceeds the current length.
    pub fn truncate(&mut self, new_len: usize) {
        assert!(new_len <= self.len);
        self.len = new_len;
    }

    /// Extends the initialized portion with zero-filled bytes.
    ///
    /// # Panics
    /// Panics if the requested bytes exceed the remaining capacity.
    pub fn allocate(&mut self, bytes: usize) {
        assert!(bytes <= self.remaining_capacity());
        self.len += bytes;
    }

    /// Copies a byte slice into a new buffer.
    pub fn try_from_slice(value: &[u8]) -> Result<Self, CapacityError> {
        let mut result = Self::new();
        result.try_push_slice(value)?;
        Ok(result)
    }

    /// Appends a slice and returns the occupied range.
    pub fn try_push_slice(&mut self, value: &[u8]) -> Result<Range<usize>, CapacityError> {
        if value.len() > self.remaining_capacity() {
            return Err(CapacityError);
        }
        let start = self.len;
        self.len += value.len();
        self.data[start..self.len].copy_from_slice(value);
        Ok(start..self.len)
    }

    /// Appends a slice and returns the occupied range.
    ///
    /// # Panics
    /// Panics if the slice exceeds the remaining capacity.
    pub fn push_slice(&mut self, value: &[u8]) -> Range<usize> {
        self.try_push_slice(value)
            .expect("FixedBytes capacity exceeded")
    }

    /// Appends one byte and returns its index.
    pub fn try_push_byte(&mut self, value: u8) -> Result<usize, CapacityError> {
        if self.len == N {
            return Err(CapacityError);
        }
        let index = self.len;
        self.data[index] = value;
        self.len += 1;
        Ok(index)
    }

    /// Appends one byte and returns its index.
    ///
    /// # Panics
    /// Panics if the buffer is full.
    pub fn push_byte(&mut self, value: u8) -> usize {
        self.try_push_byte(value)
            .expect("FixedBytes capacity exceeded")
    }
}

impl<const N: usize> Default for FixedBytes<N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const N: usize> From<&[u8]> for FixedBytes<N> {
    fn from(value: &[u8]) -> Self {
        Self::try_from_slice(value).expect("FixedBytes capacity exceeded")
    }
}

impl<const N: usize> From<&[u8; N]> for FixedBytes<N> {
    fn from(value: &[u8; N]) -> Self {
        Self {
            data: *value,
            len: N,
        }
    }
}

impl<const N: usize> fmt::Debug for FixedBytes<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("FixedBytes").field(&self.as_bytes()).finish()
    }
}

impl<const N: usize> fmt::Display for FixedBytes<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.try_as_str() {
            Ok(value) => f.write_str(value),
            Err(_) => write!(f, "{:?}", self.as_bytes()),
        }
    }
}

/// Stack-allocated, valid UTF-8 text with a fixed byte capacity.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct FixedStr<const N: usize>(FixedBytes<N>);

impl<const N: usize> FixedStr<N> {
    /// Creates an empty string.
    pub const fn new() -> Self {
        Self(FixedBytes::new())
    }

    /// Returns the UTF-8 byte length.
    pub const fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the string is empty.
    pub const fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the maximum UTF-8 byte capacity.
    pub const fn capacity(&self) -> usize {
        N
    }

    /// Returns the remaining UTF-8 byte capacity.
    pub const fn remaining_capacity(&self) -> usize {
        self.0.remaining_capacity()
    }

    /// Returns the contents as a string slice.
    pub fn as_str(&self) -> &str {
        // Construction and mutation accept only valid UTF-8.
        unsafe { core::str::from_utf8_unchecked(self.0.as_bytes()) }
    }

    /// Returns the UTF-8 bytes.
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Removes all text.
    pub fn clear(&mut self) {
        self.0.clear();
    }

    /// Appends text and returns its byte range.
    pub fn try_push_str(&mut self, value: &str) -> Result<Range<usize>, CapacityError> {
        self.0.try_push_slice(value.as_bytes())
    }

    /// Appends text and returns its byte range.
    ///
    /// # Panics
    /// Panics if the text exceeds the remaining capacity.
    pub fn push_str(&mut self, value: &str) -> Range<usize> {
        self.try_push_str(value)
            .expect("FixedStr capacity exceeded")
    }

    /// Appends one Unicode scalar and returns its UTF-8 byte range.
    pub fn try_push(&mut self, value: char) -> Result<Range<usize>, CapacityError> {
        let mut bytes = [0; 4];
        self.try_push_str(value.encode_utf8(&mut bytes))
    }

    /// Shortens the string to `new_len` UTF-8 bytes.
    ///
    /// # Panics
    /// Panics unless `new_len` is a character boundary within the string.
    pub fn truncate(&mut self, new_len: usize) {
        assert!(self.as_str().is_char_boundary(new_len));
        self.0.truncate(new_len);
    }

    /// Converts the string into its fixed byte buffer.
    pub const fn into_bytes(self) -> FixedBytes<N> {
        self.0
    }
}

impl<const N: usize> Default for FixedStr<N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const N: usize> TryFrom<&str> for FixedStr<N> {
    type Error = CapacityError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Ok(Self(FixedBytes::try_from_slice(value.as_bytes())?))
    }
}

impl<const N: usize> TryFrom<FixedBytes<N>> for FixedStr<N> {
    type Error = core::str::Utf8Error;

    fn try_from(value: FixedBytes<N>) -> Result<Self, Self::Error> {
        value.try_as_str()?;
        Ok(Self(value))
    }
}

impl<const N: usize> fmt::Debug for FixedStr<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("FixedStr").field(&self.as_str()).finish()
    }
}

impl<const N: usize> fmt::Display for FixedStr<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// UTF-16 byte order used by [`FixedUtf16`].
pub trait Utf16ByteOrder: Copy {
    /// Decodes one code unit from its on-disk byte order.
    fn read(bytes: [u8; 2]) -> u16;
    /// Encodes one code unit into its on-disk byte order.
    fn write(value: u16) -> [u8; 2];
}

/// Little-endian UTF-16 code-unit encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LittleEndian;

/// Big-endian UTF-16 code-unit encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BigEndian;

impl Utf16ByteOrder for LittleEndian {
    fn read(bytes: [u8; 2]) -> u16 {
        u16::from_le_bytes(bytes)
    }
    fn write(value: u16) -> [u8; 2] {
        value.to_le_bytes()
    }
}

impl Utf16ByteOrder for BigEndian {
    fn read(bytes: [u8; 2]) -> u16 {
        u16::from_be_bytes(bytes)
    }
    fn write(value: u16) -> [u8; 2] {
        value.to_be_bytes()
    }
}

/// Fixed-width, NUL-padded UTF-16 code units in a specified byte order.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FixedUtf16<const N: usize, E: Utf16ByteOrder> {
    data: [[u8; 2]; N],
    byte_order: PhantomData<E>,
}

/// Fixed-width little-endian UTF-16 text.
pub type FixedUtf16Le<const N: usize> = FixedUtf16<N, LittleEndian>;
/// Fixed-width big-endian UTF-16 text.
pub type FixedUtf16Be<const N: usize> = FixedUtf16<N, BigEndian>;

impl<const N: usize, E: Utf16ByteOrder> FixedUtf16<N, E> {
    /// Creates a NUL-filled value.
    pub const fn new() -> Self {
        Self {
            data: [[0; 2]; N],
            byte_order: PhantomData,
        }
    }

    /// Encodes a string into fixed-width UTF-16.
    pub fn try_from_str(value: &str) -> Result<Self, CapacityError> {
        let mut result = Self::new();
        for (index, unit) in value.encode_utf16().enumerate() {
            if index == N {
                return Err(CapacityError);
            }
            result.data[index] = E::write(unit);
        }
        Ok(result)
    }

    /// Returns all encoded code-unit bytes, including NUL padding.
    pub fn as_bytes(&self) -> &[[u8; 2]; N] {
        &self.data
    }

    /// Decodes code units up to the first NUL.
    pub fn decode(&self) -> impl Iterator<Item = Result<char, core::char::DecodeUtf16Error>> + '_ {
        char::decode_utf16(
            self.data
                .iter()
                .map(|bytes| E::read(*bytes))
                .take_while(|unit| *unit != 0),
        )
    }

    #[cfg(feature = "alloc")]
    /// Decodes the value into an allocated UTF-8 string.
    pub fn to_string(&self) -> Result<alloc::string::String, core::char::DecodeUtf16Error> {
        self.decode().collect()
    }
}

impl<const N: usize, E: Utf16ByteOrder> Default for FixedUtf16<N, E> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "bytemuck")]
unsafe impl<const N: usize, E: Utf16ByteOrder + 'static> bytemuck::Zeroable for FixedUtf16<N, E> {}
#[cfg(feature = "bytemuck")]
unsafe impl<const N: usize, E: Utf16ByteOrder + 'static> bytemuck::Pod for FixedUtf16<N, E> {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bytes_allow_non_utf8() {
        let bytes = FixedBytes::<2>::try_from_slice([0xff, 0].as_slice()).unwrap();
        assert!(bytes.try_as_str().is_err());
    }

    #[test]
    fn fixed_str_preserves_utf8() {
        let mut text = FixedStr::<8>::try_from("é").unwrap();
        text.try_push('!').unwrap();
        assert_eq!(text.as_str(), "é!");
    }

    #[test]
    fn utf16_round_trips_both_orders() {
        let le = FixedUtf16Le::<8>::try_from_str("A😀").unwrap();
        let be = FixedUtf16Be::<8>::try_from_str("A😀").unwrap();
        assert_eq!(le.to_string().unwrap(), "A😀");
        assert_eq!(be.to_string().unwrap(), "A😀");
    }
}