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