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