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