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(
591        &mut self, off: usize,
592    ) -> Result<(OctetsMut<'_>, OctetsMut<'_>)> {
593        if self.len() < off {
594            return Err(BufferTooShortError);
595        }
596
597        let (left, right) = self.buf.split_at_mut(off);
598
599        let first = OctetsMut { buf: left, off: 0 };
600
601        let last = OctetsMut { buf: right, off: 0 };
602
603        Ok((first, last))
604    }
605
606    /// Returns a slice of `len` elements from the current offset.
607    pub fn slice(&'a mut self, len: usize) -> Result<&'a mut [u8]> {
608        if len > self.cap() {
609            return Err(BufferTooShortError);
610        }
611
612        Ok(&mut self.buf[self.off..self.off + len])
613    }
614
615    /// Returns a slice of `len` elements from the end of the buffer.
616    pub fn slice_last(&'a mut self, len: usize) -> Result<&'a mut [u8]> {
617        if len > self.cap() {
618            return Err(BufferTooShortError);
619        }
620
621        let cap = self.cap();
622        Ok(&mut self.buf[cap - len..])
623    }
624
625    /// Advances the buffer's offset.
626    pub fn skip(&mut self, skip: usize) -> Result<()> {
627        if skip > self.cap() {
628            return Err(BufferTooShortError);
629        }
630
631        self.off += skip;
632
633        Ok(())
634    }
635
636    /// Returns the remaining capacity in the buffer.
637    pub fn cap(&self) -> usize {
638        self.buf.len() - self.off
639    }
640
641    /// Returns the total length of the buffer.
642    pub fn len(&self) -> usize {
643        self.buf.len()
644    }
645
646    /// Returns `true` if the buffer is empty.
647    pub fn is_empty(&self) -> bool {
648        self.buf.len() == 0
649    }
650
651    /// Returns the current offset of the buffer.
652    pub fn off(&self) -> usize {
653        self.off
654    }
655
656    /// Returns a reference to the internal buffer.
657    pub fn buf(&self) -> &[u8] {
658        self.buf
659    }
660
661    /// Copies the buffer from the current offset into a new `Vec<u8>`.
662    pub fn to_vec(&self) -> Vec<u8> {
663        self.as_ref().to_vec()
664    }
665}
666
667impl AsRef<[u8]> for OctetsMut<'_> {
668    fn as_ref(&self) -> &[u8] {
669        &self.buf[self.off..]
670    }
671}
672
673impl AsMut<[u8]> for OctetsMut<'_> {
674    fn as_mut(&mut self) -> &mut [u8] {
675        &mut self.buf[self.off..]
676    }
677}
678
679/// Returns how many bytes it would take to encode `v` as a variable-length
680/// integer.
681pub const fn varint_len(v: u64) -> usize {
682    if v <= 63 {
683        1
684    } else if v <= 16383 {
685        2
686    } else if v <= 1_073_741_823 {
687        4
688    } else if v <= 4_611_686_018_427_387_903 {
689        8
690    } else {
691        unreachable!()
692    }
693}
694
695/// Returns how long the variable-length integer is, given its first byte.
696pub const fn varint_parse_len(first: u8) -> usize {
697    match first >> 6 {
698        0 => 1,
699        1 => 2,
700        2 => 4,
701        3 => 8,
702        _ => unreachable!(),
703    }
704}
705
706/// The functions in this mod test the compile time assertions in the
707/// `put_u` and `peek_u` macros. If you compile this crate with
708/// `--cfg test_invalid_len_compilation_fail`, e.g., by using
709/// `cargo rustc  -- --cfg test_invalid_len_compilation_fail`
710/// You will get two compiler errors
711#[cfg(test_invalid_len_compilation_fail)]
712pub mod fails_to_compile {
713    use super::*;
714    pub fn peek_invalid_fails_to_compile(b: &mut Octets) -> Result<u8> {
715        peek_u!(b, u8, 2)
716    }
717
718    pub fn put_invalid_fails_to_compile<'a>(
719        b: &'a mut OctetsMut, v: u8,
720    ) -> Result<&'a mut [u8]> {
721        put_u!(b, u8, v, 2)
722    }
723}
724
725#[cfg(test)]
726mod tests {
727    use super::*;
728
729    #[test]
730    fn get_u() {
731        let d = [
732            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
733        ];
734
735        let mut b = Octets::with_slice(&d);
736        assert_eq!(b.cap(), 18);
737        assert_eq!(b.off(), 0);
738
739        assert_eq!(b.get_u8().unwrap(), 1);
740        assert_eq!(b.cap(), 17);
741        assert_eq!(b.off(), 1);
742
743        assert_eq!(b.get_u16().unwrap(), 0x203);
744        assert_eq!(b.cap(), 15);
745        assert_eq!(b.off(), 3);
746
747        assert_eq!(b.get_u24().unwrap(), 0x40506);
748        assert_eq!(b.cap(), 12);
749        assert_eq!(b.off(), 6);
750
751        assert_eq!(b.get_u32().unwrap(), 0x0708090a);
752        assert_eq!(b.cap(), 8);
753        assert_eq!(b.off(), 10);
754
755        assert_eq!(b.get_u64().unwrap(), 0x0b0c0d0e0f101112);
756        assert_eq!(b.cap(), 0);
757        assert_eq!(b.off(), 18);
758
759        assert!(b.get_u8().is_err());
760        assert!(b.get_u16().is_err());
761        assert!(b.get_u24().is_err());
762        assert!(b.get_u32().is_err());
763        assert!(b.get_u64().is_err());
764    }
765
766    #[test]
767    fn get_u_mut() {
768        let mut d = [
769            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
770        ];
771
772        let mut b = OctetsMut::with_slice(&mut d);
773        assert_eq!(b.cap(), 18);
774        assert_eq!(b.off(), 0);
775
776        assert_eq!(b.get_u8().unwrap(), 1);
777        assert_eq!(b.cap(), 17);
778        assert_eq!(b.off(), 1);
779
780        assert_eq!(b.get_u16().unwrap(), 0x203);
781        assert_eq!(b.cap(), 15);
782        assert_eq!(b.off(), 3);
783
784        assert_eq!(b.get_u24().unwrap(), 0x40506);
785        assert_eq!(b.cap(), 12);
786        assert_eq!(b.off(), 6);
787
788        assert_eq!(b.get_u32().unwrap(), 0x0708090a);
789        assert_eq!(b.cap(), 8);
790        assert_eq!(b.off(), 10);
791
792        assert_eq!(b.get_u64().unwrap(), 0x0b0c0d0e0f101112);
793        assert_eq!(b.cap(), 0);
794        assert_eq!(b.off(), 18);
795
796        assert!(b.get_u8().is_err());
797        assert!(b.get_u16().is_err());
798        assert!(b.get_u24().is_err());
799        assert!(b.get_u32().is_err());
800        assert!(b.get_u64().is_err());
801    }
802
803    #[test]
804    fn peek_u() {
805        let d = [1, 2];
806
807        let mut b = Octets::with_slice(&d);
808        assert_eq!(b.cap(), 2);
809        assert_eq!(b.off(), 0);
810
811        assert_eq!(b.peek_u8().unwrap(), 1);
812        assert_eq!(b.cap(), 2);
813        assert_eq!(b.off(), 0);
814
815        assert_eq!(b.peek_u8().unwrap(), 1);
816        assert_eq!(b.cap(), 2);
817        assert_eq!(b.off(), 0);
818
819        b.get_u16().unwrap();
820
821        assert!(b.peek_u8().is_err());
822    }
823
824    #[test]
825    fn peek_u_mut() {
826        let mut d = [1, 2];
827
828        let mut b = OctetsMut::with_slice(&mut d);
829        assert_eq!(b.cap(), 2);
830        assert_eq!(b.off(), 0);
831
832        assert_eq!(b.peek_u8().unwrap(), 1);
833        assert_eq!(b.cap(), 2);
834        assert_eq!(b.off(), 0);
835
836        assert_eq!(b.peek_u8().unwrap(), 1);
837        assert_eq!(b.cap(), 2);
838        assert_eq!(b.off(), 0);
839
840        b.get_u16().unwrap();
841
842        assert!(b.peek_u8().is_err());
843    }
844
845    #[test]
846    fn get_bytes() {
847        let d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
848        let mut b = Octets::with_slice(&d);
849        assert_eq!(b.cap(), 10);
850        assert_eq!(b.off(), 0);
851
852        assert_eq!(b.get_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
853        assert_eq!(b.cap(), 5);
854        assert_eq!(b.off(), 5);
855
856        assert_eq!(b.get_bytes(3).unwrap().as_ref(), [6, 7, 8]);
857        assert_eq!(b.cap(), 2);
858        assert_eq!(b.off(), 8);
859
860        assert!(b.get_bytes(3).is_err());
861        assert_eq!(b.cap(), 2);
862        assert_eq!(b.off(), 8);
863
864        assert_eq!(b.get_bytes(2).unwrap().as_ref(), [9, 10]);
865        assert_eq!(b.cap(), 0);
866        assert_eq!(b.off(), 10);
867
868        assert!(b.get_bytes(2).is_err());
869    }
870
871    #[test]
872    fn get_bytes_mut() {
873        let mut d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
874        let mut b = OctetsMut::with_slice(&mut d);
875        assert_eq!(b.cap(), 10);
876        assert_eq!(b.off(), 0);
877
878        assert_eq!(b.get_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
879        assert_eq!(b.cap(), 5);
880        assert_eq!(b.off(), 5);
881
882        assert_eq!(b.get_bytes(3).unwrap().as_ref(), [6, 7, 8]);
883        assert_eq!(b.cap(), 2);
884        assert_eq!(b.off(), 8);
885
886        assert!(b.get_bytes(3).is_err());
887        assert_eq!(b.cap(), 2);
888        assert_eq!(b.off(), 8);
889
890        assert_eq!(b.get_bytes(2).unwrap().as_ref(), [9, 10]);
891        assert_eq!(b.cap(), 0);
892        assert_eq!(b.off(), 10);
893
894        assert!(b.get_bytes(2).is_err());
895    }
896
897    #[test]
898    fn peek_bytes() {
899        let d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
900        let mut b = Octets::with_slice(&d);
901        assert_eq!(b.cap(), 10);
902        assert_eq!(b.off(), 0);
903
904        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
905        assert_eq!(b.cap(), 10);
906        assert_eq!(b.off(), 0);
907
908        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
909        assert_eq!(b.cap(), 10);
910        assert_eq!(b.off(), 0);
911
912        b.get_bytes(5).unwrap();
913    }
914
915    #[test]
916    fn peek_bytes_mut() {
917        let mut d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
918        let mut b = OctetsMut::with_slice(&mut d);
919        assert_eq!(b.cap(), 10);
920        assert_eq!(b.off(), 0);
921
922        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
923        assert_eq!(b.cap(), 10);
924        assert_eq!(b.off(), 0);
925
926        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
927        assert_eq!(b.cap(), 10);
928        assert_eq!(b.off(), 0);
929
930        b.get_bytes(5).unwrap();
931    }
932
933    #[test]
934    fn get_varint() {
935        let d = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
936        let mut b = Octets::with_slice(&d);
937        assert_eq!(b.get_varint().unwrap(), 151288809941952652);
938        assert_eq!(b.cap(), 0);
939        assert_eq!(b.off(), 8);
940
941        let d = [0x9d, 0x7f, 0x3e, 0x7d];
942        let mut b = Octets::with_slice(&d);
943        assert_eq!(b.get_varint().unwrap(), 494878333);
944        assert_eq!(b.cap(), 0);
945        assert_eq!(b.off(), 4);
946
947        let d = [0x7b, 0xbd];
948        let mut b = Octets::with_slice(&d);
949        assert_eq!(b.get_varint().unwrap(), 15293);
950        assert_eq!(b.cap(), 0);
951        assert_eq!(b.off(), 2);
952
953        let d = [0x40, 0x25];
954        let mut b = Octets::with_slice(&d);
955        assert_eq!(b.get_varint().unwrap(), 37);
956        assert_eq!(b.cap(), 0);
957        assert_eq!(b.off(), 2);
958
959        let d = [0x25];
960        let mut b = Octets::with_slice(&d);
961        assert_eq!(b.get_varint().unwrap(), 37);
962        assert_eq!(b.cap(), 0);
963        assert_eq!(b.off(), 1);
964    }
965
966    #[test]
967    fn get_varint_mut() {
968        let mut d = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
969        let mut b = OctetsMut::with_slice(&mut d);
970        assert_eq!(b.get_varint().unwrap(), 151288809941952652);
971        assert_eq!(b.cap(), 0);
972        assert_eq!(b.off(), 8);
973
974        let mut d = [0x9d, 0x7f, 0x3e, 0x7d];
975        let mut b = OctetsMut::with_slice(&mut d);
976        assert_eq!(b.get_varint().unwrap(), 494878333);
977        assert_eq!(b.cap(), 0);
978        assert_eq!(b.off(), 4);
979
980        let mut d = [0x7b, 0xbd];
981        let mut b = OctetsMut::with_slice(&mut d);
982        assert_eq!(b.get_varint().unwrap(), 15293);
983        assert_eq!(b.cap(), 0);
984        assert_eq!(b.off(), 2);
985
986        let mut d = [0x40, 0x25];
987        let mut b = OctetsMut::with_slice(&mut d);
988        assert_eq!(b.get_varint().unwrap(), 37);
989        assert_eq!(b.cap(), 0);
990        assert_eq!(b.off(), 2);
991
992        let mut d = [0x25];
993        let mut b = OctetsMut::with_slice(&mut d);
994        assert_eq!(b.get_varint().unwrap(), 37);
995        assert_eq!(b.cap(), 0);
996        assert_eq!(b.off(), 1);
997    }
998
999    #[test]
1000    fn put_varint() {
1001        let mut d = [0; 8];
1002        {
1003            let mut b = OctetsMut::with_slice(&mut d);
1004            assert!(b.put_varint(151288809941952652).is_ok());
1005            assert_eq!(b.cap(), 0);
1006            assert_eq!(b.off(), 8);
1007        }
1008        let exp = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
1009        assert_eq!(&d, &exp);
1010
1011        let mut d = [0; 4];
1012        {
1013            let mut b = OctetsMut::with_slice(&mut d);
1014            assert!(b.put_varint(494878333).is_ok());
1015            assert_eq!(b.cap(), 0);
1016            assert_eq!(b.off(), 4);
1017        }
1018        let exp = [0x9d, 0x7f, 0x3e, 0x7d];
1019        assert_eq!(&d, &exp);
1020
1021        let mut d = [0; 2];
1022        {
1023            let mut b = OctetsMut::with_slice(&mut d);
1024            assert!(b.put_varint(15293).is_ok());
1025            assert_eq!(b.cap(), 0);
1026            assert_eq!(b.off(), 2);
1027        }
1028        let exp = [0x7b, 0xbd];
1029        assert_eq!(&d, &exp);
1030
1031        let mut d = [0; 1];
1032        {
1033            let mut b = OctetsMut::with_slice(&mut d);
1034            assert!(b.put_varint(37).is_ok());
1035            assert_eq!(b.cap(), 0);
1036            assert_eq!(b.off(), 1);
1037        }
1038        let exp = [0x25];
1039        assert_eq!(&d, &exp);
1040
1041        let mut d = [0; 3];
1042        {
1043            let mut b = OctetsMut::with_slice(&mut d);
1044            assert!(b.put_varint(151288809941952652).is_err());
1045            assert_eq!(b.cap(), 3);
1046            assert_eq!(b.off(), 0);
1047        }
1048        let exp = [0; 3];
1049        assert_eq!(&d, &exp);
1050    }
1051
1052    #[test]
1053    #[should_panic]
1054    fn varint_too_large() {
1055        let mut d = [0; 3];
1056        let mut b = OctetsMut::with_slice(&mut d);
1057        assert!(b.put_varint(u64::MAX).is_err());
1058    }
1059
1060    #[test]
1061    fn put_u() {
1062        let mut d = [0; 18];
1063
1064        {
1065            let mut b = OctetsMut::with_slice(&mut d);
1066            assert_eq!(b.cap(), 18);
1067            assert_eq!(b.off(), 0);
1068
1069            assert!(b.put_u8(1).is_ok());
1070            assert_eq!(b.cap(), 17);
1071            assert_eq!(b.off(), 1);
1072
1073            assert!(b.put_u16(0x203).is_ok());
1074            assert_eq!(b.cap(), 15);
1075            assert_eq!(b.off(), 3);
1076
1077            assert!(b.put_u24(0x40506).is_ok());
1078            assert_eq!(b.cap(), 12);
1079            assert_eq!(b.off(), 6);
1080
1081            assert!(b.put_u32(0x0708090a).is_ok());
1082            assert_eq!(b.cap(), 8);
1083            assert_eq!(b.off(), 10);
1084
1085            assert!(b.put_u64(0x0b0c0d0e0f101112).is_ok());
1086            assert_eq!(b.cap(), 0);
1087            assert_eq!(b.off(), 18);
1088
1089            assert!(b.put_u8(1).is_err());
1090        }
1091
1092        let exp = [
1093            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
1094        ];
1095        assert_eq!(&d, &exp);
1096    }
1097
1098    #[test]
1099    fn put_bytes() {
1100        let mut d = [0; 5];
1101
1102        {
1103            let mut b = OctetsMut::with_slice(&mut d);
1104            assert_eq!(b.cap(), 5);
1105            assert_eq!(b.off(), 0);
1106
1107            let p = [0x0a, 0x0b, 0x0c, 0x0d, 0x0e];
1108            assert!(b.put_bytes(&p).is_ok());
1109            assert_eq!(b.cap(), 0);
1110            assert_eq!(b.off(), 5);
1111
1112            assert!(b.put_u8(1).is_err());
1113        }
1114
1115        let exp = [0xa, 0xb, 0xc, 0xd, 0xe];
1116        assert_eq!(&d, &exp);
1117    }
1118
1119    #[test]
1120    fn split() {
1121        let mut d = b"helloworld".to_vec();
1122
1123        let mut b = OctetsMut::with_slice(&mut d);
1124        assert_eq!(b.cap(), 10);
1125        assert_eq!(b.off(), 0);
1126        assert_eq!(b.as_ref(), b"helloworld");
1127
1128        assert!(b.get_bytes(5).is_ok());
1129        assert_eq!(b.cap(), 5);
1130        assert_eq!(b.off(), 5);
1131        assert_eq!(b.as_ref(), b"world");
1132
1133        let off = b.off();
1134
1135        let (first, last) = b.split_at(off).unwrap();
1136        assert_eq!(first.cap(), 5);
1137        assert_eq!(first.off(), 0);
1138        assert_eq!(first.as_ref(), b"hello");
1139
1140        assert_eq!(last.cap(), 5);
1141        assert_eq!(last.off(), 0);
1142        assert_eq!(last.as_ref(), b"world");
1143    }
1144
1145    #[test]
1146    fn split_at() {
1147        let mut d = b"helloworld".to_vec();
1148
1149        {
1150            let mut b = OctetsMut::with_slice(&mut d);
1151            let (first, second) = b.split_at(5).unwrap();
1152
1153            let mut exp1 = b"hello".to_vec();
1154            assert_eq!(first.as_ref(), &mut exp1[..]);
1155
1156            let mut exp2 = b"world".to_vec();
1157            assert_eq!(second.as_ref(), &mut exp2[..]);
1158        }
1159
1160        {
1161            let mut b = OctetsMut::with_slice(&mut d);
1162            let (first, second) = b.split_at(10).unwrap();
1163
1164            let mut exp1 = b"helloworld".to_vec();
1165            assert_eq!(first.as_ref(), &mut exp1[..]);
1166
1167            let mut exp2 = b"".to_vec();
1168            assert_eq!(second.as_ref(), &mut exp2[..]);
1169        }
1170
1171        {
1172            let mut b = OctetsMut::with_slice(&mut d);
1173            let (first, second) = b.split_at(9).unwrap();
1174
1175            let mut exp1 = b"helloworl".to_vec();
1176            assert_eq!(first.as_ref(), &mut exp1[..]);
1177
1178            let mut exp2 = b"d".to_vec();
1179            assert_eq!(second.as_ref(), &mut exp2[..]);
1180        }
1181
1182        {
1183            let mut b = OctetsMut::with_slice(&mut d);
1184            assert!(b.split_at(11).is_err());
1185        }
1186    }
1187
1188    #[test]
1189    fn slice() {
1190        let d = b"helloworld".to_vec();
1191
1192        {
1193            let b = Octets::with_slice(&d);
1194            let exp = b"hello".to_vec();
1195            assert_eq!(b.slice(5), Ok(&exp[..]));
1196        }
1197
1198        {
1199            let b = Octets::with_slice(&d);
1200            let exp = b"".to_vec();
1201            assert_eq!(b.slice(0), Ok(&exp[..]));
1202        }
1203
1204        {
1205            let mut b = Octets::with_slice(&d);
1206            b.get_bytes(5).unwrap();
1207
1208            let exp = b"world".to_vec();
1209            assert_eq!(b.slice(5), Ok(&exp[..]));
1210        }
1211
1212        {
1213            let b = Octets::with_slice(&d);
1214            assert!(b.slice(11).is_err());
1215        }
1216    }
1217
1218    #[test]
1219    fn slice_mut() {
1220        let mut d = b"helloworld".to_vec();
1221
1222        {
1223            let mut b = OctetsMut::with_slice(&mut d);
1224            let mut exp = b"hello".to_vec();
1225            assert_eq!(b.slice(5), Ok(&mut exp[..]));
1226        }
1227
1228        {
1229            let mut b = OctetsMut::with_slice(&mut d);
1230            let mut exp = b"".to_vec();
1231            assert_eq!(b.slice(0), Ok(&mut exp[..]));
1232        }
1233
1234        {
1235            let mut b = OctetsMut::with_slice(&mut d);
1236            b.get_bytes(5).unwrap();
1237
1238            let mut exp = b"world".to_vec();
1239            assert_eq!(b.slice(5), Ok(&mut exp[..]));
1240        }
1241
1242        {
1243            let mut b = OctetsMut::with_slice(&mut d);
1244            assert!(b.slice(11).is_err());
1245        }
1246    }
1247
1248    #[test]
1249    fn slice_last() {
1250        let d = b"helloworld".to_vec();
1251
1252        {
1253            let b = Octets::with_slice(&d);
1254            let exp = b"orld".to_vec();
1255            assert_eq!(b.slice_last(4), Ok(&exp[..]));
1256        }
1257
1258        {
1259            let b = Octets::with_slice(&d);
1260            let exp = b"d".to_vec();
1261            assert_eq!(b.slice_last(1), Ok(&exp[..]));
1262        }
1263
1264        {
1265            let b = Octets::with_slice(&d);
1266            let exp = b"".to_vec();
1267            assert_eq!(b.slice_last(0), Ok(&exp[..]));
1268        }
1269
1270        {
1271            let b = Octets::with_slice(&d);
1272            let exp = b"helloworld".to_vec();
1273            assert_eq!(b.slice_last(10), Ok(&exp[..]));
1274        }
1275
1276        {
1277            let b = Octets::with_slice(&d);
1278            assert!(b.slice_last(11).is_err());
1279        }
1280    }
1281
1282    #[test]
1283    fn slice_last_mut() {
1284        let mut d = b"helloworld".to_vec();
1285
1286        {
1287            let mut b = OctetsMut::with_slice(&mut d);
1288            let mut exp = b"orld".to_vec();
1289            assert_eq!(b.slice_last(4), Ok(&mut exp[..]));
1290        }
1291
1292        {
1293            let mut b = OctetsMut::with_slice(&mut d);
1294            let mut exp = b"d".to_vec();
1295            assert_eq!(b.slice_last(1), Ok(&mut exp[..]));
1296        }
1297
1298        {
1299            let mut b = OctetsMut::with_slice(&mut d);
1300            let mut exp = b"".to_vec();
1301            assert_eq!(b.slice_last(0), Ok(&mut exp[..]));
1302        }
1303
1304        {
1305            let mut b = OctetsMut::with_slice(&mut d);
1306            let mut exp = b"helloworld".to_vec();
1307            assert_eq!(b.slice_last(10), Ok(&mut exp[..]));
1308        }
1309
1310        {
1311            let mut b = OctetsMut::with_slice(&mut d);
1312            assert!(b.slice_last(11).is_err());
1313        }
1314    }
1315}