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