1#![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 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 pub const fn new() -> Self {
171 Self { bytes: Vec::new() }
172 }
173 pub const fn const_capacity(&self) -> usize {
177 N
178 }
179
180 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.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 pub fn as_view(&self) -> &BytesView<LenT> {
223 S::as_byte_view(self)
224 }
225
226 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 pub fn as_mut_ptr(&mut self) -> *mut u8 {
237 self.bytes.as_mut_ptr()
238 }
239
240 pub fn as_slice(&self) -> &[u8] {
242 self.bytes.as_slice()
243 }
244
245 pub fn as_mut_slice(&mut self) -> &mut [u8] {
247 self.bytes.as_mut_slice()
248 }
249
250 pub fn capacity(&self) -> usize {
254 self.bytes.capacity()
255 }
256
257 pub fn clear(&mut self) {
259 self.bytes.clear()
260 }
261
262 #[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 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 pub fn extend_from_slice(&mut self, other: &[u8]) -> Result<(), CapacityError> {
287 self.bytes.extend_from_slice(other)
288 }
289
290 pub fn pop(&mut self) -> Option<u8> {
292 self.bytes.pop()
293 }
294
295 pub fn push(&mut self, byte: u8) -> Result<(), ()> {
297 self.bytes.push(byte).map_err(drop)
298 }
299
300 pub unsafe fn pop_unchecked(&mut self) -> u8 {
306 unsafe { self.bytes.pop_unchecked() }
307 }
308
309 pub unsafe fn push_unchecked(&mut self, byte: u8) {
315 unsafe {
316 self.bytes.push_unchecked(byte);
317 }
318 }
319
320 pub fn truncate(&mut self, len: usize) {
322 self.bytes.truncate(len)
323 }
324
325 pub fn resize(&mut self, new_len: usize, value: u8) -> Result<(), CapacityError> {
333 self.bytes.resize(new_len, value)
334 }
335
336 pub fn resize_zero(&mut self, new_len: usize) -> Result<(), CapacityError> {
342 self.bytes.resize_default(new_len)
343 }
344
345 pub unsafe fn set_len(&mut self, new_len: usize) {
365 self.bytes.set_len(new_len)
366 }
367
368 pub fn swap_remove(&mut self, index: usize) -> u8 {
378 self.bytes.swap_remove(index)
379 }
380
381 pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> u8 {
391 unsafe { self.bytes.swap_remove_unchecked(index) }
392 }
393
394 pub fn is_full(&self) -> bool {
396 self.bytes.is_full()
397 }
398
399 pub fn is_empty(&self) -> bool {
401 self.bytes.is_empty()
402 }
403
404 pub fn starts_with(&self, needle: &[u8]) -> bool {
408 self.bytes.starts_with(needle)
409 }
410
411 pub fn ends_with(&self, needle: &[u8]) -> bool {
415 self.bytes.ends_with(needle)
416 }
417
418 pub fn insert(&mut self, index: usize, value: u8) -> Result<(), ()> {
425 self.bytes.insert(index, value).map_err(drop)
426 }
427
428 pub fn remove(&mut self, index: usize) -> u8 {
435 self.bytes.remove(index)
436 }
437
438 pub fn retain(&mut self, f: impl FnMut(&u8) -> bool) {
444 self.bytes.retain(f)
445 }
446 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 pub fn resize_capacity<const M: usize>(&self) -> Result<Bytes<M>, CapacityError> {
461 Bytes::try_from(&**self)
462 }
463}
464
465impl<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
496impl<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 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 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}