heapless_bytes/
lib.rs

1//! # heapless-bytes
2//!
3//! Newtype around heapless byte Vec with efficient serde.
4
5#![cfg_attr(not(test), no_std)]
6#![allow(clippy::result_unit_err)]
7
8#[cfg(feature = "bytes")]
9mod bytes_traits;
10
11use core::{
12    cmp::Ordering,
13    fmt::{self, Debug},
14    hash::{Hash, Hasher},
15    marker::PhantomData,
16    ops::{Deref, DerefMut},
17};
18
19use heapless::{
20    vec::{OwnedVecStorage, Vec, VecInner, ViewVecStorage},
21    CapacityError, LenType,
22};
23
24use serde_core::{
25    de::{Deserialize, Deserializer, Visitor},
26    ser::{Serialize, Serializer},
27};
28pub use storage::BytesStorage;
29
30mod storage {
31    use super::{BytesInner, BytesView};
32    use heapless::{
33        vec::{OwnedVecStorage, VecStorage, ViewVecStorage},
34        LenType,
35    };
36
37    /// Trait defining how data for a Byte buffer is stored.
38    ///
39    /// There's two implementations available:
40    ///
41    /// - [`OwnedVecStorage`]: stores the data in an array whose size is known at compile time.
42    /// - [`ViewVecStorage`]: stores the data in an unsized slice
43    ///
44    /// This allows [`BytesInner`] to be generic over either sized or unsized storage. The [`heapless-bytes`](crate)
45    /// crate contains a [`BytesInner`] struct that's generic on [`BytesStorage`],
46    /// and two type aliases for convenience:
47    ///
48    /// - [`Bytes<N>`](crate::Bytes) = `BytesInner<OwnedVecStorage<u8, N>>`
49    /// - [`BytesView<T>`](crate::BytesView) = `BytesInner<ViewVecStorage<u8>>`
50    ///
51    /// `Bytes` can be unsized into `StrinsgView`, either by unsizing coercions such as `&mut Bytes -> &mut BytesView` or
52    /// `Box<Bytes> -> Box<BytesView>`, or explicitly with [`.as_view()`](crate::Bytes::as_view) or [`.as_mut_view()`](crate::Bytes::as_mut_view).
53    ///
54    /// This trait is sealed, so you cannot implement it for your own types. You can only use
55    /// the implementations provided by this crate.
56    ///
57    /// [`OwnedVecStorage`]: heapless::vec::OwnedVecStorage
58    /// [`ViewVecStorage`]: heapless::vec::ViewVecStorage
59    pub trait BytesStorage: BytesStorageSealed {}
60    pub trait BytesStorageSealed: VecStorage<u8> {
61        fn as_byte_view<LenT: LenType>(this: &BytesInner<LenT, Self>) -> &BytesView<LenT>
62        where
63            Self: BytesStorage;
64        fn as_byte_mut_view<LenT: LenType>(
65            this: &mut BytesInner<LenT, Self>,
66        ) -> &mut BytesView<LenT>
67        where
68            Self: BytesStorage;
69    }
70
71    impl<const N: usize> BytesStorage for OwnedVecStorage<u8, N> {}
72    impl<const N: usize> BytesStorageSealed for OwnedVecStorage<u8, N> {
73        fn as_byte_view<LenT: LenType>(this: &BytesInner<LenT, Self>) -> &BytesView<LenT>
74        where
75            Self: BytesStorage,
76        {
77            this
78        }
79        fn as_byte_mut_view<LenT: LenType>(
80            this: &mut BytesInner<LenT, Self>,
81        ) -> &mut BytesView<LenT>
82        where
83            Self: BytesStorage,
84        {
85            this
86        }
87    }
88
89    impl BytesStorage for ViewVecStorage<u8> {}
90
91    impl BytesStorageSealed for ViewVecStorage<u8> {
92        fn as_byte_view<LenT: LenType>(this: &BytesInner<LenT, Self>) -> &BytesView<LenT>
93        where
94            Self: BytesStorage,
95        {
96            this
97        }
98        fn as_byte_mut_view<LenT: LenType>(
99            this: &mut BytesInner<LenT, Self>,
100        ) -> &mut BytesView<LenT>
101        where
102            Self: BytesStorage,
103        {
104            this
105        }
106    }
107}
108
109pub type OwnedBytesStorage<const N: usize> = OwnedVecStorage<u8, N>;
110pub type ViewBytesStorage = ViewVecStorage<u8>;
111
112pub struct BytesInner<LenT: LenType, S: BytesStorage + ?Sized> {
113    bytes: VecInner<u8, LenT, S>,
114}
115
116pub type Bytes<const N: usize, LenT = usize> = BytesInner<LenT, OwnedBytesStorage<N>>;
117pub type BytesView<LenT = usize> = BytesInner<LenT, ViewBytesStorage>;
118
119pub type Bytes8<LenT = usize> = Bytes<8, LenT>;
120pub type Bytes16<LenT = usize> = Bytes<16, LenT>;
121pub type Bytes32<LenT = usize> = Bytes<32, LenT>;
122pub type Bytes64<LenT = usize> = Bytes<64, LenT>;
123
124impl<const N: usize, LenT: LenType> Clone for Bytes<N, LenT> {
125    fn clone(&self) -> Self {
126        Self {
127            bytes: self.bytes.clone(),
128        }
129    }
130}
131
132impl<S: BytesStorage + ?Sized, LenT: LenType> Eq for BytesInner<LenT, S> {}
133impl<S: BytesStorage + ?Sized, LenT: LenType> Ord for BytesInner<LenT, S> {
134    fn cmp(&self, other: &Self) -> Ordering {
135        self.bytes.cmp(&other.bytes)
136    }
137}
138
139#[cfg(feature = "heapless-0.9")]
140impl<const N: usize, LenT: LenType> From<Vec<u8, N, LenT>> for Bytes<N, LenT> {
141    fn from(vec: Vec<u8, N, LenT>) -> Self {
142        Bytes { bytes: vec }
143    }
144}
145
146#[cfg(feature = "heapless-0.9")]
147impl<const N: usize, LenT: LenType> From<Bytes<N, LenT>> for Vec<u8, N, LenT> {
148    fn from(value: Bytes<N, LenT>) -> Self {
149        value.bytes
150    }
151}
152
153impl<const N: usize, LenT: LenType> TryFrom<&[u8]> for Bytes<N, LenT> {
154    type Error = CapacityError;
155    fn try_from(value: &[u8]) -> Result<Self, CapacityError> {
156        Ok(Self {
157            bytes: Vec::from_slice(value)?,
158        })
159    }
160}
161
162impl<const N: usize, LenT: LenType> Default for Bytes<N, LenT> {
163    fn default() -> Self {
164        Self::new()
165    }
166}
167
168impl<const N: usize, LenT: LenType> Bytes<N, LenT> {
169    /// Construct a new, empty `Bytes<N>`.
170    pub const fn new() -> Self {
171        Self { bytes: Vec::new() }
172    }
173    /// Get the capacity of the buffer.
174    ///
175    /// Always equal to the `N` const generic.
176    pub const fn const_capacity(&self) -> usize {
177        N
178    }
179
180    /// Copy the contents of this `Bytes` instance into a new instance with a higher capacity.
181    ///
182    /// ```
183    /// # use heapless_bytes::Bytes;
184    /// let bytes32: Bytes<32> = Bytes::from([0; 32]);
185    /// let bytes64: Bytes<64> = bytes32.increase_capacity();
186    /// assert_eq!(bytes64.len(), 32);
187    /// assert_eq!(bytes64.capacity(), 64);
188    /// ```
189    ///
190    /// Decreasing the capacity causes a compiler error:
191    /// ```compile_fail
192    /// # use heapless_bytes::Bytes;
193    /// let bytes32: Bytes<32> = Bytes::from([0; 32]);
194    /// let bytes16: Bytes<16> = bytes32.increase_capacity();
195    /// ```
196    pub fn increase_capacity<const M: usize>(&self) -> Bytes<M, LenT> {
197        let () = AssertLessThanEq::<N, M>::ASSERT;
198        let mut bytes = Vec::new();
199        // bytes has length 0 and capacity M, self has length N, N <= M, so this can never panic
200        bytes.extend_from_slice(self.as_slice()).unwrap();
201        Bytes { bytes }
202    }
203
204    pub fn cast_len_type<NewLenT: LenType>(self) -> Bytes<N, NewLenT> {
205        BytesInner {
206            bytes: self.bytes.cast_len_type(),
207        }
208    }
209}
210
211#[cfg(feature = "heapless-0.9")]
212impl<S: BytesStorage + ?Sized, LenT: LenType> AsMut<heapless::vec::VecInner<u8, LenT, S>>
213    for BytesInner<LenT, S>
214{
215    fn as_mut(&mut self) -> &mut heapless::vec::VecInner<u8, LenT, S> {
216        &mut self.bytes
217    }
218}
219
220impl<S: BytesStorage + ?Sized, LenT: LenType> BytesInner<LenT, S> {
221    /// Get a "view" to the Buffer with the `N` const generic erased
222    pub fn as_view(&self) -> &BytesView<LenT> {
223        S::as_byte_view(self)
224    }
225
226    /// Get a mutable "view" to the Buffer with the `N` const generic erased
227    pub fn as_mut_view(&mut self) -> &mut BytesView<LenT> {
228        S::as_byte_mut_view(self)
229    }
230
231    pub fn as_ptr(&self) -> *const u8 {
232        self.bytes.as_ptr()
233    }
234
235    /// Returns a raw pointer to the vector’s buffer, which may be mutated through
236    pub fn as_mut_ptr(&mut self) -> *mut u8 {
237        self.bytes.as_mut_ptr()
238    }
239
240    /// Extracts a slice containing the entire buffer.
241    pub fn as_slice(&self) -> &[u8] {
242        self.bytes.as_slice()
243    }
244
245    /// Extracts a mutable slice containing the entire buffer.
246    pub fn as_mut_slice(&mut self) -> &mut [u8] {
247        self.bytes.as_mut_slice()
248    }
249
250    /// Get the capacity of the buffer.
251    ///
252    /// Always equal to the `N` const generic.
253    pub fn capacity(&self) -> usize {
254        self.bytes.capacity()
255    }
256
257    /// Clear the buffer, making it empty
258    pub fn clear(&mut self) {
259        self.bytes.clear()
260    }
261
262    /// Extends the buffer from an iterator.
263    ///
264    /// # Panic
265    ///
266    /// Panics if the buffer cannot hold all elements of the iterator.
267    #[deprecated(
268        since = "0.4.0",
269        note = "Panics when out of capacity, use try_extend instead"
270    )]
271    pub fn extend<I: IntoIterator<Item = u8>>(&mut self, iter: I) {
272        self.bytes.extend(iter)
273    }
274
275    /// Extends the buffer from an iterator.
276    ///
277    /// Returns [`Err`] if out of capacity
278    pub fn try_extend<I: IntoIterator<Item = u8>>(&mut self, iter: I) -> Result<(), ()> {
279        for b in iter {
280            self.push(b)?;
281        }
282        Ok(())
283    }
284
285    /// Extend the buffer with the contents of a slice
286    pub fn extend_from_slice(&mut self, other: &[u8]) -> Result<(), CapacityError> {
287        self.bytes.extend_from_slice(other)
288    }
289
290    /// Removes the last byte from the buffer and returns it, or `None` if it's empty
291    pub fn pop(&mut self) -> Option<u8> {
292        self.bytes.pop()
293    }
294
295    /// Appends a byte to the back of the collection
296    pub fn push(&mut self, byte: u8) -> Result<(), ()> {
297        self.bytes.push(byte).map_err(drop)
298    }
299
300    /// Removes the last byte from the buffer and returns it
301    ///
302    /// # Safety
303    ///
304    /// This assumes the buffer to have at least one element.
305    pub unsafe fn pop_unchecked(&mut self) -> u8 {
306        unsafe { self.bytes.pop_unchecked() }
307    }
308
309    /// Appends a byte to the back of the buffer
310    ///
311    /// # Safety
312    ///
313    /// This assumes the buffer is not full.
314    pub unsafe fn push_unchecked(&mut self, byte: u8) {
315        unsafe {
316            self.bytes.push_unchecked(byte);
317        }
318    }
319
320    /// Shortens the buffer, keeping the first `len` elements and dropping the rest.
321    pub fn truncate(&mut self, len: usize) {
322        self.bytes.truncate(len)
323    }
324
325    /// Resizes the buffer in-place so that len is equal to new_len.
326    ///
327    /// If new_len is greater than len, the buffer is extended by the
328    /// difference, with each additional slot filled with `value`. If
329    /// `new_len` is less than `len`, the buffer is simply truncated.
330    ///
331    /// See also [`resize_zero`](Self::resize_zero).
332    pub fn resize(&mut self, new_len: usize, value: u8) -> Result<(), CapacityError> {
333        self.bytes.resize(new_len, value)
334    }
335
336    /// Resizes the buffer in-place so that len is equal to new_len.
337    ///
338    /// If new_len is greater than len, the buffer is extended by the
339    /// difference, with each additional slot filled with `0`. If
340    /// `new_len` is less than `len`, the buffer is simply truncated.
341    pub fn resize_zero(&mut self, new_len: usize) -> Result<(), CapacityError> {
342        self.bytes.resize_default(new_len)
343    }
344
345    /// Forces the length of the buffer to `new_len`.
346    ///
347    /// This is a low-level operation that maintains none of the normal
348    /// invariants of the type. Normally changing the length of a buffer
349    /// is done using one of the safe operations instead, such as
350    /// [`truncate`], [`resize`], [`extend`], or [`clear`].
351    ///
352    /// [`truncate`]: Self::truncate
353    /// [`resize`]: Self::resize
354    /// [`extend`]: core::iter::Extend
355    /// [`clear`]: Self::clear
356    ///
357    /// # Safety
358    ///
359    /// - `new_len` must be less than or equal to [`capacity()`].
360    /// - The elements at `old_len..new_len` must be initialized.
361    ///
362    /// [`capacity()`]: Self::capacity
363    ///
364    pub unsafe fn set_len(&mut self, new_len: usize) {
365        self.bytes.set_len(new_len)
366    }
367
368    /// Removes a byte  from the buffer and returns it.
369    ///
370    /// The removed byte is replaced by the last byte of the vector.
371    ///
372    /// This does not preserve ordering, but is *O*(1).
373    ///
374    /// # Panics
375    ///
376    /// Panics if `index` is out of bounds.
377    pub fn swap_remove(&mut self, index: usize) -> u8 {
378        self.bytes.swap_remove(index)
379    }
380
381    /// Removes a byte  from the buffer and returns it.
382    ///
383    /// The removed byte is replaced by the last byte of the vector.
384    ///
385    /// This does not preserve ordering, but is *O*(1).
386    ///
387    /// # Safety
388    ///
389    /// `index` must not be out of bounds.
390    pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> u8 {
391        unsafe { self.bytes.swap_remove_unchecked(index) }
392    }
393
394    /// Returns true if the buffer is full
395    pub fn is_full(&self) -> bool {
396        self.bytes.is_full()
397    }
398
399    /// Returns true if the buffer is empty
400    pub fn is_empty(&self) -> bool {
401        self.bytes.is_empty()
402    }
403
404    /// Returns `true` if `needle` is a prefix of the buffer.
405    ///
406    /// Always returns `true` if `needle` is an empty slice.
407    pub fn starts_with(&self, needle: &[u8]) -> bool {
408        self.bytes.starts_with(needle)
409    }
410
411    /// Returns `true` if `needle` is a suffix of the buffer.
412    ///
413    /// Always returns `true` if `needle` is an empty slice.
414    pub fn ends_with(&self, needle: &[u8]) -> bool {
415        self.bytes.ends_with(needle)
416    }
417
418    /// Inserts a byte at position `index` within the buffer, shifting all
419    /// bytes after it to the right.
420    ///
421    /// # Panics
422    ///
423    /// Panics if `index > len`.
424    pub fn insert(&mut self, index: usize, value: u8) -> Result<(), ()> {
425        self.bytes.insert(index, value).map_err(drop)
426    }
427
428    /// Removes and return the byte at position `index` within the buffer, shifting all
429    /// bytes after it to the left.
430    ///
431    /// # Panics
432    ///
433    /// Panics if `index > len`.
434    pub fn remove(&mut self, index: usize) -> u8 {
435        self.bytes.remove(index)
436    }
437
438    /// Retains only the bytes specified by the predicate.
439    ///
440    /// In other words, remove all bytes `b` for which `f(&b)` returns `false`.
441    /// This method operates in place, visiting each element exactly once in the
442    /// original order, and preserves the order of the retained elements.
443    pub fn retain(&mut self, f: impl FnMut(&u8) -> bool) {
444        self.bytes.retain(f)
445    }
446    /// Retains only the bytes specified by the predicate, passing a mutable reference to it.
447    ///
448    /// In other words, remove all bytes `b` for which `f(&mut b)` returns `false`.
449    /// This method operates in place, visiting each element exactly once in the
450    /// original order, and preserves the order of the retained elements.
451    pub fn retain_mut(&mut self, f: impl FnMut(&mut u8) -> bool) {
452        self.bytes.retain_mut(f)
453    }
454
455    pub fn resize_to_capacity(&mut self) {
456        self.bytes.resize_default(self.bytes.capacity()).ok();
457    }
458
459    /// Low-noise conversion between lengths.
460    pub fn resize_capacity<const M: usize>(&self) -> Result<Bytes<M>, CapacityError> {
461        Bytes::try_from(&**self)
462    }
463}
464
465/// Construct a `Bytes<N>` instance from an array with `N` elements.
466///
467/// Currently, the array is copied, but a more efficient implementation could be used in the
468/// future.
469///
470/// ```
471/// # use heapless_bytes::Bytes;
472/// let bytes: Bytes<3> = Bytes::from([0, 1, 2]);
473/// ```
474///
475/// Length mismatches cause a compiler error:
476/// ```compile_fail
477/// # use heapless_bytes::Bytes;
478/// let bytes: Bytes<3> = Bytes::from([0, 1]);  // does not compile
479/// ```
480/// ```compile_fail
481/// # use heapless_bytes::Bytes;
482/// let bytes: Bytes<3> = Bytes::from([0, 1, 2, 3]);  // does not compile
483/// ```
484impl<const N: usize, LenT: LenType> From<[u8; N]> for Bytes<N, LenT> {
485    fn from(bytes: [u8; N]) -> Self {
486        Self::from(&bytes)
487    }
488}
489
490struct AssertLessThanEq<const I: usize, const J: usize>;
491
492impl<const I: usize, const J: usize> AssertLessThanEq<I, J> {
493    const ASSERT: () = assert!(I <= J, "Cannot convert infallibly between two arrays when the capacity of the new array is not sufficient");
494}
495
496/// Construct a `Bytes<N>` instance by copying from an array with `N` or less elements.
497///
498/// ```
499/// # use heapless_bytes::Bytes;
500/// let bytes: Bytes<3> = Bytes::from(&[0, 1, 2]);
501/// let shorter_bytes: Bytes<3> = Bytes::from(&[0, 1]);
502/// ```
503///
504/// Overlong input data causes a compiler error:
505/// ```compile_fail
506/// # use heapless_bytes::Bytes;
507/// let bytes: Bytes<3> = Bytes::from(&[0, 1, 2, 3]);  // does not compile
508/// ```
509impl<const N: usize, const M: usize, LenT: LenType> From<&[u8; M]> for Bytes<N, LenT> {
510    fn from(data: &[u8; M]) -> Self {
511        let () = AssertLessThanEq::<M, N>::ASSERT;
512        let mut bytes = Vec::new();
513        // vec has length 0 and capacity N, bytes has length M, M <= N, so this can never panic
514        bytes.extend_from_slice(data).unwrap();
515        Bytes { bytes }
516    }
517}
518
519impl<S: BytesStorage + ?Sized, LenT: LenType> Debug for BytesInner<LenT, S> {
520    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
521        // TODO: There has to be a better way :'-)
522
523        use core::ascii::escape_default;
524        f.write_str("b'")?;
525        for byte in &self.bytes {
526            write!(f, "{}", escape_default(*byte))?;
527        }
528        f.write_str("'")?;
529        Ok(())
530    }
531}
532
533impl<S: BytesStorage + ?Sized, LenT: LenType> AsRef<[u8]> for BytesInner<LenT, S> {
534    fn as_ref(&self) -> &[u8] {
535        &self.bytes
536    }
537}
538
539impl<S: BytesStorage + ?Sized, LenT: LenType> AsMut<[u8]> for BytesInner<LenT, S> {
540    fn as_mut(&mut self) -> &mut [u8] {
541        &mut self.bytes
542    }
543}
544
545impl<S: BytesStorage + ?Sized, LenT: LenType> Deref for BytesInner<LenT, S> {
546    type Target = [u8];
547
548    fn deref(&self) -> &Self::Target {
549        &self.bytes
550    }
551}
552
553impl<S: BytesStorage + ?Sized, LenT: LenType> DerefMut for BytesInner<LenT, S> {
554    fn deref_mut(&mut self) -> &mut Self::Target {
555        &mut self.bytes
556    }
557}
558
559impl<Rhs, S: BytesStorage + ?Sized, LenT: LenType> PartialEq<Rhs> for BytesInner<LenT, S>
560where
561    Rhs: ?Sized + AsRef<[u8]>,
562{
563    fn eq(&self, other: &Rhs) -> bool {
564        self.as_ref().eq(other.as_ref())
565    }
566}
567
568impl<Rhs, S: BytesStorage + ?Sized, LenT: LenType> PartialOrd<Rhs> for BytesInner<LenT, S>
569where
570    Rhs: ?Sized + AsRef<[u8]>,
571{
572    fn partial_cmp(&self, other: &Rhs) -> Option<Ordering> {
573        self.as_ref().partial_cmp(other.as_ref())
574    }
575}
576
577impl<S: BytesStorage + ?Sized, LenT: LenType> Hash for BytesInner<LenT, S> {
578    fn hash<H: Hasher>(&self, state: &mut H) {
579        self.bytes.hash(state);
580    }
581}
582
583#[derive(Clone)]
584pub struct IntoIter<const N: usize, LenT: LenType = usize> {
585    inner: <Vec<u8, N, LenT> as IntoIterator>::IntoIter,
586}
587
588impl<const N: usize, LenT: LenType> Iterator for IntoIter<N, LenT> {
589    type Item = u8;
590    fn next(&mut self) -> Option<Self::Item> {
591        self.inner.next()
592    }
593}
594
595impl<const N: usize, LenT: LenType> IntoIterator for Bytes<N, LenT> {
596    type Item = u8;
597    type IntoIter = IntoIter<N, LenT>;
598
599    fn into_iter(self) -> Self::IntoIter {
600        IntoIter {
601            inner: self.bytes.into_iter(),
602        }
603    }
604}
605
606impl<'a, S: BytesStorage + ?Sized, LenT: LenType> IntoIterator for &'a BytesInner<LenT, S> {
607    type Item = &'a u8;
608    type IntoIter = <&'a [u8] as IntoIterator>::IntoIter;
609
610    fn into_iter(self) -> Self::IntoIter {
611        self.bytes.iter()
612    }
613}
614
615impl<'a, S: BytesStorage + ?Sized, LenT: LenType> IntoIterator for &'a mut BytesInner<LenT, S> {
616    type Item = &'a mut u8;
617    type IntoIter = <&'a mut [u8] as IntoIterator>::IntoIter;
618
619    fn into_iter(self) -> Self::IntoIter {
620        self.bytes.iter_mut()
621    }
622}
623
624impl<S: BytesStorage + ?Sized, LenT: LenType> Serialize for BytesInner<LenT, S> {
625    fn serialize<SER>(&self, serializer: SER) -> Result<SER::Ok, SER::Error>
626    where
627        SER: Serializer,
628    {
629        serializer.serialize_bytes(self)
630    }
631}
632
633impl<S: BytesStorage + ?Sized, LenT: LenType> core::fmt::Write for BytesInner<LenT, S> {
634    fn write_str(&mut self, s: &str) -> fmt::Result {
635        self.bytes.write_str(s)
636    }
637    fn write_char(&mut self, s: char) -> fmt::Result {
638        self.bytes.write_char(s)
639    }
640    fn write_fmt(&mut self, s: core::fmt::Arguments<'_>) -> fmt::Result {
641        self.bytes.write_fmt(s)
642    }
643}
644
645impl<'de, const N: usize, LenT: LenType> Deserialize<'de> for Bytes<N, LenT> {
646    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
647    where
648        D: Deserializer<'de>,
649    {
650        struct ValueVisitor<const N: usize, LenT: LenType>(PhantomData<LenT>);
651
652        impl<'de, const N: usize, LenT: LenType> Visitor<'de> for ValueVisitor<N, LenT> {
653            type Value = Bytes<N, LenT>;
654
655            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
656                formatter.write_str("a sequence of bytes")
657            }
658
659            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
660            where
661                E: serde_core::de::Error,
662            {
663                Bytes::try_from(v).map_err(|_: CapacityError| E::invalid_length(v.len(), &self))
664            }
665
666            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
667            where
668                A: serde_core::de::SeqAccess<'de>,
669            {
670                use serde_core::de::Error;
671
672                let mut this = Bytes::new();
673                while let Some(byte) = seq.next_element()? {
674                    this.push(byte)
675                        .map_err(|()| A::Error::invalid_length(this.len(), &self))?;
676                }
677                Ok(this)
678            }
679        }
680
681        deserializer.deserialize_bytes(ValueVisitor(PhantomData))
682    }
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688    use serde_test::{assert_tokens, Token};
689
690    #[test]
691    fn serde() {
692        let mut bytes = Bytes::<0>::new();
693        assert!(bytes.push(1).is_err());
694        assert_tokens(&bytes, &[Token::Bytes(&[])]);
695
696        let mut bytes = Bytes::<16>::new();
697        bytes.push(1).unwrap();
698        assert_tokens(&bytes, &[Token::Bytes(&[1])]);
699        assert!(bytes.extend_from_slice(&[2; 16]).is_err());
700        assert_eq!(&*bytes, &[1]);
701        assert!(bytes.extend_from_slice(&[2; 15]).is_ok());
702        assert_eq!(&*bytes, &[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]);
703        assert_tokens(
704            &bytes,
705            &[Token::Bytes(&[
706                1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
707            ])],
708        );
709    }
710
711    #[test]
712    fn display() {
713        assert_eq!(
714            r"b'\x00abcde\n'",
715            format!(
716                "{:?}",
717                Bytes::<10>::try_from(b"\0abcde\n".as_slice())
718                    .unwrap()
719                    .as_view()
720            )
721        );
722    }
723
724    #[test]
725    fn from() {
726        let _: Bytes<10> = [0; 10].into();
727        let _: Bytes<10> = (&[0; 8]).into();
728        #[cfg(feature = "heapless-0.9")]
729        let _: Bytes<10> = Vec::<u8, 10, usize>::new().into();
730    }
731}