octets/
lib.rs

1// Copyright (C) 2018-2019, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright notice,
9//       this list of conditions and the following disclaimer.
10//
11//     * Redistributions in binary form must reproduce the above copyright
12//       notice, this list of conditions and the following disclaimer in the
13//       documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27/// Zero-copy abstraction for parsing and constructing network packets.
28use std::mem;
29use std::ptr;
30
31/// A specialized [`Result`] type for [`OctetsMut`] operations.
32///
33/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
34/// [`OctetsMut`]: struct.OctetsMut.html
35pub type Result<T> = std::result::Result<T, BufferTooShortError>;
36
37/// An error indicating that the provided [`OctetsMut`] is not big enough.
38///
39/// [`OctetsMut`]: struct.OctetsMut.html
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub struct BufferTooShortError;
42
43impl std::fmt::Display for BufferTooShortError {
44    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
45        write!(f, "BufferTooShortError")
46    }
47}
48
49impl std::error::Error for BufferTooShortError {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        None
52    }
53}
54
55/// Helper macro that asserts at compile time. It requires that
56/// `cond` is a const expression.
57macro_rules! static_assert {
58    ($cond:expr) => {{
59        const _: () = assert!($cond);
60    }};
61}
62
63macro_rules! peek_u {
64    ($b:expr, $ty:ty, $len:expr) => {{
65        let len = $len;
66        let src = &$b.buf[$b.off..];
67
68        if src.len() < len {
69            return Err(BufferTooShortError);
70        }
71
72        static_assert!($len <= mem::size_of::<$ty>());
73        let mut out: $ty = 0;
74        unsafe {
75            let dst = &mut out as *mut $ty as *mut u8;
76            let off = (mem::size_of::<$ty>() - len) as isize;
77
78            ptr::copy_nonoverlapping(src.as_ptr(), dst.offset(off), len);
79        };
80
81        Ok(<$ty>::from_be(out))
82    }};
83}
84
85macro_rules! get_u {
86    ($b:expr, $ty:ty, $len:expr) => {{
87        let out = peek_u!($b, $ty, $len);
88
89        $b.off += $len;
90
91        out
92    }};
93}
94
95macro_rules! put_u {
96    ($b:expr, $ty:ty, $v:expr, $len:expr) => {{
97        let len = $len;
98
99        if $b.buf.len() < $b.off + len {
100            return Err(BufferTooShortError);
101        }
102
103        let v = $v;
104
105        let dst = &mut $b.buf[$b.off..($b.off + len)];
106
107        static_assert!($len <= mem::size_of::<$ty>());
108        unsafe {
109            let src = &<$ty>::to_be(v) as *const $ty as *const u8;
110            let off = (mem::size_of::<$ty>() - len) as isize;
111
112            ptr::copy_nonoverlapping(src.offset(off), dst.as_mut_ptr(), len);
113        }
114
115        $b.off += $len;
116
117        Ok(dst)
118    }};
119}
120
121/// A zero-copy immutable byte buffer.
122///
123/// `Octets` wraps an in-memory buffer of bytes and provides utility functions
124/// for manipulating it. The underlying buffer is provided by the user and is
125/// not copied when creating an `Octets`. Operations are panic-free and will
126/// avoid indexing the buffer past its end.
127///
128/// Additionally, an offset (initially set to the start of the buffer) is
129/// incremented as bytes are read from / written to the buffer, to allow for
130/// sequential operations.
131#[derive(Debug, PartialEq, Eq)]
132pub struct Octets<'a> {
133    buf: &'a [u8],
134    off: usize,
135}
136
137impl<'a> Octets<'a> {
138    /// Creates an `Octets` from the given slice, without copying.
139    ///
140    /// Since the `Octets` is immutable, the input slice needs to be
141    /// immutable.
142    pub fn with_slice(buf: &'a [u8]) -> Self {
143        Octets { buf, off: 0 }
144    }
145
146    /// Reads an unsigned 8-bit integer from the current offset and advances
147    /// the buffer.
148    pub fn get_u8(&mut self) -> Result<u8> {
149        get_u!(self, u8, 1)
150    }
151
152    /// Reads an unsigned 8-bit integer from the current offset without
153    /// advancing the buffer.
154    pub fn peek_u8(&mut self) -> Result<u8> {
155        peek_u!(self, u8, 1)
156    }
157
158    /// Reads an unsigned 16-bit integer in network byte-order from the current
159    /// offset and advances the buffer.
160    pub fn get_u16(&mut self) -> Result<u16> {
161        get_u!(self, u16, 2)
162    }
163
164    /// Reads an unsigned 24-bit integer in network byte-order from the current
165    /// offset and advances the buffer.
166    pub fn get_u24(&mut self) -> Result<u32> {
167        get_u!(self, u32, 3)
168    }
169
170    /// Reads an unsigned 32-bit integer in network byte-order from the current
171    /// offset and advances the buffer.
172    pub fn get_u32(&mut self) -> Result<u32> {
173        get_u!(self, u32, 4)
174    }
175
176    /// Reads an unsigned 64-bit integer in network byte-order from the current
177    /// offset and advances the buffer.
178    pub fn get_u64(&mut self) -> Result<u64> {
179        get_u!(self, u64, 8)
180    }
181
182    /// Reads an unsigned variable-length integer in network byte-order from
183    /// the current offset and advances the buffer.
184    pub fn get_varint(&mut self) -> Result<u64> {
185        let first = self.peek_u8()?;
186
187        let len = varint_parse_len(first);
188
189        if len > self.cap() {
190            return Err(BufferTooShortError);
191        }
192
193        let out = match len {
194            1 => u64::from(self.get_u8()?),
195
196            2 => u64::from(self.get_u16()? & 0x3fff),
197
198            4 => u64::from(self.get_u32()? & 0x3fffffff),
199
200            8 => self.get_u64()? & 0x3fffffffffffffff,
201
202            _ => unreachable!(),
203        };
204
205        Ok(out)
206    }
207
208    /// Reads `len` bytes from the current offset without copying and advances
209    /// the buffer.
210    pub fn get_bytes(&mut self, len: usize) -> Result<Octets<'a>> {
211        if self.cap() < len {
212            return Err(BufferTooShortError);
213        }
214
215        let out = Octets {
216            buf: &self.buf[self.off..self.off + len],
217            off: 0,
218        };
219
220        self.off += len;
221
222        Ok(out)
223    }
224
225    /// Reads `len` bytes from the current offset without copying and advances
226    /// the buffer, where `len` is an unsigned 8-bit integer prefix.
227    pub fn get_bytes_with_u8_length(&mut self) -> Result<Octets<'a>> {
228        let len = self.get_u8()?;
229        self.get_bytes(len as usize)
230    }
231
232    /// Reads `len` bytes from the current offset without copying and advances
233    /// the buffer, where `len` is an unsigned 16-bit integer prefix in network
234    /// byte-order.
235    pub fn get_bytes_with_u16_length(&mut self) -> Result<Octets<'a>> {
236        let len = self.get_u16()?;
237        self.get_bytes(len as usize)
238    }
239
240    /// Reads `len` bytes from the current offset without copying and advances
241    /// the buffer, where `len` is an unsigned variable-length integer prefix
242    /// in network byte-order.
243    pub fn get_bytes_with_varint_length(&mut self) -> Result<Octets<'a>> {
244        let len = self.get_varint()?;
245        self.get_bytes(len as usize)
246    }
247
248    /// Reads `len` bytes from the current offset without copying and without
249    /// advancing the buffer.
250    pub fn peek_bytes(&self, len: usize) -> Result<Octets<'a>> {
251        if self.cap() < len {
252            return Err(BufferTooShortError);
253        }
254
255        let out = Octets {
256            buf: &self.buf[self.off..self.off + len],
257            off: 0,
258        };
259
260        Ok(out)
261    }
262
263    /// Returns a slice of `len` elements from the current offset.
264    pub fn slice(&self, len: usize) -> Result<&'a [u8]> {
265        if len > self.cap() {
266            return Err(BufferTooShortError);
267        }
268
269        Ok(&self.buf[self.off..self.off + len])
270    }
271
272    /// Returns a slice of `len` elements from the end of the buffer.
273    pub fn slice_last(&self, len: usize) -> Result<&'a [u8]> {
274        if len > self.cap() {
275            return Err(BufferTooShortError);
276        }
277
278        let cap = self.cap();
279        Ok(&self.buf[cap - len..])
280    }
281
282    /// Advances the buffer's offset.
283    pub fn skip(&mut self, skip: usize) -> Result<()> {
284        if skip > self.cap() {
285            return Err(BufferTooShortError);
286        }
287
288        self.off += skip;
289
290        Ok(())
291    }
292
293    /// Returns the remaining capacity in the buffer.
294    pub fn cap(&self) -> usize {
295        self.buf.len() - self.off
296    }
297
298    /// Returns the total length of the buffer.
299    pub fn len(&self) -> usize {
300        self.buf.len()
301    }
302
303    /// Returns `true` if the buffer is empty.
304    pub fn is_empty(&self) -> bool {
305        self.buf.len() == 0
306    }
307
308    /// Returns the current offset of the buffer.
309    pub fn off(&self) -> usize {
310        self.off
311    }
312
313    /// Returns a reference to the internal buffer.
314    pub fn buf(&self) -> &'a [u8] {
315        self.buf
316    }
317
318    /// Copies the buffer from the current offset into a new `Vec<u8>`.
319    pub fn to_vec(&self) -> Vec<u8> {
320        self.as_ref().to_vec()
321    }
322}
323
324impl AsRef<[u8]> for Octets<'_> {
325    fn as_ref(&self) -> &[u8] {
326        &self.buf[self.off..]
327    }
328}
329
330/// A zero-copy mutable byte buffer.
331///
332/// Like `Octets` but mutable.
333#[derive(Debug, PartialEq, Eq)]
334pub struct OctetsMut<'a> {
335    buf: &'a mut [u8],
336    off: usize,
337}
338
339impl<'a> OctetsMut<'a> {
340    /// Creates an `OctetsMut` from the given slice, without copying.
341    ///
342    /// Since there's no copy, the input slice needs to be mutable to allow
343    /// modifications.
344    pub fn with_slice(buf: &'a mut [u8]) -> Self {
345        OctetsMut { buf, off: 0 }
346    }
347
348    /// Reads an unsigned 8-bit integer from the current offset and advances
349    /// the buffer.
350    pub fn get_u8(&mut self) -> Result<u8> {
351        get_u!(self, u8, 1)
352    }
353
354    /// Reads an unsigned 8-bit integer from the current offset without
355    /// advancing the buffer.
356    pub fn peek_u8(&mut self) -> Result<u8> {
357        peek_u!(self, u8, 1)
358    }
359
360    /// Writes an unsigned 8-bit integer at the current offset and advances
361    /// the buffer.
362    pub fn put_u8(&mut self, v: u8) -> Result<&mut [u8]> {
363        put_u!(self, u8, v, 1)
364    }
365
366    /// Reads an unsigned 16-bit integer in network byte-order from the current
367    /// offset and advances the buffer.
368    pub fn get_u16(&mut self) -> Result<u16> {
369        get_u!(self, u16, 2)
370    }
371
372    /// Writes an unsigned 16-bit integer in network byte-order at the current
373    /// offset and advances the buffer.
374    pub fn put_u16(&mut self, v: u16) -> Result<&mut [u8]> {
375        put_u!(self, u16, v, 2)
376    }
377
378    /// Reads an unsigned 24-bit integer in network byte-order from the current
379    /// offset and advances the buffer.
380    pub fn get_u24(&mut self) -> Result<u32> {
381        get_u!(self, u32, 3)
382    }
383
384    /// Writes an unsigned 24-bit integer in network byte-order at the current
385    /// offset and advances the buffer.
386    pub fn put_u24(&mut self, v: u32) -> Result<&mut [u8]> {
387        put_u!(self, u32, v, 3)
388    }
389
390    /// Reads an unsigned 32-bit integer in network byte-order from the current
391    /// offset and advances the buffer.
392    pub fn get_u32(&mut self) -> Result<u32> {
393        get_u!(self, u32, 4)
394    }
395
396    /// Writes an unsigned 32-bit integer in network byte-order at the current
397    /// offset and advances the buffer.
398    pub fn put_u32(&mut self, v: u32) -> Result<&mut [u8]> {
399        put_u!(self, u32, v, 4)
400    }
401
402    /// Reads an unsigned 64-bit integer in network byte-order from the current
403    /// offset and advances the buffer.
404    pub fn get_u64(&mut self) -> Result<u64> {
405        get_u!(self, u64, 8)
406    }
407
408    /// Writes an unsigned 64-bit integer in network byte-order at the current
409    /// offset and advances the buffer.
410    pub fn put_u64(&mut self, v: u64) -> Result<&mut [u8]> {
411        put_u!(self, u64, v, 8)
412    }
413
414    /// Reads an unsigned variable-length integer in network byte-order from
415    /// the current offset and advances the buffer.
416    pub fn get_varint(&mut self) -> Result<u64> {
417        let first = self.peek_u8()?;
418
419        let len = varint_parse_len(first);
420
421        if len > self.cap() {
422            return Err(BufferTooShortError);
423        }
424
425        let out = match len {
426            1 => u64::from(self.get_u8()?),
427
428            2 => u64::from(self.get_u16()? & 0x3fff),
429
430            4 => u64::from(self.get_u32()? & 0x3fffffff),
431
432            8 => self.get_u64()? & 0x3fffffffffffffff,
433
434            _ => unreachable!(),
435        };
436
437        Ok(out)
438    }
439
440    /// Writes an unsigned variable-length integer in network byte-order at the
441    /// current offset and advances the buffer.
442    pub fn put_varint(&mut self, v: u64) -> Result<&mut [u8]> {
443        self.put_varint_with_len(v, varint_len(v))
444    }
445
446    /// Writes an unsigned variable-length integer of the specified length, in
447    /// network byte-order at the current offset and advances the buffer.
448    pub fn put_varint_with_len(
449        &mut self, v: u64, len: usize,
450    ) -> Result<&mut [u8]> {
451        if self.cap() < len {
452            return Err(BufferTooShortError);
453        }
454
455        let buf = match len {
456            1 => self.put_u8(v as u8)?,
457
458            2 => {
459                let buf = self.put_u16(v as u16)?;
460                buf[0] |= 0x40;
461                buf
462            },
463
464            4 => {
465                let buf = self.put_u32(v as u32)?;
466                buf[0] |= 0x80;
467                buf
468            },
469
470            8 => {
471                let buf = self.put_u64(v)?;
472                buf[0] |= 0xc0;
473                buf
474            },
475
476            _ => panic!("value is too large for varint"),
477        };
478
479        Ok(buf)
480    }
481
482    /// Reads `len` bytes from the current offset without copying and advances
483    /// the buffer.
484    pub fn get_bytes(&mut self, len: usize) -> Result<Octets> {
485        if self.cap() < len {
486            return Err(BufferTooShortError);
487        }
488
489        let out = Octets {
490            buf: &self.buf[self.off..self.off + len],
491            off: 0,
492        };
493
494        self.off += len;
495
496        Ok(out)
497    }
498
499    /// Reads `len` bytes from the current offset without copying and advances
500    /// the buffer.
501    pub fn get_bytes_mut(&mut self, len: usize) -> Result<OctetsMut> {
502        if self.cap() < len {
503            return Err(BufferTooShortError);
504        }
505
506        let out = OctetsMut {
507            buf: &mut self.buf[self.off..self.off + len],
508            off: 0,
509        };
510
511        self.off += len;
512
513        Ok(out)
514    }
515
516    /// Reads `len` bytes from the current offset without copying and advances
517    /// the buffer, where `len` is an unsigned 8-bit integer prefix.
518    pub fn get_bytes_with_u8_length(&mut self) -> Result<Octets> {
519        let len = self.get_u8()?;
520        self.get_bytes(len as usize)
521    }
522
523    /// Reads `len` bytes from the current offset without copying and advances
524    /// the buffer, where `len` is an unsigned 16-bit integer prefix in network
525    /// byte-order.
526    pub fn get_bytes_with_u16_length(&mut self) -> Result<Octets> {
527        let len = self.get_u16()?;
528        self.get_bytes(len as usize)
529    }
530
531    /// Reads `len` bytes from the current offset without copying and advances
532    /// the buffer, where `len` is an unsigned variable-length integer prefix
533    /// in network byte-order.
534    pub fn get_bytes_with_varint_length(&mut self) -> Result<Octets> {
535        let len = self.get_varint()?;
536        self.get_bytes(len as usize)
537    }
538
539    /// Reads `len` bytes from the current offset without copying and without
540    /// advancing the buffer.
541    pub fn peek_bytes(&mut self, len: usize) -> Result<Octets> {
542        if self.cap() < len {
543            return Err(BufferTooShortError);
544        }
545
546        let out = Octets {
547            buf: &self.buf[self.off..self.off + len],
548            off: 0,
549        };
550
551        Ok(out)
552    }
553
554    /// Reads `len` bytes from the current offset without copying and without
555    /// advancing the buffer.
556    pub fn peek_bytes_mut(&mut self, len: usize) -> Result<OctetsMut> {
557        if self.cap() < len {
558            return Err(BufferTooShortError);
559        }
560
561        let out = OctetsMut {
562            buf: &mut self.buf[self.off..self.off + len],
563            off: 0,
564        };
565
566        Ok(out)
567    }
568
569    /// Writes `len` bytes from the current offset without copying and advances
570    /// the buffer.
571    pub fn put_bytes(&mut self, v: &[u8]) -> Result<()> {
572        let len = v.len();
573
574        if self.cap() < len {
575            return Err(BufferTooShortError);
576        }
577
578        if len == 0 {
579            return Ok(());
580        }
581
582        self.as_mut()[..len].copy_from_slice(v);
583
584        self.off += len;
585
586        Ok(())
587    }
588
589    /// Splits the buffer in two at the given absolute offset.
590    pub fn split_at(&mut self, off: usize) -> Result<(OctetsMut, OctetsMut)> {
591        if self.len() < off {
592            return Err(BufferTooShortError);
593        }
594
595        let (left, right) = self.buf.split_at_mut(off);
596
597        let first = OctetsMut { buf: left, off: 0 };
598
599        let last = OctetsMut { buf: right, off: 0 };
600
601        Ok((first, last))
602    }
603
604    /// Returns a slice of `len` elements from the current offset.
605    pub fn slice(&'a mut self, len: usize) -> Result<&'a mut [u8]> {
606        if len > self.cap() {
607            return Err(BufferTooShortError);
608        }
609
610        Ok(&mut self.buf[self.off..self.off + len])
611    }
612
613    /// Returns a slice of `len` elements from the end of the buffer.
614    pub fn slice_last(&'a mut self, len: usize) -> Result<&'a mut [u8]> {
615        if len > self.cap() {
616            return Err(BufferTooShortError);
617        }
618
619        let cap = self.cap();
620        Ok(&mut self.buf[cap - len..])
621    }
622
623    /// Advances the buffer's offset.
624    pub fn skip(&mut self, skip: usize) -> Result<()> {
625        if skip > self.cap() {
626            return Err(BufferTooShortError);
627        }
628
629        self.off += skip;
630
631        Ok(())
632    }
633
634    /// Returns the remaining capacity in the buffer.
635    pub fn cap(&self) -> usize {
636        self.buf.len() - self.off
637    }
638
639    /// Returns the total length of the buffer.
640    pub fn len(&self) -> usize {
641        self.buf.len()
642    }
643
644    /// Returns `true` if the buffer is empty.
645    pub fn is_empty(&self) -> bool {
646        self.buf.len() == 0
647    }
648
649    /// Returns the current offset of the buffer.
650    pub fn off(&self) -> usize {
651        self.off
652    }
653
654    /// Returns a reference to the internal buffer.
655    pub fn buf(&self) -> &[u8] {
656        self.buf
657    }
658
659    /// Copies the buffer from the current offset into a new `Vec<u8>`.
660    pub fn to_vec(&self) -> Vec<u8> {
661        self.as_ref().to_vec()
662    }
663}
664
665impl AsRef<[u8]> for OctetsMut<'_> {
666    fn as_ref(&self) -> &[u8] {
667        &self.buf[self.off..]
668    }
669}
670
671impl AsMut<[u8]> for OctetsMut<'_> {
672    fn as_mut(&mut self) -> &mut [u8] {
673        &mut self.buf[self.off..]
674    }
675}
676
677/// Returns how many bytes it would take to encode `v` as a variable-length
678/// integer.
679pub const fn varint_len(v: u64) -> usize {
680    if v <= 63 {
681        1
682    } else if v <= 16383 {
683        2
684    } else if v <= 1_073_741_823 {
685        4
686    } else if v <= 4_611_686_018_427_387_903 {
687        8
688    } else {
689        unreachable!()
690    }
691}
692
693/// Returns how long the variable-length integer is, given its first byte.
694pub const fn varint_parse_len(first: u8) -> usize {
695    match first >> 6 {
696        0 => 1,
697        1 => 2,
698        2 => 4,
699        3 => 8,
700        _ => unreachable!(),
701    }
702}
703
704/// The functions in this mod test the compile time assertions in the
705/// `put_u` and `peek_u` macros. If you compile this crate with
706/// `--cfg test_invalid_len_compilation_fail`, e.g., by using
707/// `cargo rustc  -- --cfg test_invalid_len_compilation_fail`
708/// You will get two compiler errors
709#[cfg(test_invalid_len_compilation_fail)]
710pub mod fails_to_compile {
711    use super::*;
712    pub fn peek_invalid_fails_to_compile(b: &mut Octets) -> Result<u8> {
713        peek_u!(b, u8, 2)
714    }
715
716    pub fn put_invalid_fails_to_compile<'a>(
717        b: &'a mut OctetsMut, v: u8,
718    ) -> Result<&'a mut [u8]> {
719        put_u!(b, u8, v, 2)
720    }
721}
722
723#[cfg(test)]
724mod tests {
725    use super::*;
726
727    #[test]
728    fn get_u() {
729        let d = [
730            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
731        ];
732
733        let mut b = Octets::with_slice(&d);
734        assert_eq!(b.cap(), 18);
735        assert_eq!(b.off(), 0);
736
737        assert_eq!(b.get_u8().unwrap(), 1);
738        assert_eq!(b.cap(), 17);
739        assert_eq!(b.off(), 1);
740
741        assert_eq!(b.get_u16().unwrap(), 0x203);
742        assert_eq!(b.cap(), 15);
743        assert_eq!(b.off(), 3);
744
745        assert_eq!(b.get_u24().unwrap(), 0x40506);
746        assert_eq!(b.cap(), 12);
747        assert_eq!(b.off(), 6);
748
749        assert_eq!(b.get_u32().unwrap(), 0x0708090a);
750        assert_eq!(b.cap(), 8);
751        assert_eq!(b.off(), 10);
752
753        assert_eq!(b.get_u64().unwrap(), 0x0b0c0d0e0f101112);
754        assert_eq!(b.cap(), 0);
755        assert_eq!(b.off(), 18);
756
757        assert!(b.get_u8().is_err());
758        assert!(b.get_u16().is_err());
759        assert!(b.get_u24().is_err());
760        assert!(b.get_u32().is_err());
761        assert!(b.get_u64().is_err());
762    }
763
764    #[test]
765    fn get_u_mut() {
766        let mut d = [
767            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
768        ];
769
770        let mut b = OctetsMut::with_slice(&mut d);
771        assert_eq!(b.cap(), 18);
772        assert_eq!(b.off(), 0);
773
774        assert_eq!(b.get_u8().unwrap(), 1);
775        assert_eq!(b.cap(), 17);
776        assert_eq!(b.off(), 1);
777
778        assert_eq!(b.get_u16().unwrap(), 0x203);
779        assert_eq!(b.cap(), 15);
780        assert_eq!(b.off(), 3);
781
782        assert_eq!(b.get_u24().unwrap(), 0x40506);
783        assert_eq!(b.cap(), 12);
784        assert_eq!(b.off(), 6);
785
786        assert_eq!(b.get_u32().unwrap(), 0x0708090a);
787        assert_eq!(b.cap(), 8);
788        assert_eq!(b.off(), 10);
789
790        assert_eq!(b.get_u64().unwrap(), 0x0b0c0d0e0f101112);
791        assert_eq!(b.cap(), 0);
792        assert_eq!(b.off(), 18);
793
794        assert!(b.get_u8().is_err());
795        assert!(b.get_u16().is_err());
796        assert!(b.get_u24().is_err());
797        assert!(b.get_u32().is_err());
798        assert!(b.get_u64().is_err());
799    }
800
801    #[test]
802    fn peek_u() {
803        let d = [1, 2];
804
805        let mut b = Octets::with_slice(&d);
806        assert_eq!(b.cap(), 2);
807        assert_eq!(b.off(), 0);
808
809        assert_eq!(b.peek_u8().unwrap(), 1);
810        assert_eq!(b.cap(), 2);
811        assert_eq!(b.off(), 0);
812
813        assert_eq!(b.peek_u8().unwrap(), 1);
814        assert_eq!(b.cap(), 2);
815        assert_eq!(b.off(), 0);
816
817        b.get_u16().unwrap();
818
819        assert!(b.peek_u8().is_err());
820    }
821
822    #[test]
823    fn peek_u_mut() {
824        let mut d = [1, 2];
825
826        let mut b = OctetsMut::with_slice(&mut d);
827        assert_eq!(b.cap(), 2);
828        assert_eq!(b.off(), 0);
829
830        assert_eq!(b.peek_u8().unwrap(), 1);
831        assert_eq!(b.cap(), 2);
832        assert_eq!(b.off(), 0);
833
834        assert_eq!(b.peek_u8().unwrap(), 1);
835        assert_eq!(b.cap(), 2);
836        assert_eq!(b.off(), 0);
837
838        b.get_u16().unwrap();
839
840        assert!(b.peek_u8().is_err());
841    }
842
843    #[test]
844    fn get_bytes() {
845        let d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
846        let mut b = Octets::with_slice(&d);
847        assert_eq!(b.cap(), 10);
848        assert_eq!(b.off(), 0);
849
850        assert_eq!(b.get_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
851        assert_eq!(b.cap(), 5);
852        assert_eq!(b.off(), 5);
853
854        assert_eq!(b.get_bytes(3).unwrap().as_ref(), [6, 7, 8]);
855        assert_eq!(b.cap(), 2);
856        assert_eq!(b.off(), 8);
857
858        assert!(b.get_bytes(3).is_err());
859        assert_eq!(b.cap(), 2);
860        assert_eq!(b.off(), 8);
861
862        assert_eq!(b.get_bytes(2).unwrap().as_ref(), [9, 10]);
863        assert_eq!(b.cap(), 0);
864        assert_eq!(b.off(), 10);
865
866        assert!(b.get_bytes(2).is_err());
867    }
868
869    #[test]
870    fn get_bytes_mut() {
871        let mut d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
872        let mut b = OctetsMut::with_slice(&mut d);
873        assert_eq!(b.cap(), 10);
874        assert_eq!(b.off(), 0);
875
876        assert_eq!(b.get_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
877        assert_eq!(b.cap(), 5);
878        assert_eq!(b.off(), 5);
879
880        assert_eq!(b.get_bytes(3).unwrap().as_ref(), [6, 7, 8]);
881        assert_eq!(b.cap(), 2);
882        assert_eq!(b.off(), 8);
883
884        assert!(b.get_bytes(3).is_err());
885        assert_eq!(b.cap(), 2);
886        assert_eq!(b.off(), 8);
887
888        assert_eq!(b.get_bytes(2).unwrap().as_ref(), [9, 10]);
889        assert_eq!(b.cap(), 0);
890        assert_eq!(b.off(), 10);
891
892        assert!(b.get_bytes(2).is_err());
893    }
894
895    #[test]
896    fn peek_bytes() {
897        let d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
898        let mut b = Octets::with_slice(&d);
899        assert_eq!(b.cap(), 10);
900        assert_eq!(b.off(), 0);
901
902        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
903        assert_eq!(b.cap(), 10);
904        assert_eq!(b.off(), 0);
905
906        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
907        assert_eq!(b.cap(), 10);
908        assert_eq!(b.off(), 0);
909
910        b.get_bytes(5).unwrap();
911    }
912
913    #[test]
914    fn peek_bytes_mut() {
915        let mut d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
916        let mut b = OctetsMut::with_slice(&mut d);
917        assert_eq!(b.cap(), 10);
918        assert_eq!(b.off(), 0);
919
920        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
921        assert_eq!(b.cap(), 10);
922        assert_eq!(b.off(), 0);
923
924        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
925        assert_eq!(b.cap(), 10);
926        assert_eq!(b.off(), 0);
927
928        b.get_bytes(5).unwrap();
929    }
930
931    #[test]
932    fn get_varint() {
933        let d = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
934        let mut b = Octets::with_slice(&d);
935        assert_eq!(b.get_varint().unwrap(), 151288809941952652);
936        assert_eq!(b.cap(), 0);
937        assert_eq!(b.off(), 8);
938
939        let d = [0x9d, 0x7f, 0x3e, 0x7d];
940        let mut b = Octets::with_slice(&d);
941        assert_eq!(b.get_varint().unwrap(), 494878333);
942        assert_eq!(b.cap(), 0);
943        assert_eq!(b.off(), 4);
944
945        let d = [0x7b, 0xbd];
946        let mut b = Octets::with_slice(&d);
947        assert_eq!(b.get_varint().unwrap(), 15293);
948        assert_eq!(b.cap(), 0);
949        assert_eq!(b.off(), 2);
950
951        let d = [0x40, 0x25];
952        let mut b = Octets::with_slice(&d);
953        assert_eq!(b.get_varint().unwrap(), 37);
954        assert_eq!(b.cap(), 0);
955        assert_eq!(b.off(), 2);
956
957        let d = [0x25];
958        let mut b = Octets::with_slice(&d);
959        assert_eq!(b.get_varint().unwrap(), 37);
960        assert_eq!(b.cap(), 0);
961        assert_eq!(b.off(), 1);
962    }
963
964    #[test]
965    fn get_varint_mut() {
966        let mut d = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
967        let mut b = OctetsMut::with_slice(&mut d);
968        assert_eq!(b.get_varint().unwrap(), 151288809941952652);
969        assert_eq!(b.cap(), 0);
970        assert_eq!(b.off(), 8);
971
972        let mut d = [0x9d, 0x7f, 0x3e, 0x7d];
973        let mut b = OctetsMut::with_slice(&mut d);
974        assert_eq!(b.get_varint().unwrap(), 494878333);
975        assert_eq!(b.cap(), 0);
976        assert_eq!(b.off(), 4);
977
978        let mut d = [0x7b, 0xbd];
979        let mut b = OctetsMut::with_slice(&mut d);
980        assert_eq!(b.get_varint().unwrap(), 15293);
981        assert_eq!(b.cap(), 0);
982        assert_eq!(b.off(), 2);
983
984        let mut d = [0x40, 0x25];
985        let mut b = OctetsMut::with_slice(&mut d);
986        assert_eq!(b.get_varint().unwrap(), 37);
987        assert_eq!(b.cap(), 0);
988        assert_eq!(b.off(), 2);
989
990        let mut d = [0x25];
991        let mut b = OctetsMut::with_slice(&mut d);
992        assert_eq!(b.get_varint().unwrap(), 37);
993        assert_eq!(b.cap(), 0);
994        assert_eq!(b.off(), 1);
995    }
996
997    #[test]
998    fn put_varint() {
999        let mut d = [0; 8];
1000        {
1001            let mut b = OctetsMut::with_slice(&mut d);
1002            assert!(b.put_varint(151288809941952652).is_ok());
1003            assert_eq!(b.cap(), 0);
1004            assert_eq!(b.off(), 8);
1005        }
1006        let exp = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
1007        assert_eq!(&d, &exp);
1008
1009        let mut d = [0; 4];
1010        {
1011            let mut b = OctetsMut::with_slice(&mut d);
1012            assert!(b.put_varint(494878333).is_ok());
1013            assert_eq!(b.cap(), 0);
1014            assert_eq!(b.off(), 4);
1015        }
1016        let exp = [0x9d, 0x7f, 0x3e, 0x7d];
1017        assert_eq!(&d, &exp);
1018
1019        let mut d = [0; 2];
1020        {
1021            let mut b = OctetsMut::with_slice(&mut d);
1022            assert!(b.put_varint(15293).is_ok());
1023            assert_eq!(b.cap(), 0);
1024            assert_eq!(b.off(), 2);
1025        }
1026        let exp = [0x7b, 0xbd];
1027        assert_eq!(&d, &exp);
1028
1029        let mut d = [0; 1];
1030        {
1031            let mut b = OctetsMut::with_slice(&mut d);
1032            assert!(b.put_varint(37).is_ok());
1033            assert_eq!(b.cap(), 0);
1034            assert_eq!(b.off(), 1);
1035        }
1036        let exp = [0x25];
1037        assert_eq!(&d, &exp);
1038
1039        let mut d = [0; 3];
1040        {
1041            let mut b = OctetsMut::with_slice(&mut d);
1042            assert!(b.put_varint(151288809941952652).is_err());
1043            assert_eq!(b.cap(), 3);
1044            assert_eq!(b.off(), 0);
1045        }
1046        let exp = [0; 3];
1047        assert_eq!(&d, &exp);
1048    }
1049
1050    #[test]
1051    #[should_panic]
1052    fn varint_too_large() {
1053        let mut d = [0; 3];
1054        let mut b = OctetsMut::with_slice(&mut d);
1055        assert!(b.put_varint(u64::MAX).is_err());
1056    }
1057
1058    #[test]
1059    fn put_u() {
1060        let mut d = [0; 18];
1061
1062        {
1063            let mut b = OctetsMut::with_slice(&mut d);
1064            assert_eq!(b.cap(), 18);
1065            assert_eq!(b.off(), 0);
1066
1067            assert!(b.put_u8(1).is_ok());
1068            assert_eq!(b.cap(), 17);
1069            assert_eq!(b.off(), 1);
1070
1071            assert!(b.put_u16(0x203).is_ok());
1072            assert_eq!(b.cap(), 15);
1073            assert_eq!(b.off(), 3);
1074
1075            assert!(b.put_u24(0x40506).is_ok());
1076            assert_eq!(b.cap(), 12);
1077            assert_eq!(b.off(), 6);
1078
1079            assert!(b.put_u32(0x0708090a).is_ok());
1080            assert_eq!(b.cap(), 8);
1081            assert_eq!(b.off(), 10);
1082
1083            assert!(b.put_u64(0x0b0c0d0e0f101112).is_ok());
1084            assert_eq!(b.cap(), 0);
1085            assert_eq!(b.off(), 18);
1086
1087            assert!(b.put_u8(1).is_err());
1088        }
1089
1090        let exp = [
1091            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
1092        ];
1093        assert_eq!(&d, &exp);
1094    }
1095
1096    #[test]
1097    fn put_bytes() {
1098        let mut d = [0; 5];
1099
1100        {
1101            let mut b = OctetsMut::with_slice(&mut d);
1102            assert_eq!(b.cap(), 5);
1103            assert_eq!(b.off(), 0);
1104
1105            let p = [0x0a, 0x0b, 0x0c, 0x0d, 0x0e];
1106            assert!(b.put_bytes(&p).is_ok());
1107            assert_eq!(b.cap(), 0);
1108            assert_eq!(b.off(), 5);
1109
1110            assert!(b.put_u8(1).is_err());
1111        }
1112
1113        let exp = [0xa, 0xb, 0xc, 0xd, 0xe];
1114        assert_eq!(&d, &exp);
1115    }
1116
1117    #[test]
1118    fn split() {
1119        let mut d = b"helloworld".to_vec();
1120
1121        let mut b = OctetsMut::with_slice(&mut d);
1122        assert_eq!(b.cap(), 10);
1123        assert_eq!(b.off(), 0);
1124        assert_eq!(b.as_ref(), b"helloworld");
1125
1126        assert!(b.get_bytes(5).is_ok());
1127        assert_eq!(b.cap(), 5);
1128        assert_eq!(b.off(), 5);
1129        assert_eq!(b.as_ref(), b"world");
1130
1131        let off = b.off();
1132
1133        let (first, last) = b.split_at(off).unwrap();
1134        assert_eq!(first.cap(), 5);
1135        assert_eq!(first.off(), 0);
1136        assert_eq!(first.as_ref(), b"hello");
1137
1138        assert_eq!(last.cap(), 5);
1139        assert_eq!(last.off(), 0);
1140        assert_eq!(last.as_ref(), b"world");
1141    }
1142
1143    #[test]
1144    fn split_at() {
1145        let mut d = b"helloworld".to_vec();
1146
1147        {
1148            let mut b = OctetsMut::with_slice(&mut d);
1149            let (first, second) = b.split_at(5).unwrap();
1150
1151            let mut exp1 = b"hello".to_vec();
1152            assert_eq!(first.as_ref(), &mut exp1[..]);
1153
1154            let mut exp2 = b"world".to_vec();
1155            assert_eq!(second.as_ref(), &mut exp2[..]);
1156        }
1157
1158        {
1159            let mut b = OctetsMut::with_slice(&mut d);
1160            let (first, second) = b.split_at(10).unwrap();
1161
1162            let mut exp1 = b"helloworld".to_vec();
1163            assert_eq!(first.as_ref(), &mut exp1[..]);
1164
1165            let mut exp2 = b"".to_vec();
1166            assert_eq!(second.as_ref(), &mut exp2[..]);
1167        }
1168
1169        {
1170            let mut b = OctetsMut::with_slice(&mut d);
1171            let (first, second) = b.split_at(9).unwrap();
1172
1173            let mut exp1 = b"helloworl".to_vec();
1174            assert_eq!(first.as_ref(), &mut exp1[..]);
1175
1176            let mut exp2 = b"d".to_vec();
1177            assert_eq!(second.as_ref(), &mut exp2[..]);
1178        }
1179
1180        {
1181            let mut b = OctetsMut::with_slice(&mut d);
1182            assert!(b.split_at(11).is_err());
1183        }
1184    }
1185
1186    #[test]
1187    fn slice() {
1188        let d = b"helloworld".to_vec();
1189
1190        {
1191            let b = Octets::with_slice(&d);
1192            let exp = b"hello".to_vec();
1193            assert_eq!(b.slice(5), Ok(&exp[..]));
1194        }
1195
1196        {
1197            let b = Octets::with_slice(&d);
1198            let exp = b"".to_vec();
1199            assert_eq!(b.slice(0), Ok(&exp[..]));
1200        }
1201
1202        {
1203            let mut b = Octets::with_slice(&d);
1204            b.get_bytes(5).unwrap();
1205
1206            let exp = b"world".to_vec();
1207            assert_eq!(b.slice(5), Ok(&exp[..]));
1208        }
1209
1210        {
1211            let b = Octets::with_slice(&d);
1212            assert!(b.slice(11).is_err());
1213        }
1214    }
1215
1216    #[test]
1217    fn slice_mut() {
1218        let mut d = b"helloworld".to_vec();
1219
1220        {
1221            let mut b = OctetsMut::with_slice(&mut d);
1222            let mut exp = b"hello".to_vec();
1223            assert_eq!(b.slice(5), Ok(&mut exp[..]));
1224        }
1225
1226        {
1227            let mut b = OctetsMut::with_slice(&mut d);
1228            let mut exp = b"".to_vec();
1229            assert_eq!(b.slice(0), Ok(&mut exp[..]));
1230        }
1231
1232        {
1233            let mut b = OctetsMut::with_slice(&mut d);
1234            b.get_bytes(5).unwrap();
1235
1236            let mut exp = b"world".to_vec();
1237            assert_eq!(b.slice(5), Ok(&mut exp[..]));
1238        }
1239
1240        {
1241            let mut b = OctetsMut::with_slice(&mut d);
1242            assert!(b.slice(11).is_err());
1243        }
1244    }
1245
1246    #[test]
1247    fn slice_last() {
1248        let d = b"helloworld".to_vec();
1249
1250        {
1251            let b = Octets::with_slice(&d);
1252            let exp = b"orld".to_vec();
1253            assert_eq!(b.slice_last(4), Ok(&exp[..]));
1254        }
1255
1256        {
1257            let b = Octets::with_slice(&d);
1258            let exp = b"d".to_vec();
1259            assert_eq!(b.slice_last(1), Ok(&exp[..]));
1260        }
1261
1262        {
1263            let b = Octets::with_slice(&d);
1264            let exp = b"".to_vec();
1265            assert_eq!(b.slice_last(0), Ok(&exp[..]));
1266        }
1267
1268        {
1269            let b = Octets::with_slice(&d);
1270            let exp = b"helloworld".to_vec();
1271            assert_eq!(b.slice_last(10), Ok(&exp[..]));
1272        }
1273
1274        {
1275            let b = Octets::with_slice(&d);
1276            assert!(b.slice_last(11).is_err());
1277        }
1278    }
1279
1280    #[test]
1281    fn slice_last_mut() {
1282        let mut d = b"helloworld".to_vec();
1283
1284        {
1285            let mut b = OctetsMut::with_slice(&mut d);
1286            let mut exp = b"orld".to_vec();
1287            assert_eq!(b.slice_last(4), Ok(&mut exp[..]));
1288        }
1289
1290        {
1291            let mut b = OctetsMut::with_slice(&mut d);
1292            let mut exp = b"d".to_vec();
1293            assert_eq!(b.slice_last(1), Ok(&mut exp[..]));
1294        }
1295
1296        {
1297            let mut b = OctetsMut::with_slice(&mut d);
1298            let mut exp = b"".to_vec();
1299            assert_eq!(b.slice_last(0), Ok(&mut exp[..]));
1300        }
1301
1302        {
1303            let mut b = OctetsMut::with_slice(&mut d);
1304            let mut exp = b"helloworld".to_vec();
1305            assert_eq!(b.slice_last(10), Ok(&mut exp[..]));
1306        }
1307
1308        {
1309            let mut b = OctetsMut::with_slice(&mut d);
1310            assert!(b.slice_last(11).is_err());
1311        }
1312    }
1313}