1#[cfg(feature = "alloc")]
6use alloc::vec::Vec;
7#[cfg(feature = "alloc")]
8use core::convert::Infallible;
9use core::{fmt, mem};
10
11use internals::write_err;
12
13#[cfg(feature = "alloc")]
14use super::Decodable;
15use super::Decoder;
16
17#[cfg(feature = "alloc")]
19const MAX_VEC_SIZE: u64 = 4_000_000;
20
21#[cfg(feature = "alloc")]
23const MAX_VECTOR_ALLOCATE: usize = 1_000_000;
24
25#[cfg(feature = "alloc")]
29pub struct ByteVecDecoder {
30 prefix_decoder: Option<CompactSizeDecoder>,
31 buffer: Vec<u8>,
32 bytes_expected: usize,
33 bytes_written: usize,
34}
35
36#[cfg(feature = "alloc")]
37impl ByteVecDecoder {
38 pub const fn new() -> Self {
40 Self {
41 prefix_decoder: Some(CompactSizeDecoder::new()),
42 buffer: Vec::new(),
43 bytes_expected: 0,
44 bytes_written: 0,
45 }
46 }
47
48 fn reserve(&mut self) {
60 if self.buffer.len() == self.buffer.capacity() {
61 let bytes_remaining = self.bytes_expected - self.bytes_written;
62 let batch_size = bytes_remaining.min(MAX_VECTOR_ALLOCATE);
63 self.buffer.reserve_exact(batch_size);
64 }
65 }
66}
67
68#[cfg(feature = "alloc")]
69impl Default for ByteVecDecoder {
70 fn default() -> Self { Self::new() }
71}
72
73#[cfg(feature = "alloc")]
74impl Decoder for ByteVecDecoder {
75 type Output = Vec<u8>;
76 type Error = ByteVecDecoderError;
77
78 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
79 use {ByteVecDecoderError as E, ByteVecDecoderErrorInner as Inner};
80
81 if let Some(mut decoder) = self.prefix_decoder.take() {
82 if decoder.push_bytes(bytes).map_err(|e| E(Inner::LengthPrefixDecode(e)))? {
83 self.prefix_decoder = Some(decoder);
84 return Ok(true);
85 }
86 let length = decoder.end().map_err(|e| E(Inner::LengthPrefixDecode(e)))?;
87
88 self.prefix_decoder = None;
89 self.bytes_expected =
90 cast_to_usize_if_valid(length).map_err(|e| E(Inner::LengthPrefixInvalid(e)))?;
91
92 }
94
95 self.reserve();
96
97 let remaining = self.bytes_expected - self.bytes_written;
98 let available_capacity = self.buffer.capacity() - self.buffer.len();
99 let copy_len = bytes.len().min(remaining).min(available_capacity);
100
101 self.buffer.extend_from_slice(&bytes[..copy_len]);
102 self.bytes_written += copy_len;
103 *bytes = &bytes[copy_len..];
104
105 Ok(self.bytes_written < self.bytes_expected)
107 }
108
109 fn end(self) -> Result<Self::Output, Self::Error> {
110 use {ByteVecDecoderError as E, ByteVecDecoderErrorInner as Inner};
111
112 if self.bytes_written == self.bytes_expected {
113 Ok(self.buffer)
114 } else {
115 Err(E(Inner::UnexpectedEof(UnexpectedEofError {
116 missing: self.bytes_expected - self.bytes_written,
117 })))
118 }
119 }
120
121 fn read_limit(&self) -> usize {
122 if let Some(prefix_decoder) = &self.prefix_decoder {
123 prefix_decoder.read_limit()
124 } else {
125 self.bytes_expected - self.bytes_written
126 }
127 }
128}
129
130#[cfg(feature = "alloc")]
134pub struct VecDecoder<T: Decodable> {
135 prefix_decoder: Option<CompactSizeDecoder>,
136 length: usize,
137 buffer: Vec<T>,
138 decoder: Option<<T as Decodable>::Decoder>,
139}
140
141#[cfg(feature = "alloc")]
142impl<T: Decodable> VecDecoder<T> {
143 pub const fn new() -> Self {
145 Self {
146 prefix_decoder: Some(CompactSizeDecoder::new()),
147 length: 0,
148 buffer: Vec::new(),
149 decoder: None,
150 }
151 }
152
153 fn reserve(&mut self) {
166 if self.buffer.len() == self.buffer.capacity() {
167 let elements_remaining = self.length - self.buffer.len();
168 let element_size = mem::size_of::<T>().max(1);
169 let batch_elements = MAX_VECTOR_ALLOCATE / element_size;
170 let elements_to_reserve = elements_remaining.min(batch_elements);
171 self.buffer.reserve_exact(elements_to_reserve);
172 }
173 }
174}
175
176#[cfg(feature = "alloc")]
177impl<T: Decodable> Default for VecDecoder<T> {
178 fn default() -> Self { Self::new() }
179}
180
181#[cfg(feature = "alloc")]
182impl<T: Decodable> Decoder for VecDecoder<T> {
183 type Output = Vec<T>;
184 type Error = VecDecoderError<<<T as Decodable>::Decoder as Decoder>::Error>;
185
186 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
187 use {VecDecoderError as E, VecDecoderErrorInner as Inner};
188
189 if let Some(mut decoder) = self.prefix_decoder.take() {
190 if decoder.push_bytes(bytes).map_err(|e| E(Inner::LengthPrefixDecode(e)))? {
191 self.prefix_decoder = Some(decoder);
192 return Ok(true);
193 }
194 let length = decoder.end().map_err(|e| E(Inner::LengthPrefixDecode(e)))?;
195 if length == 0 {
196 return Ok(false);
197 }
198
199 self.prefix_decoder = None;
200 self.length =
201 cast_to_usize_if_valid(length).map_err(|e| E(Inner::LengthPrefixInvalid(e)))?;
202
203 }
205
206 while !bytes.is_empty() {
207 self.reserve();
208
209 let mut decoder = self.decoder.take().unwrap_or_else(T::decoder);
210
211 if decoder.push_bytes(bytes).map_err(|e| E(Inner::Item(e)))? {
212 self.decoder = Some(decoder);
213 return Ok(true);
214 }
215 let item = decoder.end().map_err(|e| E(Inner::Item(e)))?;
216 self.buffer.push(item);
217
218 if self.buffer.len() == self.length {
219 return Ok(false);
220 }
221 }
222
223 if self.buffer.len() == self.length {
224 Ok(false)
225 } else {
226 Ok(true)
227 }
228 }
229
230 fn end(self) -> Result<Self::Output, Self::Error> {
231 use VecDecoderErrorInner as E;
232
233 if self.buffer.len() == self.length {
234 Ok(self.buffer)
235 } else {
236 Err(VecDecoderError(E::UnexpectedEof(UnexpectedEofError {
237 missing: self.length - self.buffer.len(),
238 })))
239 }
240 }
241
242 fn read_limit(&self) -> usize {
243 if let Some(prefix_decoder) = &self.prefix_decoder {
244 prefix_decoder.read_limit()
245 } else if let Some(decoder) = &self.decoder {
246 decoder.read_limit()
247 } else if self.buffer.len() == self.length {
248 0
250 } else {
251 let items_left_to_decode = self.length - self.buffer.len();
252 let decoder = T::decoder();
253 let limit_per_decoder = decoder.read_limit();
255 items_left_to_decode * limit_per_decoder
256 }
257 }
258}
259
260#[cfg(feature = "alloc")]
270pub fn cast_to_usize_if_valid(n: u64) -> Result<usize, LengthPrefixExceedsMaxError> {
271 if n > MAX_VEC_SIZE {
272 return Err(LengthPrefixExceedsMaxError { value: n });
273 }
274
275 usize::try_from(n).map_err(|_| LengthPrefixExceedsMaxError { value: n })
276}
277
278pub struct ArrayDecoder<const N: usize> {
280 buffer: [u8; N],
281 bytes_written: usize,
282}
283
284impl<const N: usize> ArrayDecoder<N> {
285 pub const fn new() -> Self { Self { buffer: [0; N], bytes_written: 0 } }
287}
288
289impl<const N: usize> Default for ArrayDecoder<N> {
290 fn default() -> Self { Self::new() }
291}
292
293impl<const N: usize> Decoder for ArrayDecoder<N> {
294 type Output = [u8; N];
295 type Error = UnexpectedEofError;
296
297 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
298 let remaining_space = N - self.bytes_written;
299 let copy_len = bytes.len().min(remaining_space);
300
301 if copy_len > 0 {
302 self.buffer[self.bytes_written..self.bytes_written + copy_len]
303 .copy_from_slice(&bytes[..copy_len]);
304 self.bytes_written += copy_len;
305 *bytes = &bytes[copy_len..];
307 }
308
309 Ok(self.bytes_written < N)
311 }
312
313 #[inline]
314 fn end(self) -> Result<Self::Output, Self::Error> {
315 if self.bytes_written == N {
316 Ok(self.buffer)
317 } else {
318 Err(UnexpectedEofError { missing: N - self.bytes_written })
319 }
320 }
321
322 #[inline]
323 fn read_limit(&self) -> usize { N - self.bytes_written }
324}
325
326pub struct Decoder2<A, B>
328where
329 A: Decoder,
330 B: Decoder,
331{
332 state: Decoder2State<A, B>,
333}
334
335enum Decoder2State<A: Decoder, B: Decoder> {
336 First(A, B),
338 Second(A::Output, B),
340 Errored,
342}
343
344impl<A, B> Decoder2<A, B>
345where
346 A: Decoder,
347 B: Decoder,
348{
349 pub const fn new(first: A, second: B) -> Self { Self { state: Decoder2State::First(first, second) } }
351}
352
353impl<A, B> Decoder for Decoder2<A, B>
354where
355 A: Decoder,
356 B: Decoder,
357{
358 type Output = (A::Output, B::Output);
359 type Error = Decoder2Error<A::Error, B::Error>;
360
361 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
362 loop {
363 match &mut self.state {
364 Decoder2State::First(first_decoder, _) => {
365 if first_decoder.push_bytes(bytes).map_err(Decoder2Error::First)? {
366 return Ok(true);
368 }
369
370 match mem::replace(&mut self.state, Decoder2State::Errored) {
374 Decoder2State::First(first, second) => {
375 let first_result = first.end().map_err(Decoder2Error::First)?;
376 self.state = Decoder2State::Second(first_result, second);
377 }
378 _ => unreachable!("we know we're in First state"),
379 }
380 }
381 Decoder2State::Second(_, second_decoder) => {
382 return second_decoder.push_bytes(bytes).map_err(|error| {
383 self.state = Decoder2State::Errored;
384 Decoder2Error::Second(error)
385 });
386 }
387 Decoder2State::Errored => {
388 panic!("use of failed decoder");
389 }
390 }
391 }
392 }
393
394 #[inline]
395 fn end(self) -> Result<Self::Output, Self::Error> {
396 match self.state {
397 Decoder2State::First(first_decoder, second_decoder) => {
398 let first_result = first_decoder.end().map_err(Decoder2Error::First)?;
402 let second_result = second_decoder.end().map_err(Decoder2Error::Second)?;
403 Ok((first_result, second_result))
404 }
405 Decoder2State::Second(first_result, second_decoder) => {
406 let second_result = second_decoder.end().map_err(Decoder2Error::Second)?;
407 Ok((first_result, second_result))
408 }
409 Decoder2State::Errored => {
410 panic!("use of failed decoder");
411 }
412 }
413 }
414
415 #[inline]
416 fn read_limit(&self) -> usize {
417 match &self.state {
418 Decoder2State::First(first_decoder, second_decoder) =>
419 first_decoder.read_limit() + second_decoder.read_limit(),
420 Decoder2State::Second(_, second_decoder) => second_decoder.read_limit(),
421 Decoder2State::Errored => 0,
422 }
423 }
424}
425
426pub struct Decoder3<A, B, C>
428where
429 A: Decoder,
430 B: Decoder,
431 C: Decoder,
432{
433 inner: Decoder2<Decoder2<A, B>, C>,
434}
435
436impl<A, B, C> Decoder3<A, B, C>
437where
438 A: Decoder,
439 B: Decoder,
440 C: Decoder,
441{
442 pub const fn new(dec_1: A, dec_2: B, dec_3: C) -> Self {
444 Self { inner: Decoder2::new(Decoder2::new(dec_1, dec_2), dec_3) }
445 }
446}
447
448impl<A, B, C> Decoder for Decoder3<A, B, C>
449where
450 A: Decoder,
451 B: Decoder,
452 C: Decoder,
453{
454 type Output = (A::Output, B::Output, C::Output);
455 type Error = Decoder3Error<A::Error, B::Error, C::Error>;
456
457 #[inline]
458 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
459 self.inner.push_bytes(bytes).map_err(|error| match error {
460 Decoder2Error::First(Decoder2Error::First(a)) => Decoder3Error::First(a),
461 Decoder2Error::First(Decoder2Error::Second(b)) => Decoder3Error::Second(b),
462 Decoder2Error::Second(c) => Decoder3Error::Third(c),
463 })
464 }
465
466 #[inline]
467 fn end(self) -> Result<Self::Output, Self::Error> {
468 let result = self.inner.end().map_err(|error| match error {
469 Decoder2Error::First(Decoder2Error::First(a)) => Decoder3Error::First(a),
470 Decoder2Error::First(Decoder2Error::Second(b)) => Decoder3Error::Second(b),
471 Decoder2Error::Second(c) => Decoder3Error::Third(c),
472 })?;
473
474 let ((first, second), third) = result;
475 Ok((first, second, third))
476 }
477
478 #[inline]
479 fn read_limit(&self) -> usize { self.inner.read_limit() }
480}
481
482pub struct Decoder4<A, B, C, D>
484where
485 A: Decoder,
486 B: Decoder,
487 C: Decoder,
488 D: Decoder,
489{
490 inner: Decoder2<Decoder2<A, B>, Decoder2<C, D>>,
491}
492
493impl<A, B, C, D> Decoder4<A, B, C, D>
494where
495 A: Decoder,
496 B: Decoder,
497 C: Decoder,
498 D: Decoder,
499{
500 pub const fn new(dec_1: A, dec_2: B, dec_3: C, dec_4: D) -> Self {
502 Self { inner: Decoder2::new(Decoder2::new(dec_1, dec_2), Decoder2::new(dec_3, dec_4)) }
503 }
504}
505
506impl<A, B, C, D> Decoder for Decoder4<A, B, C, D>
507where
508 A: Decoder,
509 B: Decoder,
510 C: Decoder,
511 D: Decoder,
512{
513 type Output = (A::Output, B::Output, C::Output, D::Output);
514 type Error = Decoder4Error<A::Error, B::Error, C::Error, D::Error>;
515
516 #[inline]
517 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
518 self.inner.push_bytes(bytes).map_err(|error| match error {
519 Decoder2Error::First(Decoder2Error::First(a)) => Decoder4Error::First(a),
520 Decoder2Error::First(Decoder2Error::Second(b)) => Decoder4Error::Second(b),
521 Decoder2Error::Second(Decoder2Error::First(c)) => Decoder4Error::Third(c),
522 Decoder2Error::Second(Decoder2Error::Second(d)) => Decoder4Error::Fourth(d),
523 })
524 }
525
526 #[inline]
527 fn end(self) -> Result<Self::Output, Self::Error> {
528 let result = self.inner.end().map_err(|error| match error {
529 Decoder2Error::First(Decoder2Error::First(a)) => Decoder4Error::First(a),
530 Decoder2Error::First(Decoder2Error::Second(b)) => Decoder4Error::Second(b),
531 Decoder2Error::Second(Decoder2Error::First(c)) => Decoder4Error::Third(c),
532 Decoder2Error::Second(Decoder2Error::Second(d)) => Decoder4Error::Fourth(d),
533 })?;
534
535 let ((first, second), (third, fourth)) = result;
536 Ok((first, second, third, fourth))
537 }
538
539 #[inline]
540 fn read_limit(&self) -> usize { self.inner.read_limit() }
541}
542
543#[allow(clippy::type_complexity)] pub struct Decoder6<A, B, C, D, E, F>
546where
547 A: Decoder,
548 B: Decoder,
549 C: Decoder,
550 D: Decoder,
551 E: Decoder,
552 F: Decoder,
553{
554 inner: Decoder2<Decoder3<A, B, C>, Decoder3<D, E, F>>,
555}
556
557impl<A, B, C, D, E, F> Decoder6<A, B, C, D, E, F>
558where
559 A: Decoder,
560 B: Decoder,
561 C: Decoder,
562 D: Decoder,
563 E: Decoder,
564 F: Decoder,
565{
566 pub const fn new(dec_1: A, dec_2: B, dec_3: C, dec_4: D, dec_5: E, dec_6: F) -> Self {
568 Self {
569 inner: Decoder2::new(
570 Decoder3::new(dec_1, dec_2, dec_3),
571 Decoder3::new(dec_4, dec_5, dec_6),
572 ),
573 }
574 }
575}
576
577impl<A, B, C, D, E, F> Decoder for Decoder6<A, B, C, D, E, F>
578where
579 A: Decoder,
580 B: Decoder,
581 C: Decoder,
582 D: Decoder,
583 E: Decoder,
584 F: Decoder,
585{
586 type Output = (A::Output, B::Output, C::Output, D::Output, E::Output, F::Output);
587 type Error = Decoder6Error<A::Error, B::Error, C::Error, D::Error, E::Error, F::Error>;
588
589 #[inline]
590 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
591 self.inner.push_bytes(bytes).map_err(|error| match error {
592 Decoder2Error::First(Decoder3Error::First(a)) => Decoder6Error::First(a),
593 Decoder2Error::First(Decoder3Error::Second(b)) => Decoder6Error::Second(b),
594 Decoder2Error::First(Decoder3Error::Third(c)) => Decoder6Error::Third(c),
595 Decoder2Error::Second(Decoder3Error::First(d)) => Decoder6Error::Fourth(d),
596 Decoder2Error::Second(Decoder3Error::Second(e)) => Decoder6Error::Fifth(e),
597 Decoder2Error::Second(Decoder3Error::Third(f)) => Decoder6Error::Sixth(f),
598 })
599 }
600
601 #[inline]
602 fn end(self) -> Result<Self::Output, Self::Error> {
603 let result = self.inner.end().map_err(|error| match error {
604 Decoder2Error::First(Decoder3Error::First(a)) => Decoder6Error::First(a),
605 Decoder2Error::First(Decoder3Error::Second(b)) => Decoder6Error::Second(b),
606 Decoder2Error::First(Decoder3Error::Third(c)) => Decoder6Error::Third(c),
607 Decoder2Error::Second(Decoder3Error::First(d)) => Decoder6Error::Fourth(d),
608 Decoder2Error::Second(Decoder3Error::Second(e)) => Decoder6Error::Fifth(e),
609 Decoder2Error::Second(Decoder3Error::Third(f)) => Decoder6Error::Sixth(f),
610 })?;
611
612 let ((first, second, third), (fourth, fifth, sixth)) = result;
613 Ok((first, second, third, fourth, fifth, sixth))
614 }
615
616 #[inline]
617 fn read_limit(&self) -> usize { self.inner.read_limit() }
618}
619
620#[derive(Debug, Clone)]
624pub struct CompactSizeDecoder {
625 buf: internals::array_vec::ArrayVec<u8, 9>,
626}
627
628impl CompactSizeDecoder {
629 pub const fn new() -> Self { Self { buf: internals::array_vec::ArrayVec::new() } }
631}
632
633impl Default for CompactSizeDecoder {
634 fn default() -> Self { Self::new() }
635}
636
637impl Decoder for CompactSizeDecoder {
638 type Output = u64;
639 type Error = CompactSizeDecoderError;
640
641 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
642 if bytes.is_empty() {
643 return Ok(true);
644 }
645
646 if self.buf.is_empty() {
647 self.buf.push(bytes[0]);
648 *bytes = &bytes[1..];
649 }
650 let len = match self.buf[0] {
651 0xFF => 9,
652 0xFE => 5,
653 0xFD => 3,
654 _ => 1,
655 };
656 let to_copy = bytes.len().min(len - self.buf.len());
657 self.buf.extend_from_slice(&bytes[..to_copy]);
658 *bytes = &bytes[to_copy..];
659
660 Ok(self.buf.len() != len)
661 }
662
663 fn end(self) -> Result<Self::Output, Self::Error> {
664 use CompactSizeDecoderErrorInner as E;
665
666 fn arr<const N: usize>(slice: &[u8]) -> Result<[u8; N], CompactSizeDecoderError> {
667 slice.try_into().map_err(|_| {
668 CompactSizeDecoderError(E::UnexpectedEof { required: N, received: slice.len() })
669 })
670 }
671
672 let (first, payload) = self
673 .buf
674 .split_first()
675 .ok_or(CompactSizeDecoderError(E::UnexpectedEof { required: 1, received: 0 }))?;
676
677 match *first {
678 0xFF => {
679 let x = u64::from_le_bytes(arr(payload)?);
680 if x < 0x100_000_000 {
681 Err(CompactSizeDecoderError(E::NonMinimal { value: x }))
682 } else {
683 Ok(x)
684 }
685 }
686 0xFE => {
687 let x = u32::from_le_bytes(arr(payload)?);
688 if x < 0x10000 {
689 Err(CompactSizeDecoderError(E::NonMinimal { value: x.into() }))
690 } else {
691 Ok(x.into())
692 }
693 }
694 0xFD => {
695 let x = u16::from_le_bytes(arr(payload)?);
696 if x < 0xFD {
697 Err(CompactSizeDecoderError(E::NonMinimal { value: x.into() }))
698 } else {
699 Ok(x.into())
700 }
701 }
702 n => Ok(n.into()),
703 }
704 }
705
706 fn read_limit(&self) -> usize {
707 match self.buf.len() {
708 0 => 1,
709 already_read => match self.buf[0] {
710 0xFF => 9_usize.saturating_sub(already_read),
711 0xFE => 5_usize.saturating_sub(already_read),
712 0xFD => 3_usize.saturating_sub(already_read),
713 _ => 0,
714 },
715 }
716 }
717}
718
719#[derive(Debug, Clone, PartialEq, Eq)]
721pub struct CompactSizeDecoderError(CompactSizeDecoderErrorInner);
722
723#[derive(Debug, Clone, PartialEq, Eq)]
724enum CompactSizeDecoderErrorInner {
725 UnexpectedEof {
727 required: usize,
729 received: usize,
731 },
732 NonMinimal {
734 value: u64,
736 },
737}
738
739impl fmt::Display for CompactSizeDecoderError {
740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
741 use CompactSizeDecoderErrorInner as E;
742
743 match self.0 {
744 E::UnexpectedEof { required: 1, received: 0 } => {
745 write!(f, "required at least one byte but the input is empty")
746 }
747 E::UnexpectedEof { required, received: 0 } => {
748 write!(f, "required at least {} bytes but the input is empty", required)
749 }
750 E::UnexpectedEof { required, received } => write!(
751 f,
752 "required at least {} bytes but only {} bytes were received",
753 required, received
754 ),
755 E::NonMinimal { value } => write!(f, "the value {} was not encoded minimally", value),
756 }
757 }
758}
759
760#[cfg(feature = "std")]
761impl std::error::Error for CompactSizeDecoderError {}
762
763#[cfg(feature = "alloc")]
765#[derive(Debug, Clone, PartialEq, Eq)]
766pub struct ByteVecDecoderError(ByteVecDecoderErrorInner);
767
768#[cfg(feature = "alloc")]
769#[derive(Debug, Clone, PartialEq, Eq)]
770enum ByteVecDecoderErrorInner {
771 LengthPrefixDecode(CompactSizeDecoderError),
773 LengthPrefixInvalid(LengthPrefixExceedsMaxError),
775 UnexpectedEof(UnexpectedEofError),
777}
778
779#[cfg(feature = "alloc")]
780impl From<Infallible> for ByteVecDecoderError {
781 fn from(never: Infallible) -> Self { match never {} }
782}
783
784#[cfg(feature = "alloc")]
785impl fmt::Display for ByteVecDecoderError {
786 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
787 use ByteVecDecoderErrorInner as E;
788
789 match self.0 {
790 E::LengthPrefixDecode(ref e) => write_err!(f, "byte vec decoder error"; e),
791 E::LengthPrefixInvalid(ref e) => write_err!(f, "byte vec decoder error"; e),
792 E::UnexpectedEof(ref e) => write_err!(f, "byte vec decoder error"; e),
793 }
794 }
795}
796
797#[cfg(all(feature = "std", feature = "alloc"))]
798impl std::error::Error for ByteVecDecoderError {
799 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
800 use ByteVecDecoderErrorInner as E;
801
802 match self.0 {
803 E::LengthPrefixDecode(ref e) => Some(e),
804 E::LengthPrefixInvalid(ref e) => Some(e),
805 E::UnexpectedEof(ref e) => Some(e),
806 }
807 }
808}
809
810#[cfg(feature = "alloc")]
812#[derive(Debug, Clone, PartialEq, Eq)]
813pub struct VecDecoderError<Err>(VecDecoderErrorInner<Err>);
814
815#[cfg(feature = "alloc")]
816#[derive(Debug, Clone, PartialEq, Eq)]
817enum VecDecoderErrorInner<Err> {
818 LengthPrefixDecode(CompactSizeDecoderError),
820 LengthPrefixInvalid(LengthPrefixExceedsMaxError),
822 Item(Err),
824 UnexpectedEof(UnexpectedEofError),
826}
827
828#[cfg(feature = "alloc")]
829impl<Err> From<Infallible> for VecDecoderError<Err> {
830 fn from(never: Infallible) -> Self { match never {} }
831}
832
833#[cfg(feature = "alloc")]
834impl<Err> fmt::Display for VecDecoderError<Err>
835where
836 Err: fmt::Display + fmt::Debug,
837{
838 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
839 use VecDecoderErrorInner as E;
840
841 match self.0 {
842 E::LengthPrefixDecode(ref e) => write_err!(f, "vec decoder error"; e),
843 E::LengthPrefixInvalid(ref e) => write_err!(f, "vec decoder error"; e),
844 E::Item(ref e) => write_err!(f, "vec decoder error"; e),
845 E::UnexpectedEof(ref e) => write_err!(f, "vec decoder error"; e),
846 }
847 }
848}
849
850#[cfg(feature = "std")]
851impl<Err> std::error::Error for VecDecoderError<Err>
852where
853 Err: std::error::Error + 'static,
854{
855 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
856 use VecDecoderErrorInner as E;
857
858 match self.0 {
859 E::LengthPrefixDecode(ref e) => Some(e),
860 E::LengthPrefixInvalid(ref e) => Some(e),
861 E::Item(ref e) => Some(e),
862 E::UnexpectedEof(ref e) => Some(e),
863 }
864 }
865}
866
867#[cfg(feature = "alloc")]
869#[derive(Debug, Clone, PartialEq, Eq)]
870pub struct LengthPrefixExceedsMaxError {
871 value: u64,
873}
874
875#[cfg(feature = "alloc")]
876impl core::fmt::Display for LengthPrefixExceedsMaxError {
877 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
878 let max = match mem::size_of::<usize>() {
879 1 => u32::from(u8::MAX),
880 2 => u32::from(u16::MAX),
881 _ => 4_000_000,
882 };
883
884 write!(f, "length prefix {} exceeds max value {}", self.value, max)
885 }
886}
887
888#[cfg(all(feature = "std", feature = "alloc"))]
889impl std::error::Error for LengthPrefixExceedsMaxError {}
890
891#[derive(Debug, Clone, PartialEq, Eq)]
893pub struct UnexpectedEofError {
894 missing: usize,
896}
897
898impl fmt::Display for UnexpectedEofError {
899 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
900 write!(f, "not enough bytes for decoder, {} more bytes required", self.missing)
901 }
902}
903
904#[cfg(feature = "std")]
905impl std::error::Error for UnexpectedEofError {}
906
907#[derive(Debug, Clone, PartialEq, Eq)]
909pub enum Decoder2Error<A, B> {
910 First(A),
912 Second(B),
914}
915
916impl<A, B> fmt::Display for Decoder2Error<A, B>
917where
918 A: fmt::Display,
919 B: fmt::Display,
920{
921 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
922 match self {
923 Self::First(ref e) => write_err!(f, "first decoder error"; e),
924 Self::Second(ref e) => write_err!(f, "second decoder error"; e),
925 }
926 }
927}
928
929#[cfg(feature = "std")]
930impl<A, B> std::error::Error for Decoder2Error<A, B>
931where
932 A: std::error::Error + 'static,
933 B: std::error::Error + 'static,
934{
935 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
936 match self {
937 Self::First(ref e) => Some(e),
938 Self::Second(ref e) => Some(e),
939 }
940 }
941}
942
943#[derive(Debug, Clone, PartialEq, Eq)]
945pub enum Decoder3Error<A, B, C> {
946 First(A),
948 Second(B),
950 Third(C),
952}
953
954impl<A, B, C> fmt::Display for Decoder3Error<A, B, C>
955where
956 A: fmt::Display,
957 B: fmt::Display,
958 C: fmt::Display,
959{
960 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
961 match self {
962 Self::First(ref e) => write_err!(f, "first decoder error"; e),
963 Self::Second(ref e) => write_err!(f, "second decoder error"; e),
964 Self::Third(ref e) => write_err!(f, "third decoder error"; e),
965 }
966 }
967}
968
969#[cfg(feature = "std")]
970impl<A, B, C> std::error::Error for Decoder3Error<A, B, C>
971where
972 A: std::error::Error + 'static,
973 B: std::error::Error + 'static,
974 C: std::error::Error + 'static,
975{
976 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
977 match self {
978 Self::First(ref e) => Some(e),
979 Self::Second(ref e) => Some(e),
980 Self::Third(ref e) => Some(e),
981 }
982 }
983}
984
985#[derive(Debug, Clone, PartialEq, Eq)]
987pub enum Decoder4Error<A, B, C, D> {
988 First(A),
990 Second(B),
992 Third(C),
994 Fourth(D),
996}
997
998impl<A, B, C, D> fmt::Display for Decoder4Error<A, B, C, D>
999where
1000 A: fmt::Display,
1001 B: fmt::Display,
1002 C: fmt::Display,
1003 D: fmt::Display,
1004{
1005 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1006 match self {
1007 Self::First(ref e) => write_err!(f, "first decoder error"; e),
1008 Self::Second(ref e) => write_err!(f, "second decoder error"; e),
1009 Self::Third(ref e) => write_err!(f, "third decoder error"; e),
1010 Self::Fourth(ref e) => write_err!(f, "fourth decoder error"; e),
1011 }
1012 }
1013}
1014
1015#[cfg(feature = "std")]
1016impl<A, B, C, D> std::error::Error for Decoder4Error<A, B, C, D>
1017where
1018 A: std::error::Error + 'static,
1019 B: std::error::Error + 'static,
1020 C: std::error::Error + 'static,
1021 D: std::error::Error + 'static,
1022{
1023 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1024 match self {
1025 Self::First(ref e) => Some(e),
1026 Self::Second(ref e) => Some(e),
1027 Self::Third(ref e) => Some(e),
1028 Self::Fourth(ref e) => Some(e),
1029 }
1030 }
1031}
1032
1033#[derive(Debug, Clone, PartialEq, Eq)]
1035pub enum Decoder6Error<A, B, C, D, E, F> {
1036 First(A),
1038 Second(B),
1040 Third(C),
1042 Fourth(D),
1044 Fifth(E),
1046 Sixth(F),
1048}
1049
1050impl<A, B, C, D, E, F> fmt::Display for Decoder6Error<A, B, C, D, E, F>
1051where
1052 A: fmt::Display,
1053 B: fmt::Display,
1054 C: fmt::Display,
1055 D: fmt::Display,
1056 E: fmt::Display,
1057 F: fmt::Display,
1058{
1059 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1060 match self {
1061 Self::First(ref e) => write_err!(f, "first decoder error"; e),
1062 Self::Second(ref e) => write_err!(f, "second decoder error"; e),
1063 Self::Third(ref e) => write_err!(f, "third decoder error"; e),
1064 Self::Fourth(ref e) => write_err!(f, "fourth decoder error"; e),
1065 Self::Fifth(ref e) => write_err!(f, "fifth decoder error"; e),
1066 Self::Sixth(ref e) => write_err!(f, "sixth decoder error"; e),
1067 }
1068 }
1069}
1070
1071#[cfg(feature = "std")]
1072impl<A, B, C, D, E, F> std::error::Error for Decoder6Error<A, B, C, D, E, F>
1073where
1074 A: std::error::Error + 'static,
1075 B: std::error::Error + 'static,
1076 C: std::error::Error + 'static,
1077 D: std::error::Error + 'static,
1078 E: std::error::Error + 'static,
1079 F: std::error::Error + 'static,
1080{
1081 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1082 match self {
1083 Self::First(ref e) => Some(e),
1084 Self::Second(ref e) => Some(e),
1085 Self::Third(ref e) => Some(e),
1086 Self::Fourth(ref e) => Some(e),
1087 Self::Fifth(ref e) => Some(e),
1088 Self::Sixth(ref e) => Some(e),
1089 }
1090 }
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095 #[cfg(feature = "alloc")]
1096 use alloc::vec;
1097 #[cfg(feature = "alloc")]
1098 use alloc::vec::Vec;
1099 #[cfg(feature = "alloc")]
1100 use core::iter;
1101 #[cfg(feature = "std")]
1102 use std::io::Cursor;
1103
1104 use super::*;
1105
1106 macro_rules! check_decode_one_byte_at_a_time {
1108 ($decoder:ident $($test_name:ident, $want:expr, $array:expr);* $(;)?) => {
1109 $(
1110 #[test]
1111 #[allow(non_snake_case)]
1112 fn $test_name() {
1113 let mut decoder = $decoder::default();
1114
1115 for (i, _) in $array.iter().enumerate() {
1116 if i < $array.len() - 1 {
1117 let mut p = &$array[i..i+1];
1118 assert!(decoder.push_bytes(&mut p).unwrap());
1119 } else {
1120 let mut p = &$array[i..];
1122 assert!(!decoder.push_bytes(&mut p).unwrap());
1123 }
1124 }
1125
1126 let got = decoder.end().unwrap();
1127 assert_eq!(got, $want);
1128 }
1129 )*
1130
1131 }
1132 }
1133
1134 check_decode_one_byte_at_a_time! {
1135 CompactSizeDecoder
1136 decode_compact_size_0x10, 0x10, [0x10];
1137 decode_compact_size_0xFC, 0xFC, [0xFC];
1138 decode_compact_size_0xFD, 0xFD, [0xFD, 0xFD, 0x00];
1139 decode_compact_size_0x100, 0x100, [0xFD, 0x00, 0x01];
1140 decode_compact_size_0xFFF, 0x0FFF, [0xFD, 0xFF, 0x0F];
1141 decode_compact_size_0x0F0F_0F0F, 0x0F0F_0F0F, [0xFE, 0xF, 0xF, 0xF, 0xF];
1142 decode_compact_size_0xF0F0_F0F0_F0E0, 0xF0F0_F0F0_F0E0, [0xFF, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0, 0];
1143 }
1144
1145 #[test]
1146 #[cfg(feature = "alloc")]
1147 fn compact_size_zero() {
1148 let encoded = alloc::vec![0x00, 0xFF, 0xFF];
1150
1151 let mut slice = encoded.as_slice();
1152 let mut decoder = CompactSizeDecoder::new();
1153 assert!(!decoder.push_bytes(&mut slice).unwrap());
1154
1155 let got = decoder.end().unwrap();
1156 assert_eq!(got, 0);
1157 }
1158
1159 #[cfg(feature = "alloc")]
1160 fn two_fifty_six_bytes_encoded() -> Vec<u8> {
1161 let data = [0xff; 256];
1162 let mut v = Vec::with_capacity(259);
1163
1164 v.extend_from_slice(&[0xFD, 0x00, 0x01]); v.extend_from_slice(&data);
1166 v
1167 }
1168
1169 #[cfg(feature = "alloc")]
1170 check_decode_one_byte_at_a_time! {
1171 ByteVecDecoder
1172 decode_byte_vec, alloc::vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
1173 [0x08, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
1174 decode_byte_vec_multi_byte_length_prefix, [0xff; 256], two_fifty_six_bytes_encoded();
1175 }
1176
1177 #[cfg(feature = "alloc")]
1178 #[derive(Clone, Debug, PartialEq, Eq)]
1179 pub struct Inner(u32);
1180
1181 #[cfg(feature = "alloc")]
1183 pub struct InnerDecoder(ArrayDecoder<4>);
1184
1185 #[cfg(feature = "alloc")]
1186 impl Decoder for InnerDecoder {
1187 type Output = Inner;
1188 type Error = UnexpectedEofError;
1189
1190 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
1191 self.0.push_bytes(bytes)
1192 }
1193
1194 fn end(self) -> Result<Self::Output, Self::Error> {
1195 let n = u32::from_le_bytes(self.0.end()?);
1196 Ok(Inner(n))
1197 }
1198
1199 fn read_limit(&self) -> usize { self.0.read_limit() }
1200 }
1201
1202 #[cfg(feature = "alloc")]
1203 impl Decodable for Inner {
1204 type Decoder = InnerDecoder;
1205 fn decoder() -> Self::Decoder { InnerDecoder(ArrayDecoder::<4>::new()) }
1206 }
1207
1208 #[cfg(feature = "alloc")]
1209 #[derive(Clone, Debug, PartialEq, Eq)]
1210 pub struct Test(Vec<Inner>);
1211
1212 #[cfg(feature = "alloc")]
1214 #[derive(Default)]
1215 pub struct TestDecoder(VecDecoder<Inner>);
1216
1217 #[cfg(feature = "alloc")]
1218 impl Decoder for TestDecoder {
1219 type Output = Test;
1220 type Error = VecDecoderError<UnexpectedEofError>;
1221
1222 fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
1223 self.0.push_bytes(bytes)
1224 }
1225
1226 fn end(self) -> Result<Self::Output, Self::Error> {
1227 let v = self.0.end()?;
1228 Ok(Test(v))
1229 }
1230
1231 fn read_limit(&self) -> usize { self.0.read_limit() }
1232 }
1233
1234 #[cfg(feature = "alloc")]
1235 impl Decodable for Test {
1236 type Decoder = TestDecoder;
1237 fn decoder() -> Self::Decoder { TestDecoder(VecDecoder::new()) }
1238 }
1239
1240 #[test]
1241 #[cfg(feature = "alloc")]
1242 fn vec_decoder_empty() {
1243 let encoded = vec![0x00, 0xFF, 0xFF];
1245
1246 let mut slice = encoded.as_slice();
1247 let mut decoder = Test::decoder();
1248 assert!(!decoder.push_bytes(&mut slice).unwrap());
1249
1250 let got = decoder.end().unwrap();
1251 let want = Test(vec![]);
1252
1253 assert_eq!(got, want);
1254 }
1255
1256 #[test]
1257 #[cfg(feature = "alloc")]
1258 fn vec_decoder_one_item() {
1259 let encoded = vec![0x01, 0xEF, 0xBE, 0xAD, 0xDE];
1260
1261 let mut slice = encoded.as_slice();
1262 let mut decoder = Test::decoder();
1263 decoder.push_bytes(&mut slice).unwrap();
1264
1265 let got = decoder.end().unwrap();
1266 let want = Test(vec![Inner(0xDEAD_BEEF)]);
1267
1268 assert_eq!(got, want);
1269 }
1270
1271 #[test]
1272 #[cfg(feature = "alloc")]
1273 fn vec_decoder_two_items() {
1274 let encoded = vec![0x02, 0xEF, 0xBE, 0xAD, 0xDE, 0xBE, 0xBA, 0xFE, 0xCA];
1275
1276 let mut slice = encoded.as_slice();
1277 let mut decoder = Test::decoder();
1278 decoder.push_bytes(&mut slice).unwrap();
1279
1280 let got = decoder.end().unwrap();
1281 let want = Test(vec![Inner(0xDEAD_BEEF), Inner(0xCAFE_BABE)]);
1282
1283 assert_eq!(got, want);
1284 }
1285
1286 #[cfg(feature = "alloc")]
1287 fn two_fifty_six_elements() -> Test {
1288 Test(iter::repeat(Inner(0xDEAD_BEEF)).take(256).collect())
1289 }
1290
1291 #[cfg(feature = "alloc")]
1292 fn two_fifty_six_elements_encoded() -> Vec<u8> {
1293 [0xFD, 0x00, 0x01] .into_iter()
1295 .chain(iter::repeat(0xDEAD_BEEF_u32.to_le_bytes()).take(256).flatten())
1296 .collect()
1297 }
1298
1299 #[cfg(feature = "alloc")]
1300 check_decode_one_byte_at_a_time! {
1301 TestDecoder
1302 decode_vec, Test(vec![Inner(0xDEAD_BEEF), Inner(0xCAFE_BABE)]),
1303 vec![0x02, 0xEF, 0xBE, 0xAD, 0xDE, 0xBE, 0xBA, 0xFE, 0xCA];
1304 decode_vec_multi_byte_length_prefix, two_fifty_six_elements(), two_fifty_six_elements_encoded();
1305 }
1306
1307 #[test]
1308 #[cfg(feature = "alloc")]
1309 fn vec_decoder_one_item_plus_more_data() {
1310 let encoded = vec![0x01, 0xEF, 0xBE, 0xAD, 0xDE, 0xff, 0xff, 0xff, 0xff];
1312
1313 let mut slice = encoded.as_slice();
1314
1315 let mut decoder = Test::decoder();
1316 decoder.push_bytes(&mut slice).unwrap();
1317
1318 let got = decoder.end().unwrap();
1319 let want = Test(vec![Inner(0xDEAD_BEEF)]);
1320
1321 assert_eq!(got, want);
1322 }
1323
1324 #[cfg(feature = "std")]
1325 #[test]
1326 fn decode_vec_from_read_unbuffered_success() {
1327 let encoded = [0x01, 0xEF, 0xBE, 0xAD, 0xDE, 0xff, 0xff, 0xff, 0xff];
1328 let mut cursor = Cursor::new(&encoded);
1329
1330 let got = crate::decode_from_read_unbuffered::<Test, _>(&mut cursor).unwrap();
1331 assert_eq!(cursor.position(), 5);
1332
1333 let want = Test(vec![Inner(0xDEAD_BEEF)]);
1334 assert_eq!(got, want);
1335 }
1336}