octseq/
parse.rs

1//! Reading data from an octet sequence.
2//!
3//! Parsing is a little more complicated since encoded data may very well be
4//! broken or ambiguously encoded. The helper type [`Parser`] wraps an octets
5//! ref and allows to parse values from the octets.
6
7use core::fmt;
8use core::ops::{Bound, RangeBounds};
9use crate::octets::Octets;
10
11//------------ Parser --------------------------------------------------------
12
13/// A parser for sequentially extracting data from an octets sequence.
14///
15/// The parser wraps an [Octets] reference and remembers the read position on
16/// the referenced sequence. Methods allow reading out data and progressing
17/// the position beyond processed data.
18#[derive(Debug)]
19pub struct Parser<'a, Octs: ?Sized> {
20    /// The underlying octets reference.
21    octets: &'a Octs,
22
23    /// The current position of the parser from the beginning of `octets`.
24    pos: usize,
25
26    /// The length of the octets sequence.
27    len: usize,
28}
29
30impl<'a, Octs: ?Sized> Parser<'a, Octs> {
31    /// Creates a new parser atop a reference to an octet sequence.
32    pub fn from_ref(octets: &'a Octs) -> Self
33    where
34        Octs: AsRef<[u8]>,
35    {
36        Parser {
37            pos: 0,
38            len: octets.as_ref().len(),
39            octets,
40        }
41    }
42
43    /// Creates a new parser only using a range of the given octets.
44    ///
45    /// # Panics
46    ///
47    /// Panics if `range` is decreasing or out of bounds.
48    pub fn with_range<R>(octets: &'a Octs, range: R) -> Self
49    where
50        Octs: AsRef<[u8]>,
51        R: RangeBounds<usize>
52    {
53        match Self::_try_with_range(octets, range) {
54            Ok(p) => p,
55            Err(e) => panic!("{}", e)
56        }
57    }
58
59    /// Creates a new parser only using a range if possible.
60    ///
61    /// If `range` is decreasing or out of bounds, returns an Error.
62    pub fn try_with_range<R>(
63        octets: &'a Octs, range: R
64    ) -> Option<Self>
65    where
66        Octs: AsRef<[u8]>,
67        R: RangeBounds<usize>
68    {
69        Self::_try_with_range(octets, range).ok()
70    }
71
72    /// Creates a new parser only using a range if possible.
73    ///
74    /// If `range` is decreasing or out of bounds, returns an Error.
75    fn _try_with_range<R>(
76        octets: &'a Octs, range: R
77    ) -> Result<Self, &'static str>
78    where
79        Octs: AsRef<[u8]>,
80        R: RangeBounds<usize>
81    {
82        let octets_len = octets.as_ref().len();
83
84        let pos = match range.start_bound() {
85            Bound::Unbounded => 0,
86            Bound::Included(n) => *n,
87            Bound::Excluded(n) => *n + 1,
88        };
89
90        if pos > octets_len {
91            return Err("range start is out of range for octets")
92        }
93
94        let len = match range.end_bound() {
95            Bound::Unbounded => octets_len,
96            Bound::Excluded(n) => *n,
97            Bound::Included(n) => *n + 1,
98        };
99
100        if len > octets_len {
101            return Err("range end is out of range for octets")
102        }
103
104        if len < pos {
105            return Err("range starts after end")
106        }
107
108        Ok(
109            Parser {
110                pos,
111                len,
112                octets
113            }
114        )
115
116    }
117
118
119
120    /// Returns the wrapped reference to the underlying octets sequence.
121    pub fn octets_ref(&self) -> &'a Octs {
122        self.octets
123    }
124
125    /// Returns the current parse position as an index into the octets.
126    pub fn pos(&self) -> usize {
127        self.pos
128    }
129
130    /// Returns the length of the underlying octet sequence.
131    ///
132    /// This is _not_ the number of octets left for parsing. Use
133    /// [`Parser::remaining`] for that.
134    pub fn len(&self) -> usize {
135        self.len
136    }
137
138    /// Returns whether the underlying octets sequence is empty.
139    ///
140    /// This does _not_ return whether there are no more octets left to parse.
141    pub fn is_empty(&self) -> bool {
142        self.len == 0
143    }
144}
145
146impl Parser<'static, [u8]> {
147    /// Creates a new parser atop a static byte slice.
148    ///
149    /// This function is most useful for testing.
150    pub fn from_static(slice: &'static [u8]) -> Self {
151        Self::from_ref(slice)
152    }
153}
154
155impl<'a, Octs: AsRef<[u8]> + ?Sized> Parser<'a, Octs> {
156    /// Returns an octets slice of the underlying sequence.
157    ///
158    /// The slice covers the entire sequence, not just the remaining data. You
159    /// can use [`Parser::peek`] for that.
160    pub fn as_slice(&self) -> &[u8] {
161        &self.octets.as_ref()[..self.len]
162    }
163
164    /// Returns the number of remaining octets to parse.
165    pub fn remaining(&self) -> usize {
166        self.len - self.pos
167    }
168
169    /// Returns a slice for the next `len` octets.
170    ///
171    /// If less than `len` octets are left, returns an error.
172    pub fn peek(&self, len: usize) -> Result<&[u8], ShortInput> {
173        self.check_len(len)?;
174        Ok(&self.peek_all()[..len])
175    }
176
177    /// Returns a slice of the data left to parse.
178    pub fn peek_all(&self) -> &[u8] {
179        &self.octets.as_ref()[self.pos..self.len]
180    }
181
182    /// Repositions the parser to the given index.
183    ///
184    /// It is okay to reposition anywhere within the sequence. However,
185    /// if `pos` is larger than the length of the sequence, an error is
186    /// returned.
187    pub fn seek(&mut self, pos: usize) -> Result<(), ShortInput> {
188        if pos > self.len {
189            Err(ShortInput(()))
190        } else {
191            self.pos = pos;
192            Ok(())
193        }
194    }
195
196    /// Advances the parser‘s position by `len` octets.
197    ///
198    /// If this would take the parser beyond its end, an error is returned.
199    pub fn advance(&mut self, len: usize) -> Result<(), ShortInput> {
200        if len > self.remaining() {
201            Err(ShortInput(()))
202        } else {
203            self.pos += len;
204            Ok(())
205        }
206    }
207
208    /// Advances to the end of the parser.
209    pub fn advance_to_end(&mut self) {
210        self.pos = self.len
211    }
212
213    /// Checks that there are `len` octets left to parse.
214    ///
215    /// If there aren’t, returns an error.
216    pub fn check_len(&self, len: usize) -> Result<(), ShortInput> {
217        if self.remaining() < len {
218            Err(ShortInput(()))
219        } else {
220            Ok(())
221        }
222    }
223}
224
225impl<'a, Octs: AsRef<[u8]> + ?Sized> Parser<'a, Octs> {
226    /// Takes and returns the next `len` octets.
227    ///
228    /// Advances the parser by `len` octets. If there aren’t enough octets
229    /// left, leaves the parser untouched and returns an error instead.
230    pub fn parse_octets(
231        &mut self,
232        len: usize,
233    ) -> Result<Octs::Range<'a>, ShortInput>
234    where
235        Octs: Octets,
236    {
237        let end = self.pos + len;
238        if end > self.len {
239            return Err(ShortInput(()));
240        }
241        let res = self.octets.range(self.pos..end);
242        self.pos = end;
243        Ok(res)
244    }
245
246    /// Fills the provided buffer by taking octets from the parser.
247    ///
248    /// Copies as many octets as the buffer is long from the parser into the
249    /// buffer and advances the parser by that many octets.
250    ///
251    /// If there aren’t enough octets left in the parser to fill the buffer
252    /// completely, returns an error and leaves the parser untouched.
253    pub fn parse_buf(&mut self, buf: &mut [u8]) -> Result<(), ShortInput> {
254        let pos = self.pos;
255        self.advance(buf.len())?;
256        buf.copy_from_slice(&self.octets.as_ref()[pos..self.pos]);
257        Ok(())
258    }
259
260    /// Takes as many octets as requested and returns a parser for them.
261    ///
262    /// If enough octets are remaining, the method clones `self`, limits
263    /// its length to the requested number of octets, and returns it. The
264    /// returned parser will be positioned at wherever `self` was positioned.
265    /// The `self` parser will be advanced by the requested amount of octets.
266    ///
267    /// If there aren’t enough octets left in the parser to fill the buffer
268    /// completely, returns an error and leaves the parser untouched.
269    pub fn parse_parser(&mut self, len: usize) -> Result<Self, ShortInput> {
270        self.check_len(len)?;
271        let mut res = *self;
272        res.len = res.pos + len;
273        self.pos += len;
274        Ok(res)
275    }
276
277    /// Takes an `i8` from the beginning of the parser.
278    ///
279    /// Advances the parser by one octet. If there aren’t enough octets left,
280    /// leaves the parser untouched and returns an error instead.
281    pub fn parse_i8(&mut self) -> Result<i8, ShortInput> {
282        let res = self.peek(1)?[0] as i8;
283        self.pos += 1;
284        Ok(res)
285    }
286
287    /// Takes a `u8` from the beginning of the parser.
288    ///
289    /// Advances the parser by one octet. If there aren’t enough octets left,
290    /// leaves the parser untouched and returns an error instead.
291    pub fn parse_u8(&mut self) -> Result<u8, ShortInput> {
292        let res = self.peek(1)?[0];
293        self.pos += 1;
294        Ok(res)
295    }
296}
297
298impl<'a, Octs: AsRef<[u8]> + ?Sized> Parser<'a, Octs> {
299    /// Takes a big-endian `i16` from the beginning of the parser.
300    ///
301    /// The value is converted into the system’s own byte order if necessary.
302    /// The parser is advanced by two octets. If there aren’t enough octets
303    /// left, leaves the parser untouched and returns an error instead.
304    pub fn parse_i16_be(&mut self) -> Result<i16, ShortInput> {
305        let mut res = [0; 2];
306        self.parse_buf(&mut res)?;
307        Ok(i16::from_be_bytes(res))
308    }
309
310    /// Takes a little-endian `i16` from the beginning of the parser.
311    ///
312    /// The value is converted into the system’s own byte order if necessary.
313    /// The parser is advanced by two octets. If there aren’t enough octets
314    /// left, leaves the parser untouched and returns an error instead.
315    pub fn parse_i16_le(&mut self) -> Result<i16, ShortInput> {
316        let mut res = [0; 2];
317        self.parse_buf(&mut res)?;
318        Ok(i16::from_le_bytes(res))
319    }
320
321    /// Takes a big-endian `u16` from the beginning of the parser.
322    ///
323    /// The value is converted into the system’s own byte order if necessary.
324    /// The parser is advanced by two octets. If there aren’t enough octets
325    /// left, leaves the parser untouched and returns an error instead.
326    pub fn parse_u16_be(&mut self) -> Result<u16, ShortInput> {
327        let mut res = [0; 2];
328        self.parse_buf(&mut res)?;
329        Ok(u16::from_be_bytes(res))
330    }
331
332    /// Takes a little-endian `u16` from the beginning of the parser.
333    ///
334    /// The value is converted into the system’s own byte order if necessary.
335    /// The parser is advanced by two octets. If there aren’t enough octets
336    /// left, leaves the parser untouched and returns an error instead.
337    pub fn parse_u16_le(&mut self) -> Result<u16, ShortInput> {
338        let mut res = [0; 2];
339        self.parse_buf(&mut res)?;
340        Ok(u16::from_le_bytes(res))
341    }
342
343    /// Takes a big-endian `i32` from the beginning of the parser.
344    ///
345    /// The value is converted into the system’s own byte order if necessary.
346    /// The parser is advanced by four octets. If there aren’t enough octets
347    /// left, leaves the parser untouched and returns an error instead.
348    pub fn parse_i32_be(&mut self) -> Result<i32, ShortInput> {
349        let mut res = [0; 4];
350        self.parse_buf(&mut res)?;
351        Ok(i32::from_be_bytes(res))
352    }
353
354    /// Takes a little-endian `i32` from the beginning of the parser.
355    ///
356    /// The value is converted into the system’s own byte order if necessary.
357    /// The parser is advanced by four octets. If there aren’t enough octets
358    /// left, leaves the parser untouched and returns an error instead.
359    pub fn parse_i32_le(&mut self) -> Result<i32, ShortInput> {
360        let mut res = [0; 4];
361        self.parse_buf(&mut res)?;
362        Ok(i32::from_le_bytes(res))
363    }
364
365    /// Takes a big-endian `u32` from the beginning of the parser.
366    ///
367    /// The value is converted into the system’s own byte order if necessary.
368    /// The parser is advanced by four octets. If there aren’t enough octets
369    /// left, leaves the parser untouched and returns an error instead.
370    pub fn parse_u32_be(&mut self) -> Result<u32, ShortInput> {
371        let mut res = [0; 4];
372        self.parse_buf(&mut res)?;
373        Ok(u32::from_be_bytes(res))
374    }
375
376    /// Takes a little-endian `u32` from the beginning of the parser.
377    ///
378    /// The value is converted into the system’s own byte order if necessary.
379    /// The parser is advanced by four octets. If there aren’t enough octets
380    /// left, leaves the parser untouched and returns an error instead.
381    pub fn parse_u32_le(&mut self) -> Result<u32, ShortInput> {
382        let mut res = [0; 4];
383        self.parse_buf(&mut res)?;
384        Ok(u32::from_le_bytes(res))
385    }
386
387    /// Takes a big-endian `i64` from the beginning of the parser.
388    ///
389    /// The value is converted into the system’s own byte order if necessary.
390    /// The parser is advanced by eight octets. If there aren’t enough octets
391    /// left, leaves the parser untouched and returns an error instead.
392    pub fn parse_i64_be(&mut self) -> Result<i64, ShortInput> {
393        let mut res = [0; 8];
394        self.parse_buf(&mut res)?;
395        Ok(i64::from_be_bytes(res))
396    }
397
398    /// Takes a little-endian `i64` from the beginning of the parser.
399    ///
400    /// The value is converted into the system’s own byte order if necessary.
401    /// The parser is advanced by eight octets. If there aren’t enough octets
402    /// left, leaves the parser untouched and returns an error instead.
403    pub fn parse_i64_le(&mut self) -> Result<i64, ShortInput> {
404        let mut res = [0; 8];
405        self.parse_buf(&mut res)?;
406        Ok(i64::from_le_bytes(res))
407    }
408
409    /// Takes a big-endian `u64` from the beginning of the parser.
410    ///
411    /// The value is converted into the system’s own byte order if necessary.
412    /// The parser is advanced by eight octets. If there aren’t enough octets
413    /// left, leaves the parser untouched and returns an error instead.
414    pub fn parse_u64_be(&mut self) -> Result<u64, ShortInput> {
415        let mut res = [0; 8];
416        self.parse_buf(&mut res)?;
417        Ok(u64::from_be_bytes(res))
418    }
419
420    /// Takes a little-endian `u64` from the beginning of the parser.
421    ///
422    /// The value is converted into the system’s own byte order if necessary.
423    /// The parser is advanced by eight octets. If there aren’t enough octets
424    /// left, leaves the parser untouched and returns an error instead.
425    pub fn parse_u64_le(&mut self) -> Result<u64, ShortInput> {
426        let mut res = [0; 8];
427        self.parse_buf(&mut res)?;
428        Ok(u64::from_le_bytes(res))
429    }
430
431    /// Takes a big-endian `i128` from the beginning of the parser.
432    ///
433    /// The value is converted into the system’s own byte order if necessary.
434    /// The parser is advanced by 16 octets. If there aren’t enough octets
435    /// left, leaves the parser untouched and returns an error instead.
436    pub fn parse_i128_be(&mut self) -> Result<i128, ShortInput> {
437        let mut res = [0; 16];
438        self.parse_buf(&mut res)?;
439        Ok(i128::from_be_bytes(res))
440    }
441
442    /// Takes a little-endian `i128` from the beginning of the parser.
443    ///
444    /// The value is converted into the system’s own byte order if necessary.
445    /// The parser is advanced by 16 octets. If there aren’t enough octets
446    /// left, leaves the parser untouched and returns an error instead.
447    pub fn parse_i128_le(&mut self) -> Result<i128, ShortInput> {
448        let mut res = [0; 16];
449        self.parse_buf(&mut res)?;
450        Ok(i128::from_le_bytes(res))
451    }
452
453    /// Takes a big-endian `u128` from the beginning of the parser.
454    ///
455    /// The value is converted into the system’s own byte order if necessary.
456    /// The parser is advanced by 16 octets. If there aren’t enough octets
457    /// left, leaves the parser untouched and returns an error instead.
458    pub fn parse_u128_be(&mut self) -> Result<u128, ShortInput> {
459        let mut res = [0; 16];
460        self.parse_buf(&mut res)?;
461        Ok(u128::from_be_bytes(res))
462    }
463
464    /// Takes a little-endian `u128` from the beginning of the parser.
465    ///
466    /// The value is converted into the system’s own byte order if necessary.
467    /// The parser is advanced by 16 octets. If there aren’t enough octets
468    /// left, leaves the parser untouched and returns an error instead.
469    pub fn parse_u128_le(&mut self) -> Result<u128, ShortInput> {
470        let mut res = [0; 16];
471        self.parse_buf(&mut res)?;
472        Ok(u128::from_le_bytes(res))
473    }
474}
475
476
477//--- Clone and Copy
478
479impl<'a, Octs: ?Sized> Clone for Parser<'a, Octs> {
480    fn clone(&self) -> Self {
481        *self
482    }
483}
484
485impl<'a, Octs: ?Sized> Copy for Parser<'a, Octs> { }
486
487
488//--------- ShortInput -------------------------------------------------------
489
490/// An attempt was made to go beyond the end of the parser.
491#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
492pub struct ShortInput(());
493
494//--- Display and Error
495
496impl fmt::Display for ShortInput {
497    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
498        f.write_str("unexpected end of input")
499    }
500}
501
502#[cfg(feature = "std")]
503impl std::error::Error for ShortInput {}
504
505
506//============ Testing =======================================================
507
508#[cfg(test)]
509mod test {
510    use super::*;
511
512    #[test]
513    fn pos_seek_remaining() {
514        let mut parser = Parser::from_static(b"0123456789");
515        assert_eq!(parser.peek(1).unwrap(), b"0");
516        assert_eq!(parser.pos(), 0);
517        assert_eq!(parser.remaining(), 10);
518        assert_eq!(parser.seek(2), Ok(()));
519        assert_eq!(parser.pos(), 2);
520        assert_eq!(parser.remaining(), 8);
521        assert_eq!(parser.peek(1).unwrap(), b"2");
522        assert_eq!(parser.seek(10), Ok(()));
523        assert_eq!(parser.pos(), 10);
524        assert_eq!(parser.remaining(), 0);
525        assert_eq!(parser.peek_all(), b"");
526        assert!(parser.seek(11).is_err());
527        assert_eq!(parser.pos(), 10);
528        assert_eq!(parser.remaining(), 0);
529    }
530
531    #[test]
532    fn peek_check_len() {
533        let mut parser = Parser::from_static(b"0123456789");
534        assert_eq!(parser.peek(2), Ok(b"01".as_ref()));
535        assert_eq!(parser.check_len(2), Ok(()));
536        assert_eq!(parser.peek(10), Ok(b"0123456789".as_ref()));
537        assert_eq!(parser.check_len(10), Ok(()));
538        assert!(parser.peek(11).is_err());
539        assert!(parser.check_len(11).is_err());
540        parser.advance(2).unwrap();
541        assert_eq!(parser.peek(2), Ok(b"23".as_ref()));
542        assert_eq!(parser.check_len(2), Ok(()));
543        assert_eq!(parser.peek(8), Ok(b"23456789".as_ref()));
544        assert_eq!(parser.check_len(8), Ok(()));
545        assert!(parser.peek(9).is_err());
546        assert!(parser.check_len(9).is_err());
547    }
548
549    #[test]
550    fn peek_all() {
551        let mut parser = Parser::from_static(b"0123456789");
552        assert_eq!(parser.peek_all(), b"0123456789");
553        parser.advance(2).unwrap();
554        assert_eq!(parser.peek_all(), b"23456789");
555
556        let mut pp = parser.parse_parser(4).unwrap();
557        assert_eq!(pp.peek_all(), b"2345");
558        pp.advance(2).unwrap();
559        assert_eq!(pp.peek_all(), b"45");
560
561        assert_eq!(parser.peek_all(), b"6789");
562    }
563
564    #[test]
565    fn advance() {
566        let mut parser = Parser::from_static(b"0123456789");
567        assert_eq!(parser.pos(), 0);
568        assert_eq!(parser.peek(1).unwrap(), b"0");
569        assert_eq!(parser.advance(2), Ok(()));
570        assert_eq!(parser.pos(), 2);
571        assert_eq!(parser.peek(1).unwrap(), b"2");
572        assert!(parser.advance(9).is_err());
573        assert_eq!(parser.advance(8), Ok(()));
574        assert_eq!(parser.pos(), 10);
575        assert_eq!(parser.peek_all(), b"");
576    }
577
578    #[test]
579    fn parse_octets() {
580        let mut parser = Parser::from_static(b"0123456789");
581        assert_eq!(parser.parse_octets(2).unwrap(), b"01");
582        assert_eq!(parser.parse_octets(2).unwrap(), b"23");
583        assert!(parser.parse_octets(7).is_err());
584        assert_eq!(parser.parse_octets(6).unwrap(), b"456789");
585    }
586
587    #[test]
588    fn parse_buf() {
589        let mut parser = Parser::from_static(b"0123456789");
590        let mut buf = [0u8; 2];
591        assert_eq!(parser.parse_buf(&mut buf), Ok(()));
592        assert_eq!(&buf, b"01");
593        assert_eq!(parser.parse_buf(&mut buf), Ok(()));
594        assert_eq!(&buf, b"23");
595        let mut buf = [0u8; 7];
596        assert!(parser.parse_buf(&mut buf).is_err());
597        let mut buf = [0u8; 6];
598        assert_eq!(parser.parse_buf(&mut buf), Ok(()));
599        assert_eq!(&buf, b"456789");
600    }
601
602    #[test]
603    fn parse_i8() {
604        let mut parser = Parser::from_static(b"\x12\xd6");
605        assert_eq!(parser.parse_i8(), Ok(0x12_i8));
606        assert_eq!(parser.parse_i8(), Ok(-42_i8));
607        assert!(parser.parse_i8().is_err());
608    }
609
610    #[test]
611    fn parse_u8() {
612        let mut parser = Parser::from_static(b"\x12\xd6");
613        assert_eq!(parser.parse_u8(), Ok(0x12_u8));
614        assert_eq!(parser.parse_u8(), Ok(0xd6_u8));
615        assert!(parser.parse_u8().is_err());
616    }
617
618    #[test]
619    fn parse_i16_be() {
620        let mut parser = Parser::from_static(b"\x12\x34\xef\x6e\0");
621        assert_eq!(parser.parse_i16_be(), Ok(0x1234_i16));
622        assert_eq!(parser.parse_i16_be(), Ok(-4242_i16));
623        assert!(parser.parse_i16_be().is_err());
624    }
625
626    #[test]
627    fn parse_i16_le() {
628        let mut parser = Parser::from_static(b"\x34\x12\x6e\xef\0");
629        assert_eq!(parser.parse_i16_le(), Ok(0x1234_i16));
630        assert_eq!(parser.parse_i16_le(), Ok(-4242_i16));
631        assert!(parser.parse_i16_le().is_err());
632    }
633
634    #[test]
635    fn parse_u16_be() {
636        let mut parser = Parser::from_static(b"\x12\x34\xef\x6e\0");
637        assert_eq!(parser.parse_u16_be(), Ok(0x1234_u16));
638        assert_eq!(parser.parse_u16_be(), Ok(0xef6e_u16));
639        assert!(parser.parse_u16_be().is_err());
640    }
641
642    #[test]
643    fn parse_u16_le() {
644        let mut parser = Parser::from_static(b"\x34\x12\x6e\xef\0");
645        assert_eq!(parser.parse_u16_le(), Ok(0x1234_u16));
646        assert_eq!(parser.parse_u16_le(), Ok(0xef6e_u16));
647        assert!(parser.parse_u16_le().is_err());
648    }
649
650    #[test]
651    fn parse_i32_be() {
652        let mut parser =
653            Parser::from_static(b"\x12\x34\x56\x78\xfd\x78\xa8\x4e\0\0\0");
654        assert_eq!(parser.parse_i32_be(), Ok(0x12345678_i32));
655        assert_eq!(parser.parse_i32_be(), Ok(-42424242_i32));
656        assert!(parser.parse_i32_be().is_err());
657    }
658
659    #[test]
660    fn parse_i32_le() {
661        let mut parser =
662            Parser::from_static(b"\x78\x56\x34\x12\x4e\xa8\x78\xfd\0\0\0");
663        assert_eq!(parser.parse_i32_le(), Ok(0x12345678_i32));
664        assert_eq!(parser.parse_i32_le(), Ok(-42424242_i32));
665        assert!(parser.parse_i32_le().is_err());
666    }
667
668    #[test]
669    fn parse_u32_be() {
670        let mut parser =
671            Parser::from_static(b"\x12\x34\x56\x78\xfd\x78\xa8\x4e\0\0\0");
672        assert_eq!(parser.parse_u32_be(), Ok(0x12345678_u32));
673        assert_eq!(parser.parse_u32_be(), Ok(0xfd78a84e_u32));
674        assert!(parser.parse_u32_be().is_err());
675    }
676
677    #[test]
678    fn parse_u32_le() {
679        let mut parser =
680            Parser::from_static(b"\x78\x56\x34\x12\x4e\xa8\x78\xfd\0\0\0");
681        assert_eq!(parser.parse_u32_le(), Ok(0x12345678_u32));
682        assert_eq!(parser.parse_u32_le(), Ok(0xfd78a84e_u32));
683        assert!(parser.parse_u32_le().is_err());
684    }
685
686    #[test]
687    fn parse_i64_be() {
688        let mut parser = Parser::from_static(
689            b"\x12\x34\x56\x78\xfd\x78\xa8\x4e\
690              \xce\x7a\xba\x26\xdd\x0f\x29\x99\
691              \0\0\0"
692        );
693        assert_eq!(parser.parse_i64_be(), Ok(0x12345678fd78a84e_i64));
694        assert_eq!(parser.parse_i64_be(), Ok(-3568335078657414759_i64));
695        assert!(parser.parse_i64_be().is_err());
696    }
697
698    #[test]
699    fn parse_i64_le() {
700        let mut parser = Parser::from_static(
701            b"\x4e\xa8\x78\xfd\x78\x56\x34\x12\
702              \x99\x29\x0f\xdd\x26\xba\x7a\xce\
703              \0\0\0"
704        );
705        assert_eq!(parser.parse_i64_le(), Ok(0x12345678fd78a84e_i64));
706        assert_eq!(parser.parse_i64_le(), Ok(-3568335078657414759_i64));
707        assert!(parser.parse_i64_le().is_err());
708    }
709
710    #[test]
711    fn parse_u64_be() {
712        let mut parser = Parser::from_static(
713            b"\x12\x34\x56\x78\xfd\x78\xa8\x4e\
714              \xce\x7a\xba\x26\xdd\x0f\x29\x99\
715              \0\0\0"
716        );
717        assert_eq!(parser.parse_u64_be(), Ok(0x12345678fd78a84e_u64));
718        assert_eq!(parser.parse_u64_be(), Ok(0xce7aba26dd0f2999_u64));
719        assert!(parser.parse_u64_be().is_err());
720    }
721
722    #[test]
723    fn parse_u64_le() {
724        let mut parser = Parser::from_static(
725            b"\x4e\xa8\x78\xfd\x78\x56\x34\x12\
726              \x99\x29\x0f\xdd\x26\xba\x7a\xce\
727              \0\0\0"
728        );
729        assert_eq!(parser.parse_u64_le(), Ok(0x12345678fd78a84e_u64));
730        assert_eq!(parser.parse_u64_le(), Ok(0xce7aba26dd0f2999_u64));
731        assert!(parser.parse_u64_le().is_err());
732    }
733
734    #[test]
735    fn parse_i128_be() {
736        let mut parser = Parser::from_static(
737            b"\x12\x34\x56\x78\xfd\x78\xa8\x4e\
738              \xce\x7a\xba\x26\xdd\x0f\x29\x99\
739              \xf8\xc6\x0e\x5d\x3f\x5e\x3a\x74\
740              \x38\x38\x8f\x3f\x57\xa7\x94\xa0\
741              \0\0\0\0\0"
742        );
743        assert_eq!(parser.parse_i128_be(),
744            Ok(0x12345678fd78a84ece7aba26dd0f2999_i128)
745        );
746        assert_eq!(parser.parse_i128_be(),
747            Ok(-9605457846724395475894107919101750112_i128)
748        );
749        assert!(parser.parse_i128_be().is_err());
750    }
751
752    #[test]
753    fn parse_i128_le() {
754        let mut parser = Parser::from_static(
755            b"\x99\x29\x0f\xdd\x26\xba\x7a\xce\
756              \x4e\xa8\x78\xfd\x78\x56\x34\x12\
757              \xa0\x94\xa7\x57\x3f\x8f\x38\x38\
758              \x74\x3a\x5e\x3f\x5d\x0e\xc6\xf8\
759              \0\0\0\0\0"
760        );
761        assert_eq!(parser.parse_i128_le(),
762            Ok(0x12345678fd78a84ece7aba26dd0f2999_i128)
763        );
764        assert_eq!(parser.parse_i128_le(),
765            Ok(-9605457846724395475894107919101750112_i128)
766        );
767        assert!(parser.parse_i128_le().is_err());
768    }
769
770    #[test]
771    fn parse_u128_be() {
772        let mut parser = Parser::from_static(
773            b"\x12\x34\x56\x78\xfd\x78\xa8\x4e\
774              \xce\x7a\xba\x26\xdd\x0f\x29\x99\
775              \xf8\xc6\x0e\x5d\x3f\x5e\x3a\x74\
776              \x38\x38\x8f\x3f\x57\xa7\x94\xa0\
777              \0\0\0\0\0"
778        );
779        assert_eq!(parser.parse_u128_be(),
780            Ok(0x12345678fd78a84ece7aba26dd0f2999_u128)
781        );
782        assert_eq!(parser.parse_u128_be(),
783            Ok(0xf8c60e5d3f5e3a7438388f3f57a794a0_u128)
784        );
785        assert!(parser.parse_u128_be().is_err());
786    }
787
788    #[test]
789    fn parse_u128_le() {
790        let mut parser = Parser::from_static(
791            b"\x99\x29\x0f\xdd\x26\xba\x7a\xce\
792              \x4e\xa8\x78\xfd\x78\x56\x34\x12\
793              \xa0\x94\xa7\x57\x3f\x8f\x38\x38\
794              \x74\x3a\x5e\x3f\x5d\x0e\xc6\xf8\
795              \0\0\0\0\0"
796        );
797        assert_eq!(parser.parse_u128_le(),
798            Ok(0x12345678fd78a84ece7aba26dd0f2999_u128)
799        );
800        assert_eq!(parser.parse_u128_le(),
801            Ok(0xf8c60e5d3f5e3a7438388f3f57a794a0_u128)
802        );
803        assert!(parser.parse_u128_le().is_err());
804    }
805
806    #[test]
807    fn with_range() {
808        let range = [0, 1, 2, 3, 4, 5_usize];
809        let slice = &[1, 2, 3];
810
811        for start in range {
812            for end in range {
813                for start in [
814                    Bound::Unbounded,
815                    Bound::Included(start),
816                    Bound::Excluded(start)
817                ] {
818                    for end in [
819                        Bound::Unbounded,
820                        Bound::Included(end),
821                        Bound::Excluded(end)
822                    ] {
823                        let bounds = (start, end);
824                        assert_eq!(
825                            slice.get(bounds),
826                            Parser::try_with_range(
827                                slice, bounds
828                            ).as_ref().map(|p| p.peek_all()),
829                            "{:?}", bounds
830                        );
831                    }
832                }
833            }
834        }
835    }
836}