Skip to main content

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    /// Decodes a Huffman-encoded value from the current offset.
252    ///
253    /// The Huffman code implemented is the one defined for HPACK (RFC7541).
254    #[cfg(feature = "huffman_hpack")]
255    pub fn get_huffman_decoded(&mut self) -> Result<Vec<u8>> {
256        self.get_huffman_decoded_with_max_length(usize::MAX)
257    }
258
259    /// Decodes a Huffman-encoded value from the current offset. The `max_len`
260    /// parameter controls the maximum length of the decoded value.
261    ///
262    /// The Huffman code implemented is the one defined for HPACK (RFC7541).
263    #[cfg(feature = "huffman_hpack")]
264    pub fn get_huffman_decoded_with_max_length(
265        &mut self, max_len: usize,
266    ) -> Result<Vec<u8>> {
267        use self::huffman_table::DECODE_TABLE;
268
269        const FLAG_END: u8 = 1;
270        const FLAG_SYM: u8 = 2;
271        const FLAG_ERR: u8 = 4;
272
273        // Max compression ratio is >= 0.5.
274        let initial_cap = std::cmp::min(self.cap() * 2, max_len);
275        let mut out = Vec::with_capacity(initial_cap);
276
277        let mut state = 0;
278        let mut eos = false;
279
280        while let Ok(byte) = self.get_u8() {
281            for data in [byte >> 4, byte & 0xf] {
282                let (next, sym, flags) = DECODE_TABLE[state][(data) as usize];
283
284                if flags & FLAG_ERR == FLAG_ERR {
285                    // Data followed the "end" marker.
286                    return Err(BufferTooShortError);
287                } else if flags & FLAG_SYM == FLAG_SYM {
288                    // Error if pushing sym (1 byte) would overflow.
289                    if out.len() + 1 > max_len {
290                        return Err(BufferTooShortError);
291                    }
292                    out.push(sym);
293                }
294
295                state = next;
296
297                // `eos` only correct when handling the byte & 0xf case; ignored
298                // and overwritten in the byte >> 4 case.
299                eos = flags & FLAG_END == FLAG_END;
300            }
301        }
302
303        if state != 0 && !eos {
304            return Err(BufferTooShortError);
305        }
306
307        Ok(out)
308    }
309
310    /// Reads `len` bytes from the current offset without copying and without
311    /// advancing the buffer.
312    pub fn peek_bytes(&self, len: usize) -> Result<Octets<'a>> {
313        if self.cap() < len {
314            return Err(BufferTooShortError);
315        }
316
317        let out = Octets {
318            buf: &self.buf[self.off..self.off + len],
319            off: 0,
320        };
321
322        Ok(out)
323    }
324
325    /// Rewinds the buffer offset by `len` elements.
326    pub fn rewind(&mut self, len: usize) -> Result<()> {
327        if self.off() < len {
328            return Err(BufferTooShortError);
329        }
330
331        self.off -= len;
332
333        Ok(())
334    }
335
336    /// Returns a slice of `len` elements from the current offset.
337    pub fn slice(&self, len: usize) -> Result<&'a [u8]> {
338        if len > self.cap() {
339            return Err(BufferTooShortError);
340        }
341
342        Ok(&self.buf[self.off..self.off + len])
343    }
344
345    /// Returns a slice of `len` elements from the end of the buffer.
346    pub fn slice_last(&self, len: usize) -> Result<&'a [u8]> {
347        if len > self.cap() {
348            return Err(BufferTooShortError);
349        }
350
351        let end = self.buf.len();
352        Ok(&self.buf[end - len..end])
353    }
354
355    /// Advances the buffer's offset.
356    pub fn skip(&mut self, skip: usize) -> Result<()> {
357        if skip > self.cap() {
358            return Err(BufferTooShortError);
359        }
360
361        self.off += skip;
362
363        Ok(())
364    }
365
366    /// Returns the remaining capacity in the buffer.
367    pub fn cap(&self) -> usize {
368        self.buf.len() - self.off
369    }
370
371    /// Returns the total length of the buffer.
372    pub fn len(&self) -> usize {
373        self.buf.len()
374    }
375
376    /// Returns `true` if the buffer is empty.
377    pub fn is_empty(&self) -> bool {
378        self.buf.len() == 0
379    }
380
381    /// Returns the current offset of the buffer.
382    pub fn off(&self) -> usize {
383        self.off
384    }
385
386    /// Returns a reference to the internal buffer.
387    pub fn buf(&self) -> &'a [u8] {
388        self.buf
389    }
390
391    /// Copies the buffer from the current offset into a new `Vec<u8>`.
392    pub fn to_vec(&self) -> Vec<u8> {
393        self.as_ref().to_vec()
394    }
395}
396
397impl AsRef<[u8]> for Octets<'_> {
398    fn as_ref(&self) -> &[u8] {
399        &self.buf[self.off..]
400    }
401}
402
403/// A zero-copy mutable byte buffer.
404///
405/// Like `Octets` but mutable.
406#[derive(Debug, PartialEq, Eq)]
407pub struct OctetsMut<'a> {
408    buf: &'a mut [u8],
409    off: usize,
410}
411
412impl<'a> OctetsMut<'a> {
413    /// Creates an `OctetsMut` from the given slice, without copying.
414    ///
415    /// Since there's no copy, the input slice needs to be mutable to allow
416    /// modifications.
417    pub fn with_slice(buf: &'a mut [u8]) -> Self {
418        OctetsMut { buf, off: 0 }
419    }
420
421    /// Reads an unsigned 8-bit integer from the current offset and advances
422    /// the buffer.
423    pub fn get_u8(&mut self) -> Result<u8> {
424        get_u!(self, u8, 1)
425    }
426
427    /// Reads an unsigned 8-bit integer from the current offset without
428    /// advancing the buffer.
429    pub fn peek_u8(&mut self) -> Result<u8> {
430        peek_u!(self, u8, 1)
431    }
432
433    /// Writes an unsigned 8-bit integer at the current offset and advances
434    /// the buffer.
435    pub fn put_u8(&mut self, v: u8) -> Result<&mut [u8]> {
436        put_u!(self, u8, v, 1)
437    }
438
439    /// Reads an unsigned 16-bit integer in network byte-order from the current
440    /// offset and advances the buffer.
441    pub fn get_u16(&mut self) -> Result<u16> {
442        get_u!(self, u16, 2)
443    }
444
445    /// Writes an unsigned 16-bit integer in network byte-order at the current
446    /// offset and advances the buffer.
447    pub fn put_u16(&mut self, v: u16) -> Result<&mut [u8]> {
448        put_u!(self, u16, v, 2)
449    }
450
451    /// Reads an unsigned 24-bit integer in network byte-order from the current
452    /// offset and advances the buffer.
453    pub fn get_u24(&mut self) -> Result<u32> {
454        get_u!(self, u32, 3)
455    }
456
457    /// Writes an unsigned 24-bit integer in network byte-order at the current
458    /// offset and advances the buffer.
459    pub fn put_u24(&mut self, v: u32) -> Result<&mut [u8]> {
460        put_u!(self, u32, v, 3)
461    }
462
463    /// Reads an unsigned 32-bit integer in network byte-order from the current
464    /// offset and advances the buffer.
465    pub fn get_u32(&mut self) -> Result<u32> {
466        get_u!(self, u32, 4)
467    }
468
469    /// Writes an unsigned 32-bit integer in network byte-order at the current
470    /// offset and advances the buffer.
471    pub fn put_u32(&mut self, v: u32) -> Result<&mut [u8]> {
472        put_u!(self, u32, v, 4)
473    }
474
475    /// Reads an unsigned 64-bit integer in network byte-order from the current
476    /// offset and advances the buffer.
477    pub fn get_u64(&mut self) -> Result<u64> {
478        get_u!(self, u64, 8)
479    }
480
481    /// Writes an unsigned 64-bit integer in network byte-order at the current
482    /// offset and advances the buffer.
483    pub fn put_u64(&mut self, v: u64) -> Result<&mut [u8]> {
484        put_u!(self, u64, v, 8)
485    }
486
487    /// Reads an unsigned variable-length integer in network byte-order from
488    /// the current offset and advances the buffer.
489    pub fn get_varint(&mut self) -> Result<u64> {
490        let first = self.peek_u8()?;
491
492        let len = varint_parse_len(first);
493
494        if len > self.cap() {
495            return Err(BufferTooShortError);
496        }
497
498        let out = match len {
499            1 => u64::from(self.get_u8()?),
500
501            2 => u64::from(self.get_u16()? & 0x3fff),
502
503            4 => u64::from(self.get_u32()? & 0x3fffffff),
504
505            8 => self.get_u64()? & 0x3fffffffffffffff,
506
507            _ => unreachable!(),
508        };
509
510        Ok(out)
511    }
512
513    /// Writes an unsigned variable-length integer in network byte-order at the
514    /// current offset and advances the buffer.
515    pub fn put_varint(&mut self, v: u64) -> Result<&mut [u8]> {
516        self.put_varint_with_len(v, varint_len(v))
517    }
518
519    /// Writes an unsigned variable-length integer of the specified length, in
520    /// network byte-order at the current offset and advances the buffer.
521    pub fn put_varint_with_len(
522        &mut self, v: u64, len: usize,
523    ) -> Result<&mut [u8]> {
524        if self.cap() < len {
525            return Err(BufferTooShortError);
526        }
527
528        let buf = match len {
529            1 => self.put_u8(v as u8)?,
530
531            2 => {
532                let buf = self.put_u16(v as u16)?;
533                buf[0] |= 0x40;
534                buf
535            },
536
537            4 => {
538                let buf = self.put_u32(v as u32)?;
539                buf[0] |= 0x80;
540                buf
541            },
542
543            8 => {
544                let buf = self.put_u64(v)?;
545                buf[0] |= 0xc0;
546                buf
547            },
548
549            _ => panic!("value is too large for varint"),
550        };
551
552        Ok(buf)
553    }
554
555    /// Reads `len` bytes from the current offset without copying and advances
556    /// the buffer.
557    pub fn get_bytes(&mut self, len: usize) -> Result<Octets<'_>> {
558        if self.cap() < len {
559            return Err(BufferTooShortError);
560        }
561
562        let out = Octets {
563            buf: &self.buf[self.off..self.off + len],
564            off: 0,
565        };
566
567        self.off += len;
568
569        Ok(out)
570    }
571
572    /// Reads `len` bytes from the current offset without copying and advances
573    /// the buffer.
574    pub fn get_bytes_mut(&mut self, len: usize) -> Result<OctetsMut<'_>> {
575        if self.cap() < len {
576            return Err(BufferTooShortError);
577        }
578
579        let out = OctetsMut {
580            buf: &mut self.buf[self.off..self.off + len],
581            off: 0,
582        };
583
584        self.off += len;
585
586        Ok(out)
587    }
588
589    /// Reads `len` bytes from the current offset without copying and advances
590    /// the buffer, where `len` is an unsigned 8-bit integer prefix.
591    pub fn get_bytes_with_u8_length(&mut self) -> Result<Octets<'_>> {
592        let len = self.get_u8()?;
593        self.get_bytes(len as usize)
594    }
595
596    /// Reads `len` bytes from the current offset without copying and advances
597    /// the buffer, where `len` is an unsigned 16-bit integer prefix in network
598    /// byte-order.
599    pub fn get_bytes_with_u16_length(&mut self) -> Result<Octets<'_>> {
600        let len = self.get_u16()?;
601        self.get_bytes(len as usize)
602    }
603
604    /// Reads `len` bytes from the current offset without copying and advances
605    /// the buffer, where `len` is an unsigned variable-length integer prefix
606    /// in network byte-order.
607    pub fn get_bytes_with_varint_length(&mut self) -> Result<Octets<'_>> {
608        let len = self.get_varint()?;
609        self.get_bytes(len as usize)
610    }
611
612    /// Reads `len` bytes from the current offset without copying and without
613    /// advancing the buffer.
614    pub fn peek_bytes(&mut self, len: usize) -> Result<Octets<'_>> {
615        if self.cap() < len {
616            return Err(BufferTooShortError);
617        }
618
619        let out = Octets {
620            buf: &self.buf[self.off..self.off + len],
621            off: 0,
622        };
623
624        Ok(out)
625    }
626
627    /// Reads `len` bytes from the current offset without copying and without
628    /// advancing the buffer.
629    pub fn peek_bytes_mut(&mut self, len: usize) -> Result<OctetsMut<'_>> {
630        if self.cap() < len {
631            return Err(BufferTooShortError);
632        }
633
634        let out = OctetsMut {
635            buf: &mut self.buf[self.off..self.off + len],
636            off: 0,
637        };
638
639        Ok(out)
640    }
641
642    /// Writes `v` to the current offset.
643    pub fn put_bytes(&mut self, v: &[u8]) -> Result<()> {
644        let len = v.len();
645
646        if self.cap() < len {
647            return Err(BufferTooShortError);
648        }
649
650        if len == 0 {
651            return Ok(());
652        }
653
654        self.as_mut()[..len].copy_from_slice(v);
655
656        self.off += len;
657
658        Ok(())
659    }
660
661    /// Writes `v` to the current offset after Huffman-encoding it.
662    ///
663    /// The Huffman code implemented is the one defined for HPACK (RFC7541).
664    #[cfg(feature = "huffman_hpack")]
665    pub fn put_huffman_encoded<const LOWER_CASE: bool>(
666        &mut self, v: &[u8],
667    ) -> Result<()> {
668        use self::huffman_table::ENCODE_TABLE;
669
670        let mut bits: u64 = 0;
671        let mut pending = 0;
672
673        for &b in v {
674            let b = if LOWER_CASE {
675                b.to_ascii_lowercase()
676            } else {
677                b
678            };
679            let (nbits, code) = ENCODE_TABLE[b as usize];
680
681            pending += nbits;
682
683            if pending < 64 {
684                // Have room for the new token
685                bits |= code << (64 - pending);
686                continue;
687            }
688
689            pending -= 64;
690            // Take only the bits that fit
691            bits |= code >> pending;
692            self.put_u64(bits)?;
693
694            bits = if pending == 0 {
695                0
696            } else {
697                code << (64 - pending)
698            };
699        }
700
701        if pending == 0 {
702            return Ok(());
703        }
704
705        bits |= u64::MAX >> pending;
706        // TODO: replace with `next_multiple_of(8)` when stable
707        pending = (pending + 7) & !7; // Round up to a byte
708        bits >>= 64 - pending;
709
710        if pending >= 32 {
711            pending -= 32;
712            self.put_u32((bits >> pending) as u32)?;
713        }
714
715        while pending > 0 {
716            pending -= 8;
717            self.put_u8((bits >> pending) as u8)?;
718        }
719
720        Ok(())
721    }
722
723    /// Rewinds the buffer offset by `len` elements.
724    pub fn rewind(&mut self, len: usize) -> Result<()> {
725        if self.off() < len {
726            return Err(BufferTooShortError);
727        }
728
729        self.off -= len;
730
731        Ok(())
732    }
733
734    /// Splits the buffer in two at the given absolute offset.
735    pub fn split_at(
736        &mut self, off: usize,
737    ) -> Result<(OctetsMut<'_>, OctetsMut<'_>)> {
738        if self.len() < off {
739            return Err(BufferTooShortError);
740        }
741
742        let (left, right) = self.buf.split_at_mut(off);
743
744        let first = OctetsMut { buf: left, off: 0 };
745
746        let last = OctetsMut { buf: right, off: 0 };
747
748        Ok((first, last))
749    }
750
751    /// Returns a slice of `len` elements from the current offset.
752    pub fn slice(&'a mut self, len: usize) -> Result<&'a mut [u8]> {
753        if len > self.cap() {
754            return Err(BufferTooShortError);
755        }
756
757        Ok(&mut self.buf[self.off..self.off + len])
758    }
759
760    /// Returns a slice of `len` elements from the end of the buffer.
761    pub fn slice_last(&'a mut self, len: usize) -> Result<&'a mut [u8]> {
762        if len > self.cap() {
763            return Err(BufferTooShortError);
764        }
765
766        let end = self.buf.len();
767        Ok(&mut self.buf[end - len..end])
768    }
769
770    /// Advances the buffer's offset.
771    pub fn skip(&mut self, skip: usize) -> Result<()> {
772        if skip > self.cap() {
773            return Err(BufferTooShortError);
774        }
775
776        self.off += skip;
777
778        Ok(())
779    }
780
781    /// Returns the remaining capacity in the buffer.
782    pub fn cap(&self) -> usize {
783        self.buf.len() - self.off
784    }
785
786    /// Returns the total length of the buffer.
787    pub fn len(&self) -> usize {
788        self.buf.len()
789    }
790
791    /// Returns `true` if the buffer is empty.
792    pub fn is_empty(&self) -> bool {
793        self.buf.len() == 0
794    }
795
796    /// Returns the current offset of the buffer.
797    pub fn off(&self) -> usize {
798        self.off
799    }
800
801    /// Returns a reference to the internal buffer.
802    pub fn buf(&self) -> &[u8] {
803        self.buf
804    }
805
806    /// Copies the buffer from the current offset into a new `Vec<u8>`.
807    pub fn to_vec(&self) -> Vec<u8> {
808        self.as_ref().to_vec()
809    }
810}
811
812impl AsRef<[u8]> for OctetsMut<'_> {
813    fn as_ref(&self) -> &[u8] {
814        &self.buf[self.off..]
815    }
816}
817
818impl AsMut<[u8]> for OctetsMut<'_> {
819    fn as_mut(&mut self) -> &mut [u8] {
820        &mut self.buf[self.off..]
821    }
822}
823
824/// Returns how many bytes it would take to encode `v` as a variable-length
825/// integer.
826pub const fn varint_len(v: u64) -> usize {
827    if v <= 63 {
828        1
829    } else if v <= 16383 {
830        2
831    } else if v <= 1_073_741_823 {
832        4
833    } else if v <= MAX_VAR_INT {
834        8
835    } else {
836        unreachable!()
837    }
838}
839
840/// Returns how long the variable-length integer is, given its first byte.
841pub const fn varint_parse_len(first: u8) -> usize {
842    match first >> 6 {
843        0 => 1,
844        1 => 2,
845        2 => 4,
846        3 => 8,
847        _ => unreachable!(),
848    }
849}
850
851/// Returns how long the Huffman encoding of the given buffer will be.
852///
853/// The Huffman code implemented is the one defined for HPACK (RFC7541).
854#[cfg(feature = "huffman_hpack")]
855pub fn huffman_encoding_len<const LOWER_CASE: bool>(src: &[u8]) -> Result<usize> {
856    use self::huffman_table::ENCODE_TABLE;
857
858    let mut bits: usize = 0;
859
860    for &b in src {
861        let b = if LOWER_CASE {
862            b.to_ascii_lowercase()
863        } else {
864            b
865        };
866
867        let (nbits, _) = ENCODE_TABLE[b as usize];
868        bits += nbits;
869    }
870
871    let mut len = bits / 8;
872
873    if bits & 7 != 0 {
874        len += 1;
875    }
876
877    if len > src.len() {
878        return Err(BufferTooShortError);
879    }
880
881    Ok(len)
882}
883
884/// The functions in this mod test the compile time assertions in the
885/// `put_u` and `peek_u` macros. If you compile this crate with
886/// `--cfg test_invalid_len_compilation_fail`, e.g., by using
887/// `cargo rustc  -- --cfg test_invalid_len_compilation_fail`
888/// You will get two compiler errors
889#[cfg(test_invalid_len_compilation_fail)]
890pub mod fails_to_compile {
891    use super::*;
892    pub fn peek_invalid_fails_to_compile(b: &mut Octets) -> Result<u8> {
893        peek_u!(b, u8, 2)
894    }
895
896    pub fn put_invalid_fails_to_compile<'a>(
897        b: &'a mut OctetsMut, v: u8,
898    ) -> Result<&'a mut [u8]> {
899        put_u!(b, u8, v, 2)
900    }
901}
902
903#[cfg(test)]
904mod tests {
905    use super::*;
906
907    #[test]
908    fn get_u() {
909        let d = [
910            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
911        ];
912
913        let mut b = Octets::with_slice(&d);
914        assert_eq!(b.cap(), 18);
915        assert_eq!(b.off(), 0);
916
917        assert_eq!(b.get_u8().unwrap(), 1);
918        assert_eq!(b.cap(), 17);
919        assert_eq!(b.off(), 1);
920
921        assert_eq!(b.get_u16().unwrap(), 0x203);
922        assert_eq!(b.cap(), 15);
923        assert_eq!(b.off(), 3);
924
925        assert_eq!(b.get_u24().unwrap(), 0x40506);
926        assert_eq!(b.cap(), 12);
927        assert_eq!(b.off(), 6);
928
929        assert_eq!(b.get_u32().unwrap(), 0x0708090a);
930        assert_eq!(b.cap(), 8);
931        assert_eq!(b.off(), 10);
932
933        assert_eq!(b.get_u64().unwrap(), 0x0b0c0d0e0f101112);
934        assert_eq!(b.cap(), 0);
935        assert_eq!(b.off(), 18);
936
937        assert!(b.get_u8().is_err());
938        assert!(b.get_u16().is_err());
939        assert!(b.get_u24().is_err());
940        assert!(b.get_u32().is_err());
941        assert!(b.get_u64().is_err());
942    }
943
944    #[test]
945    fn get_u_mut() {
946        let mut d = [
947            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
948        ];
949
950        let mut b = OctetsMut::with_slice(&mut d);
951        assert_eq!(b.cap(), 18);
952        assert_eq!(b.off(), 0);
953
954        assert_eq!(b.get_u8().unwrap(), 1);
955        assert_eq!(b.cap(), 17);
956        assert_eq!(b.off(), 1);
957
958        assert_eq!(b.get_u16().unwrap(), 0x203);
959        assert_eq!(b.cap(), 15);
960        assert_eq!(b.off(), 3);
961
962        assert_eq!(b.get_u24().unwrap(), 0x40506);
963        assert_eq!(b.cap(), 12);
964        assert_eq!(b.off(), 6);
965
966        assert_eq!(b.get_u32().unwrap(), 0x0708090a);
967        assert_eq!(b.cap(), 8);
968        assert_eq!(b.off(), 10);
969
970        assert_eq!(b.get_u64().unwrap(), 0x0b0c0d0e0f101112);
971        assert_eq!(b.cap(), 0);
972        assert_eq!(b.off(), 18);
973
974        assert!(b.get_u8().is_err());
975        assert!(b.get_u16().is_err());
976        assert!(b.get_u24().is_err());
977        assert!(b.get_u32().is_err());
978        assert!(b.get_u64().is_err());
979    }
980
981    #[test]
982    fn peek_u() {
983        let d = [1, 2];
984
985        let mut b = Octets::with_slice(&d);
986        assert_eq!(b.cap(), 2);
987        assert_eq!(b.off(), 0);
988
989        assert_eq!(b.peek_u8().unwrap(), 1);
990        assert_eq!(b.cap(), 2);
991        assert_eq!(b.off(), 0);
992
993        assert_eq!(b.peek_u8().unwrap(), 1);
994        assert_eq!(b.cap(), 2);
995        assert_eq!(b.off(), 0);
996
997        b.get_u16().unwrap();
998
999        assert!(b.peek_u8().is_err());
1000    }
1001
1002    #[test]
1003    fn peek_u_mut() {
1004        let mut d = [1, 2];
1005
1006        let mut b = OctetsMut::with_slice(&mut d);
1007        assert_eq!(b.cap(), 2);
1008        assert_eq!(b.off(), 0);
1009
1010        assert_eq!(b.peek_u8().unwrap(), 1);
1011        assert_eq!(b.cap(), 2);
1012        assert_eq!(b.off(), 0);
1013
1014        assert_eq!(b.peek_u8().unwrap(), 1);
1015        assert_eq!(b.cap(), 2);
1016        assert_eq!(b.off(), 0);
1017
1018        b.get_u16().unwrap();
1019
1020        assert!(b.peek_u8().is_err());
1021    }
1022
1023    #[test]
1024    fn get_bytes() {
1025        let d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1026        let mut b = Octets::with_slice(&d);
1027        assert_eq!(b.cap(), 10);
1028        assert_eq!(b.off(), 0);
1029
1030        assert_eq!(b.get_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
1031        assert_eq!(b.cap(), 5);
1032        assert_eq!(b.off(), 5);
1033
1034        assert_eq!(b.get_bytes(3).unwrap().as_ref(), [6, 7, 8]);
1035        assert_eq!(b.cap(), 2);
1036        assert_eq!(b.off(), 8);
1037
1038        assert!(b.get_bytes(3).is_err());
1039        assert_eq!(b.cap(), 2);
1040        assert_eq!(b.off(), 8);
1041
1042        assert_eq!(b.get_bytes(2).unwrap().as_ref(), [9, 10]);
1043        assert_eq!(b.cap(), 0);
1044        assert_eq!(b.off(), 10);
1045
1046        assert!(b.get_bytes(2).is_err());
1047    }
1048
1049    #[test]
1050    fn get_bytes_mut() {
1051        let mut d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1052        let mut b = OctetsMut::with_slice(&mut d);
1053        assert_eq!(b.cap(), 10);
1054        assert_eq!(b.off(), 0);
1055
1056        assert_eq!(b.get_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
1057        assert_eq!(b.cap(), 5);
1058        assert_eq!(b.off(), 5);
1059
1060        assert_eq!(b.get_bytes(3).unwrap().as_ref(), [6, 7, 8]);
1061        assert_eq!(b.cap(), 2);
1062        assert_eq!(b.off(), 8);
1063
1064        assert!(b.get_bytes(3).is_err());
1065        assert_eq!(b.cap(), 2);
1066        assert_eq!(b.off(), 8);
1067
1068        assert_eq!(b.get_bytes(2).unwrap().as_ref(), [9, 10]);
1069        assert_eq!(b.cap(), 0);
1070        assert_eq!(b.off(), 10);
1071
1072        assert!(b.get_bytes(2).is_err());
1073    }
1074
1075    #[test]
1076    fn peek_bytes() {
1077        let d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1078        let mut b = Octets::with_slice(&d);
1079        assert_eq!(b.cap(), 10);
1080        assert_eq!(b.off(), 0);
1081
1082        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
1083        assert_eq!(b.cap(), 10);
1084        assert_eq!(b.off(), 0);
1085
1086        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
1087        assert_eq!(b.cap(), 10);
1088        assert_eq!(b.off(), 0);
1089
1090        b.get_bytes(5).unwrap();
1091    }
1092
1093    #[test]
1094    fn peek_bytes_mut() {
1095        let mut d = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1096        let mut b = OctetsMut::with_slice(&mut d);
1097        assert_eq!(b.cap(), 10);
1098        assert_eq!(b.off(), 0);
1099
1100        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
1101        assert_eq!(b.cap(), 10);
1102        assert_eq!(b.off(), 0);
1103
1104        assert_eq!(b.peek_bytes(5).unwrap().as_ref(), [1, 2, 3, 4, 5]);
1105        assert_eq!(b.cap(), 10);
1106        assert_eq!(b.off(), 0);
1107
1108        b.get_bytes(5).unwrap();
1109    }
1110
1111    #[test]
1112    fn get_varint() {
1113        let d = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
1114        let mut b = Octets::with_slice(&d);
1115        assert_eq!(b.get_varint().unwrap(), 151288809941952652);
1116        assert_eq!(b.cap(), 0);
1117        assert_eq!(b.off(), 8);
1118
1119        let d = [0x9d, 0x7f, 0x3e, 0x7d];
1120        let mut b = Octets::with_slice(&d);
1121        assert_eq!(b.get_varint().unwrap(), 494878333);
1122        assert_eq!(b.cap(), 0);
1123        assert_eq!(b.off(), 4);
1124
1125        let d = [0x7b, 0xbd];
1126        let mut b = Octets::with_slice(&d);
1127        assert_eq!(b.get_varint().unwrap(), 15293);
1128        assert_eq!(b.cap(), 0);
1129        assert_eq!(b.off(), 2);
1130
1131        let d = [0x40, 0x25];
1132        let mut b = Octets::with_slice(&d);
1133        assert_eq!(b.get_varint().unwrap(), 37);
1134        assert_eq!(b.cap(), 0);
1135        assert_eq!(b.off(), 2);
1136
1137        let d = [0x25];
1138        let mut b = Octets::with_slice(&d);
1139        assert_eq!(b.get_varint().unwrap(), 37);
1140        assert_eq!(b.cap(), 0);
1141        assert_eq!(b.off(), 1);
1142    }
1143
1144    #[test]
1145    fn get_varint_mut() {
1146        let mut d = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
1147        let mut b = OctetsMut::with_slice(&mut d);
1148        assert_eq!(b.get_varint().unwrap(), 151288809941952652);
1149        assert_eq!(b.cap(), 0);
1150        assert_eq!(b.off(), 8);
1151
1152        let mut d = [0x9d, 0x7f, 0x3e, 0x7d];
1153        let mut b = OctetsMut::with_slice(&mut d);
1154        assert_eq!(b.get_varint().unwrap(), 494878333);
1155        assert_eq!(b.cap(), 0);
1156        assert_eq!(b.off(), 4);
1157
1158        let mut d = [0x7b, 0xbd];
1159        let mut b = OctetsMut::with_slice(&mut d);
1160        assert_eq!(b.get_varint().unwrap(), 15293);
1161        assert_eq!(b.cap(), 0);
1162        assert_eq!(b.off(), 2);
1163
1164        let mut d = [0x40, 0x25];
1165        let mut b = OctetsMut::with_slice(&mut d);
1166        assert_eq!(b.get_varint().unwrap(), 37);
1167        assert_eq!(b.cap(), 0);
1168        assert_eq!(b.off(), 2);
1169
1170        let mut d = [0x25];
1171        let mut b = OctetsMut::with_slice(&mut d);
1172        assert_eq!(b.get_varint().unwrap(), 37);
1173        assert_eq!(b.cap(), 0);
1174        assert_eq!(b.off(), 1);
1175    }
1176
1177    #[cfg(feature = "huffman_hpack")]
1178    #[test]
1179    fn invalid_huffman() {
1180        // Extra non-zero padding byte at the end.
1181        let mut b = Octets::with_slice(
1182            b"\x00\x85\xf2\xb2\x4a\x84\xff\x84\x49\x50\x9f\xff",
1183        );
1184        assert!(b.get_huffman_decoded().is_err());
1185
1186        // Zero padded.
1187        let mut b =
1188            Octets::with_slice(b"\x00\x85\xf2\xb2\x4a\x84\xff\x83\x49\x50\x90");
1189        assert!(b.get_huffman_decoded().is_err());
1190
1191        // Non-final EOS symbol.
1192        let mut b = Octets::with_slice(
1193            b"\x00\x85\xf2\xb2\x4a\x84\xff\x87\x49\x51\xff\xff\xff\xfa\x7f",
1194        );
1195        assert!(b.get_huffman_decoded().is_err());
1196
1197        // Huffman too long.
1198        let mut b = Octets::with_slice(
1199            b"\x00\x85\xf2\xb2\x4a\x84\xff\x87\x49\x51\xff\xff\xff\xfa\x7f",
1200        );
1201        assert!(b.get_huffman_decoded_with_max_length(4).is_err());
1202    }
1203
1204    #[test]
1205    fn put_varint() {
1206        let mut d = [0; 8];
1207        {
1208            let mut b = OctetsMut::with_slice(&mut d);
1209            assert!(b.put_varint(151288809941952652).is_ok());
1210            assert_eq!(b.cap(), 0);
1211            assert_eq!(b.off(), 8);
1212        }
1213        let exp = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
1214        assert_eq!(&d, &exp);
1215
1216        let mut d = [0; 4];
1217        {
1218            let mut b = OctetsMut::with_slice(&mut d);
1219            assert!(b.put_varint(494878333).is_ok());
1220            assert_eq!(b.cap(), 0);
1221            assert_eq!(b.off(), 4);
1222        }
1223        let exp = [0x9d, 0x7f, 0x3e, 0x7d];
1224        assert_eq!(&d, &exp);
1225
1226        let mut d = [0; 2];
1227        {
1228            let mut b = OctetsMut::with_slice(&mut d);
1229            assert!(b.put_varint(15293).is_ok());
1230            assert_eq!(b.cap(), 0);
1231            assert_eq!(b.off(), 2);
1232        }
1233        let exp = [0x7b, 0xbd];
1234        assert_eq!(&d, &exp);
1235
1236        let mut d = [0; 1];
1237        {
1238            let mut b = OctetsMut::with_slice(&mut d);
1239            assert!(b.put_varint(37).is_ok());
1240            assert_eq!(b.cap(), 0);
1241            assert_eq!(b.off(), 1);
1242        }
1243        let exp = [0x25];
1244        assert_eq!(&d, &exp);
1245
1246        let mut d = [0; 3];
1247        {
1248            let mut b = OctetsMut::with_slice(&mut d);
1249            assert!(b.put_varint(151288809941952652).is_err());
1250            assert_eq!(b.cap(), 3);
1251            assert_eq!(b.off(), 0);
1252        }
1253        let exp = [0; 3];
1254        assert_eq!(&d, &exp);
1255    }
1256
1257    #[test]
1258    #[should_panic]
1259    fn varint_too_large() {
1260        let mut d = [0; 3];
1261        let mut b = OctetsMut::with_slice(&mut d);
1262        assert!(b.put_varint(u64::MAX).is_err());
1263    }
1264
1265    #[test]
1266    fn put_u() {
1267        let mut d = [0; 18];
1268
1269        {
1270            let mut b = OctetsMut::with_slice(&mut d);
1271            assert_eq!(b.cap(), 18);
1272            assert_eq!(b.off(), 0);
1273
1274            assert!(b.put_u8(1).is_ok());
1275            assert_eq!(b.cap(), 17);
1276            assert_eq!(b.off(), 1);
1277
1278            assert!(b.put_u16(0x203).is_ok());
1279            assert_eq!(b.cap(), 15);
1280            assert_eq!(b.off(), 3);
1281
1282            assert!(b.put_u24(0x40506).is_ok());
1283            assert_eq!(b.cap(), 12);
1284            assert_eq!(b.off(), 6);
1285
1286            assert!(b.put_u32(0x0708090a).is_ok());
1287            assert_eq!(b.cap(), 8);
1288            assert_eq!(b.off(), 10);
1289
1290            assert!(b.put_u64(0x0b0c0d0e0f101112).is_ok());
1291            assert_eq!(b.cap(), 0);
1292            assert_eq!(b.off(), 18);
1293
1294            assert!(b.put_u8(1).is_err());
1295        }
1296
1297        let exp = [
1298            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
1299        ];
1300        assert_eq!(&d, &exp);
1301    }
1302
1303    #[test]
1304    fn put_bytes() {
1305        let mut d = [0; 5];
1306
1307        {
1308            let mut b = OctetsMut::with_slice(&mut d);
1309            assert_eq!(b.cap(), 5);
1310            assert_eq!(b.off(), 0);
1311
1312            let p = [0x0a, 0x0b, 0x0c, 0x0d, 0x0e];
1313            assert!(b.put_bytes(&p).is_ok());
1314            assert_eq!(b.cap(), 0);
1315            assert_eq!(b.off(), 5);
1316
1317            assert!(b.put_u8(1).is_err());
1318        }
1319
1320        let exp = [0xa, 0xb, 0xc, 0xd, 0xe];
1321        assert_eq!(&d, &exp);
1322    }
1323
1324    #[test]
1325    fn rewind() {
1326        let d = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
1327        let mut b = Octets::with_slice(&d);
1328        assert_eq!(b.get_varint().unwrap(), 151288809941952652);
1329        assert_eq!(b.cap(), 0);
1330        assert_eq!(b.off(), 8);
1331
1332        assert_eq!(b.rewind(4), Ok(()));
1333        assert_eq!(b.cap(), 4);
1334        assert_eq!(b.off(), 4);
1335
1336        assert_eq!(b.get_u8().unwrap(), 0xff);
1337        assert_eq!(b.cap(), 3);
1338        assert_eq!(b.off(), 5);
1339
1340        assert!(b.rewind(6).is_err());
1341
1342        assert_eq!(b.rewind(5), Ok(()));
1343        assert_eq!(b.cap(), 8);
1344        assert_eq!(b.off(), 0);
1345
1346        assert!(b.rewind(1).is_err());
1347    }
1348
1349    #[test]
1350    fn rewind_mut() {
1351        let mut d = [0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c];
1352        let mut b = OctetsMut::with_slice(&mut d);
1353        assert_eq!(b.get_varint().unwrap(), 151288809941952652);
1354        assert_eq!(b.cap(), 0);
1355        assert_eq!(b.off(), 8);
1356
1357        assert_eq!(b.rewind(4), Ok(()));
1358        assert_eq!(b.cap(), 4);
1359        assert_eq!(b.off(), 4);
1360
1361        assert_eq!(b.get_u8().unwrap(), 0xff);
1362        assert_eq!(b.cap(), 3);
1363        assert_eq!(b.off(), 5);
1364
1365        assert!(b.rewind(6).is_err());
1366
1367        assert_eq!(b.rewind(5), Ok(()));
1368        assert_eq!(b.cap(), 8);
1369        assert_eq!(b.off(), 0);
1370
1371        assert!(b.rewind(1).is_err());
1372    }
1373
1374    #[test]
1375    fn split() {
1376        let mut d = b"helloworld".to_vec();
1377
1378        let mut b = OctetsMut::with_slice(&mut d);
1379        assert_eq!(b.cap(), 10);
1380        assert_eq!(b.off(), 0);
1381        assert_eq!(b.as_ref(), b"helloworld");
1382
1383        assert!(b.get_bytes(5).is_ok());
1384        assert_eq!(b.cap(), 5);
1385        assert_eq!(b.off(), 5);
1386        assert_eq!(b.as_ref(), b"world");
1387
1388        let off = b.off();
1389
1390        let (first, last) = b.split_at(off).unwrap();
1391        assert_eq!(first.cap(), 5);
1392        assert_eq!(first.off(), 0);
1393        assert_eq!(first.as_ref(), b"hello");
1394
1395        assert_eq!(last.cap(), 5);
1396        assert_eq!(last.off(), 0);
1397        assert_eq!(last.as_ref(), b"world");
1398    }
1399
1400    #[test]
1401    fn split_at() {
1402        let mut d = b"helloworld".to_vec();
1403
1404        {
1405            let mut b = OctetsMut::with_slice(&mut d);
1406            let (first, second) = b.split_at(5).unwrap();
1407
1408            let mut exp1 = b"hello".to_vec();
1409            assert_eq!(first.as_ref(), &mut exp1[..]);
1410
1411            let mut exp2 = b"world".to_vec();
1412            assert_eq!(second.as_ref(), &mut exp2[..]);
1413        }
1414
1415        {
1416            let mut b = OctetsMut::with_slice(&mut d);
1417            let (first, second) = b.split_at(10).unwrap();
1418
1419            let mut exp1 = b"helloworld".to_vec();
1420            assert_eq!(first.as_ref(), &mut exp1[..]);
1421
1422            let mut exp2 = b"".to_vec();
1423            assert_eq!(second.as_ref(), &mut exp2[..]);
1424        }
1425
1426        {
1427            let mut b = OctetsMut::with_slice(&mut d);
1428            let (first, second) = b.split_at(9).unwrap();
1429
1430            let mut exp1 = b"helloworl".to_vec();
1431            assert_eq!(first.as_ref(), &mut exp1[..]);
1432
1433            let mut exp2 = b"d".to_vec();
1434            assert_eq!(second.as_ref(), &mut exp2[..]);
1435        }
1436
1437        {
1438            let mut b = OctetsMut::with_slice(&mut d);
1439            assert!(b.split_at(11).is_err());
1440        }
1441    }
1442
1443    #[test]
1444    fn slice() {
1445        let d = b"helloworld".to_vec();
1446
1447        {
1448            let b = Octets::with_slice(&d);
1449            let exp = b"hello".to_vec();
1450            assert_eq!(b.slice(5), Ok(&exp[..]));
1451        }
1452
1453        {
1454            let b = Octets::with_slice(&d);
1455            let exp = b"".to_vec();
1456            assert_eq!(b.slice(0), Ok(&exp[..]));
1457        }
1458
1459        {
1460            let mut b = Octets::with_slice(&d);
1461            b.get_bytes(5).unwrap();
1462
1463            let exp = b"world".to_vec();
1464            assert_eq!(b.slice(5), Ok(&exp[..]));
1465        }
1466
1467        {
1468            let b = Octets::with_slice(&d);
1469            assert!(b.slice(11).is_err());
1470        }
1471    }
1472
1473    #[test]
1474    fn slice_mut() {
1475        let mut d = b"helloworld".to_vec();
1476
1477        {
1478            let mut b = OctetsMut::with_slice(&mut d);
1479            let mut exp = b"hello".to_vec();
1480            assert_eq!(b.slice(5), Ok(&mut exp[..]));
1481        }
1482
1483        {
1484            let mut b = OctetsMut::with_slice(&mut d);
1485            let mut exp = b"".to_vec();
1486            assert_eq!(b.slice(0), Ok(&mut exp[..]));
1487        }
1488
1489        {
1490            let mut b = OctetsMut::with_slice(&mut d);
1491            b.get_bytes(5).unwrap();
1492
1493            let mut exp = b"world".to_vec();
1494            assert_eq!(b.slice(5), Ok(&mut exp[..]));
1495        }
1496
1497        {
1498            let mut b = OctetsMut::with_slice(&mut d);
1499            assert!(b.slice(11).is_err());
1500        }
1501    }
1502
1503    #[test]
1504    fn slice_last() {
1505        let d = b"helloworld".to_vec();
1506
1507        {
1508            let b = Octets::with_slice(&d);
1509            let exp = b"orld".to_vec();
1510            assert_eq!(b.slice_last(4), Ok(&exp[..]));
1511        }
1512
1513        {
1514            let mut b = Octets::with_slice(&d);
1515            b.get_bytes(5).unwrap();
1516            let exp = b"orld".to_vec();
1517            assert_eq!(b.slice_last(4), Ok(&exp[..]));
1518        }
1519
1520        {
1521            let b = Octets::with_slice(&d);
1522            let exp = b"d".to_vec();
1523            assert_eq!(b.slice_last(1), Ok(&exp[..]));
1524        }
1525
1526        {
1527            let b = Octets::with_slice(&d);
1528            let exp = b"".to_vec();
1529            assert_eq!(b.slice_last(0), Ok(&exp[..]));
1530        }
1531
1532        {
1533            let b = Octets::with_slice(&d);
1534            let exp = b"helloworld".to_vec();
1535            assert_eq!(b.slice_last(10), Ok(&exp[..]));
1536        }
1537
1538        {
1539            let b = Octets::with_slice(&d);
1540            assert!(b.slice_last(11).is_err());
1541        }
1542    }
1543
1544    #[test]
1545    fn slice_last_mut() {
1546        let mut d = b"helloworld".to_vec();
1547
1548        {
1549            let mut b = OctetsMut::with_slice(&mut d);
1550            let mut exp = b"orld".to_vec();
1551            assert_eq!(b.slice_last(4), Ok(&mut exp[..]));
1552        }
1553
1554        {
1555            let mut b = OctetsMut::with_slice(&mut d);
1556            b.get_bytes(5).unwrap();
1557            let mut exp = b"orld".to_vec();
1558            assert_eq!(b.slice_last(4), Ok(&mut exp[..]));
1559        }
1560
1561        {
1562            let mut b = OctetsMut::with_slice(&mut d);
1563            let mut exp = b"d".to_vec();
1564            assert_eq!(b.slice_last(1), Ok(&mut exp[..]));
1565        }
1566
1567        {
1568            let mut b = OctetsMut::with_slice(&mut d);
1569            let mut exp = b"".to_vec();
1570            assert_eq!(b.slice_last(0), Ok(&mut exp[..]));
1571        }
1572
1573        {
1574            let mut b = OctetsMut::with_slice(&mut d);
1575            let mut exp = b"helloworld".to_vec();
1576            assert_eq!(b.slice_last(10), Ok(&mut exp[..]));
1577        }
1578
1579        {
1580            let mut b = OctetsMut::with_slice(&mut d);
1581            assert!(b.slice_last(11).is_err());
1582        }
1583    }
1584}
1585
1586#[cfg(feature = "huffman_hpack")]
1587mod huffman_table;