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