Skip to main content

octets/
lib.rs

1// Copyright (C) 2018-2019, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright notice,
9//       this list of conditions and the following disclaimer.
10//
11//     * Redistributions in binary form must reproduce the above copyright
12//       notice, this list of conditions and the following disclaimer in the
13//       documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27#![forbid(unsafe_code)]
28
29/// Zero-copy abstraction for parsing and constructing network packets.
30use std::mem;
31
32/// Maximum value that can be encoded via varint.
33pub const MAX_VAR_INT: u64 = 4_611_686_018_427_387_903;
34
35/// A specialized [`Result`] type for [`OctetsMut`] operations.
36///
37/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
38/// [`OctetsMut`]: struct.OctetsMut.html
39pub type Result<T> = std::result::Result<T, BufferTooShortError>;
40
41/// An error indicating that the provided [`OctetsMut`] is not big enough.
42///
43/// [`OctetsMut`]: struct.OctetsMut.html
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct BufferTooShortError;
46
47impl std::fmt::Display for BufferTooShortError {
48    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
49        write!(f, "BufferTooShortError")
50    }
51}
52
53impl std::error::Error for BufferTooShortError {
54    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
55        None
56    }
57}
58
59/// A byte sink for encoders in this crate.
60///
61/// This lets callers use octets encoders with output targets other than a
62/// single contiguous [`OctetsMut`] buffer.
63pub trait OctetsWriter {
64    /// The error returned by the output sink.
65    type Error;
66
67    /// Writes `v` to the output sink.
68    fn put_bytes(&mut self, v: &[u8]) -> std::result::Result<(), Self::Error>;
69
70    /// Writes `v` to the output sink after HPACK Huffman-encoding it.
71    ///
72    /// The Huffman code implemented is the one defined for HPACK (RFC7541).
73    ///
74    /// Encoding is not atomic. An error can be returned after writing part of
75    /// the output, so callers cannot safely retry unless the sink discards the
76    /// partial output. Sinks that perform irreversible writes, such as sending
77    /// data over the network, must buffer the output or guarantee success.
78    #[cfg(feature = "huffman_hpack")]
79    fn put_huffman_encoded<const LOWER_CASE: bool>(
80        &mut self, v: &[u8],
81    ) -> std::result::Result<(), Self::Error>
82    where
83        Self: Sized,
84    {
85        huffman_encode_with::<LOWER_CASE, _, _>(v, |chunk| self.put_bytes(chunk))
86    }
87}
88
89/// Helper macro that asserts at compile time. It requires that
90/// `cond` is a const expression.
91macro_rules! static_assert {
92    ($cond:expr) => {{
93        const _: () = assert!($cond);
94    }};
95}
96
97macro_rules! peek_u {
98    ($b:expr, $ty:ty, $len:expr) => {{
99        let len = $len;
100        let src = &$b.buf[$b.off..];
101
102        if src.len() < len {
103            return Err(BufferTooShortError);
104        }
105
106        static_assert!($len <= mem::size_of::<$ty>());
107        let mut out = [0; mem::size_of::<$ty>()];
108        out[mem::size_of::<$ty>() - len..].copy_from_slice(&src[..len]);
109
110        Ok(<$ty>::from_be_bytes(out))
111    }};
112}
113
114macro_rules! get_u {
115    ($b:expr, $ty:ty, $len:expr) => {{
116        let out = peek_u!($b, $ty, $len);
117
118        $b.off += $len;
119
120        out
121    }};
122}
123
124macro_rules! put_u {
125    ($b:expr, $ty:ty, $v:expr, $len:expr) => {{
126        let len = $len;
127
128        if $b.buf.len() < $b.off + len {
129            return Err(BufferTooShortError);
130        }
131
132        let v = $v;
133
134        let dst = &mut $b.buf[$b.off..($b.off + len)];
135
136        static_assert!($len <= mem::size_of::<$ty>());
137        let src = <$ty>::to_be_bytes(v);
138        dst.copy_from_slice(&src[mem::size_of::<$ty>() - len..]);
139
140        $b.off += $len;
141
142        Ok(dst)
143    }};
144}
145
146/// A zero-copy immutable byte buffer.
147///
148/// `Octets` wraps an in-memory buffer of bytes and provides utility functions
149/// for manipulating it. The underlying buffer is provided by the user and is
150/// not copied when creating an `Octets`. Operations are panic-free and will
151/// avoid indexing the buffer past its end.
152///
153/// Additionally, an offset (initially set to the start of the buffer) is
154/// incremented as bytes are read from / written to the buffer, to allow for
155/// sequential operations.
156#[derive(Debug, PartialEq, Eq)]
157pub struct Octets<'a> {
158    buf: &'a [u8],
159    off: usize,
160}
161
162impl<'a> Octets<'a> {
163    /// Creates an `Octets` from the given slice, without copying.
164    ///
165    /// Since the `Octets` is immutable, the input slice needs to be
166    /// immutable.
167    pub fn with_slice(buf: &'a [u8]) -> Self {
168        Octets { buf, off: 0 }
169    }
170
171    /// Reads an unsigned 8-bit integer from the current offset and advances
172    /// the buffer.
173    pub fn get_u8(&mut self) -> Result<u8> {
174        get_u!(self, u8, 1)
175    }
176
177    /// Reads an unsigned 8-bit integer from the current offset without
178    /// advancing the buffer.
179    pub fn peek_u8(&mut self) -> Result<u8> {
180        peek_u!(self, u8, 1)
181    }
182
183    /// Reads an unsigned 16-bit integer in network byte-order from the current
184    /// offset and advances the buffer.
185    pub fn get_u16(&mut self) -> Result<u16> {
186        get_u!(self, u16, 2)
187    }
188
189    /// Reads an unsigned 24-bit integer in network byte-order from the current
190    /// offset and advances the buffer.
191    pub fn get_u24(&mut self) -> Result<u32> {
192        get_u!(self, u32, 3)
193    }
194
195    /// Reads an unsigned 32-bit integer in network byte-order from the current
196    /// offset and advances the buffer.
197    pub fn get_u32(&mut self) -> Result<u32> {
198        get_u!(self, u32, 4)
199    }
200
201    /// Reads an unsigned 64-bit integer in network byte-order from the current
202    /// offset and advances the buffer.
203    pub fn get_u64(&mut self) -> Result<u64> {
204        get_u!(self, u64, 8)
205    }
206
207    /// Reads an unsigned variable-length integer in network byte-order from
208    /// the current offset and advances the buffer.
209    pub fn get_varint(&mut self) -> Result<u64> {
210        let first = self.peek_u8()?;
211
212        let len = varint_parse_len(first);
213
214        if len > self.cap() {
215            return Err(BufferTooShortError);
216        }
217
218        let out = match len {
219            1 => u64::from(self.get_u8()?),
220
221            2 => u64::from(self.get_u16()? & 0x3fff),
222
223            4 => u64::from(self.get_u32()? & 0x3fffffff),
224
225            8 => self.get_u64()? & 0x3fffffffffffffff,
226
227            _ => unreachable!(),
228        };
229
230        Ok(out)
231    }
232
233    /// Reads `len` bytes from the current offset without copying and advances
234    /// the buffer.
235    pub fn get_bytes(&mut self, len: usize) -> Result<Octets<'a>> {
236        if self.cap() < len {
237            return Err(BufferTooShortError);
238        }
239
240        let out = Octets {
241            buf: &self.buf[self.off..self.off + len],
242            off: 0,
243        };
244
245        self.off += len;
246
247        Ok(out)
248    }
249
250    /// Reads `len` bytes from the current offset without copying and advances
251    /// the buffer, where `len` is an unsigned 8-bit integer prefix.
252    pub fn get_bytes_with_u8_length(&mut self) -> Result<Octets<'a>> {
253        let len = self.get_u8()?;
254        self.get_bytes(len as usize)
255    }
256
257    /// Reads `len` bytes from the current offset without copying and advances
258    /// the buffer, where `len` is an unsigned 16-bit integer prefix in network
259    /// byte-order.
260    pub fn get_bytes_with_u16_length(&mut self) -> Result<Octets<'a>> {
261        let len = self.get_u16()?;
262        self.get_bytes(len as usize)
263    }
264
265    /// Reads `len` bytes from the current offset without copying and advances
266    /// the buffer, where `len` is an unsigned variable-length integer prefix
267    /// in network byte-order.
268    pub fn get_bytes_with_varint_length(&mut self) -> Result<Octets<'a>> {
269        let len = self.get_varint()?;
270        self.get_bytes(len as usize)
271    }
272
273    /// Decodes a Huffman-encoded value from the current offset.
274    ///
275    /// The Huffman code implemented is the one defined for HPACK (RFC7541).
276    #[cfg(feature = "huffman_hpack")]
277    pub fn get_huffman_decoded(&mut self) -> Result<Vec<u8>> {
278        self.get_huffman_decoded_with_max_length(usize::MAX)
279    }
280
281    /// Decodes a Huffman-encoded value from the current offset. The `max_len`
282    /// parameter controls the maximum length of the decoded value.
283    ///
284    /// The Huffman code implemented is the one defined for HPACK (RFC7541).
285    #[cfg(feature = "huffman_hpack")]
286    pub fn get_huffman_decoded_with_max_length(
287        &mut self, max_len: usize,
288    ) -> Result<Vec<u8>> {
289        use self::huffman_table::DECODE_TABLE;
290
291        const FLAG_END: u8 = 1;
292        const FLAG_SYM: u8 = 2;
293        const FLAG_ERR: u8 = 4;
294
295        // Max compression ratio is >= 0.5.
296        let initial_cap = std::cmp::min(self.cap() * 2, max_len);
297        let mut out = Vec::with_capacity(initial_cap);
298
299        let mut state = 0;
300        let mut eos = false;
301
302        while let Ok(byte) = self.get_u8() {
303            for data in [byte >> 4, byte & 0xf] {
304                let (next, sym, flags) = DECODE_TABLE[state][(data) as usize];
305
306                if flags & FLAG_ERR == FLAG_ERR {
307                    // Data followed the "end" marker.
308                    return Err(BufferTooShortError);
309                } else if flags & FLAG_SYM == FLAG_SYM {
310                    // Error if pushing sym (1 byte) would overflow.
311                    if out.len() + 1 > max_len {
312                        return Err(BufferTooShortError);
313                    }
314                    out.push(sym);
315                }
316
317                state = next;
318
319                // `eos` only correct when handling the byte & 0xf case; ignored
320                // and overwritten in the byte >> 4 case.
321                eos = flags & FLAG_END == FLAG_END;
322            }
323        }
324
325        if state != 0 && !eos {
326            return Err(BufferTooShortError);
327        }
328
329        Ok(out)
330    }
331
332    /// Reads `len` bytes from the current offset without copying and without
333    /// advancing the buffer.
334    pub fn peek_bytes(&self, len: usize) -> Result<Octets<'a>> {
335        if self.cap() < len {
336            return Err(BufferTooShortError);
337        }
338
339        let out = Octets {
340            buf: &self.buf[self.off..self.off + len],
341            off: 0,
342        };
343
344        Ok(out)
345    }
346
347    /// Rewinds the buffer offset by `len` elements.
348    pub fn rewind(&mut self, len: usize) -> Result<()> {
349        if self.off() < len {
350            return Err(BufferTooShortError);
351        }
352
353        self.off -= len;
354
355        Ok(())
356    }
357
358    /// Returns a slice of `len` elements from the current offset.
359    pub fn slice(&self, len: usize) -> Result<&'a [u8]> {
360        if len > self.cap() {
361            return Err(BufferTooShortError);
362        }
363
364        Ok(&self.buf[self.off..self.off + len])
365    }
366
367    /// Returns a slice of `len` elements from the end of the buffer.
368    pub fn slice_last(&self, len: usize) -> Result<&'a [u8]> {
369        if len > self.cap() {
370            return Err(BufferTooShortError);
371        }
372
373        let end = self.buf.len();
374        Ok(&self.buf[end - len..end])
375    }
376
377    /// Advances the buffer's offset.
378    pub fn skip(&mut self, skip: usize) -> Result<()> {
379        if skip > self.cap() {
380            return Err(BufferTooShortError);
381        }
382
383        self.off += skip;
384
385        Ok(())
386    }
387
388    /// Returns the remaining capacity in the buffer.
389    pub fn cap(&self) -> usize {
390        self.buf.len() - self.off
391    }
392
393    /// Returns the total length of the buffer.
394    pub fn len(&self) -> usize {
395        self.buf.len()
396    }
397
398    /// Returns `true` if the buffer is empty.
399    pub fn is_empty(&self) -> bool {
400        self.buf.len() == 0
401    }
402
403    /// Returns the current offset of the buffer.
404    pub fn off(&self) -> usize {
405        self.off
406    }
407
408    /// Returns a reference to the internal buffer.
409    pub fn buf(&self) -> &'a [u8] {
410        self.buf
411    }
412
413    /// Copies the buffer from the current offset into a new `Vec<u8>`.
414    pub fn to_vec(&self) -> Vec<u8> {
415        self.as_ref().to_vec()
416    }
417}
418
419impl AsRef<[u8]> for Octets<'_> {
420    fn as_ref(&self) -> &[u8] {
421        &self.buf[self.off..]
422    }
423}
424
425/// A zero-copy mutable byte buffer.
426///
427/// Like `Octets` but mutable.
428#[derive(Debug, PartialEq, Eq)]
429pub struct OctetsMut<'a> {
430    buf: &'a mut [u8],
431    off: usize,
432}
433
434impl<'a> OctetsMut<'a> {
435    /// Creates an `OctetsMut` from the given slice, without copying.
436    ///
437    /// Since there's no copy, the input slice needs to be mutable to allow
438    /// modifications.
439    pub fn with_slice(buf: &'a mut [u8]) -> Self {
440        OctetsMut { buf, off: 0 }
441    }
442
443    /// Reads an unsigned 8-bit integer from the current offset and advances
444    /// the buffer.
445    pub fn get_u8(&mut self) -> Result<u8> {
446        get_u!(self, u8, 1)
447    }
448
449    /// Reads an unsigned 8-bit integer from the current offset without
450    /// advancing the buffer.
451    pub fn peek_u8(&mut self) -> Result<u8> {
452        peek_u!(self, u8, 1)
453    }
454
455    /// Writes an unsigned 8-bit integer at the current offset and advances
456    /// the buffer.
457    pub fn put_u8(&mut self, v: u8) -> Result<&mut [u8]> {
458        put_u!(self, u8, v, 1)
459    }
460
461    /// Reads an unsigned 16-bit integer in network byte-order from the current
462    /// offset and advances the buffer.
463    pub fn get_u16(&mut self) -> Result<u16> {
464        get_u!(self, u16, 2)
465    }
466
467    /// Writes an unsigned 16-bit integer in network byte-order at the current
468    /// offset and advances the buffer.
469    pub fn put_u16(&mut self, v: u16) -> Result<&mut [u8]> {
470        put_u!(self, u16, v, 2)
471    }
472
473    /// Reads an unsigned 24-bit integer in network byte-order from the current
474    /// offset and advances the buffer.
475    pub fn get_u24(&mut self) -> Result<u32> {
476        get_u!(self, u32, 3)
477    }
478
479    /// Writes an unsigned 24-bit integer in network byte-order at the current
480    /// offset and advances the buffer.
481    pub fn put_u24(&mut self, v: u32) -> Result<&mut [u8]> {
482        put_u!(self, u32, v, 3)
483    }
484
485    /// Reads an unsigned 32-bit integer in network byte-order from the current
486    /// offset and advances the buffer.
487    pub fn get_u32(&mut self) -> Result<u32> {
488        get_u!(self, u32, 4)
489    }
490
491    /// Writes an unsigned 32-bit integer in network byte-order at the current
492    /// offset and advances the buffer.
493    pub fn put_u32(&mut self, v: u32) -> Result<&mut [u8]> {
494        put_u!(self, u32, v, 4)
495    }
496
497    /// Reads an unsigned 64-bit integer in network byte-order from the current
498    /// offset and advances the buffer.
499    pub fn get_u64(&mut self) -> Result<u64> {
500        get_u!(self, u64, 8)
501    }
502
503    /// Writes an unsigned 64-bit integer in network byte-order at the current
504    /// offset and advances the buffer.
505    pub fn put_u64(&mut self, v: u64) -> Result<&mut [u8]> {
506        put_u!(self, u64, v, 8)
507    }
508
509    /// Reads an unsigned variable-length integer in network byte-order from
510    /// the current offset and advances the buffer.
511    pub fn get_varint(&mut self) -> Result<u64> {
512        let first = self.peek_u8()?;
513
514        let len = varint_parse_len(first);
515
516        if len > self.cap() {
517            return Err(BufferTooShortError);
518        }
519
520        let out = match len {
521            1 => u64::from(self.get_u8()?),
522
523            2 => u64::from(self.get_u16()? & 0x3fff),
524
525            4 => u64::from(self.get_u32()? & 0x3fffffff),
526
527            8 => self.get_u64()? & 0x3fffffffffffffff,
528
529            _ => unreachable!(),
530        };
531
532        Ok(out)
533    }
534
535    /// Writes an unsigned variable-length integer in network byte-order at the
536    /// current offset and advances the buffer.
537    pub fn put_varint(&mut self, v: u64) -> Result<&mut [u8]> {
538        self.put_varint_with_len(v, varint_len(v))
539    }
540
541    /// Writes an unsigned variable-length integer of the specified length, in
542    /// network byte-order at the current offset and advances the buffer.
543    pub fn put_varint_with_len(
544        &mut self, v: u64, len: usize,
545    ) -> Result<&mut [u8]> {
546        if self.cap() < len {
547            return Err(BufferTooShortError);
548        }
549
550        let buf = match len {
551            1 => self.put_u8(v as u8)?,
552
553            2 => {
554                let buf = self.put_u16(v as u16)?;
555                buf[0] |= 0x40;
556                buf
557            },
558
559            4 => {
560                let buf = self.put_u32(v as u32)?;
561                buf[0] |= 0x80;
562                buf
563            },
564
565            8 => {
566                let buf = self.put_u64(v)?;
567                buf[0] |= 0xc0;
568                buf
569            },
570
571            _ => panic!("value is too large for varint"),
572        };
573
574        Ok(buf)
575    }
576
577    /// Reads `len` bytes from the current offset without copying and advances
578    /// the buffer.
579    pub fn get_bytes(&mut self, len: usize) -> Result<Octets<'_>> {
580        if self.cap() < len {
581            return Err(BufferTooShortError);
582        }
583
584        let out = Octets {
585            buf: &self.buf[self.off..self.off + len],
586            off: 0,
587        };
588
589        self.off += len;
590
591        Ok(out)
592    }
593
594    /// Reads `len` bytes from the current offset without copying and advances
595    /// the buffer.
596    pub fn get_bytes_mut(&mut self, len: usize) -> Result<OctetsMut<'_>> {
597        if self.cap() < len {
598            return Err(BufferTooShortError);
599        }
600
601        let out = OctetsMut {
602            buf: &mut self.buf[self.off..self.off + len],
603            off: 0,
604        };
605
606        self.off += len;
607
608        Ok(out)
609    }
610
611    /// Reads `len` bytes from the current offset without copying and advances
612    /// the buffer, where `len` is an unsigned 8-bit integer prefix.
613    pub fn get_bytes_with_u8_length(&mut self) -> Result<Octets<'_>> {
614        let len = self.get_u8()?;
615        self.get_bytes(len as usize)
616    }
617
618    /// Reads `len` bytes from the current offset without copying and advances
619    /// the buffer, where `len` is an unsigned 16-bit integer prefix in network
620    /// byte-order.
621    pub fn get_bytes_with_u16_length(&mut self) -> Result<Octets<'_>> {
622        let len = self.get_u16()?;
623        self.get_bytes(len as usize)
624    }
625
626    /// Reads `len` bytes from the current offset without copying and advances
627    /// the buffer, where `len` is an unsigned variable-length integer prefix
628    /// in network byte-order.
629    pub fn get_bytes_with_varint_length(&mut self) -> Result<Octets<'_>> {
630        let len = self.get_varint()?;
631        self.get_bytes(len as usize)
632    }
633
634    /// Reads `len` bytes from the current offset without copying and without
635    /// advancing the buffer.
636    pub fn peek_bytes(&mut self, len: usize) -> Result<Octets<'_>> {
637        if self.cap() < len {
638            return Err(BufferTooShortError);
639        }
640
641        let out = Octets {
642            buf: &self.buf[self.off..self.off + len],
643            off: 0,
644        };
645
646        Ok(out)
647    }
648
649    /// Reads `len` bytes from the current offset without copying and without
650    /// advancing the buffer.
651    pub fn peek_bytes_mut(&mut self, len: usize) -> Result<OctetsMut<'_>> {
652        if self.cap() < len {
653            return Err(BufferTooShortError);
654        }
655
656        let out = OctetsMut {
657            buf: &mut self.buf[self.off..self.off + len],
658            off: 0,
659        };
660
661        Ok(out)
662    }
663
664    /// Writes `v` to the current offset.
665    pub fn put_bytes(&mut self, v: &[u8]) -> Result<()> {
666        let len = v.len();
667
668        if self.cap() < len {
669            return Err(BufferTooShortError);
670        }
671
672        if len == 0 {
673            return Ok(());
674        }
675
676        self.as_mut()[..len].copy_from_slice(v);
677
678        self.off += len;
679
680        Ok(())
681    }
682
683    /// Writes `v` to the current offset after Huffman-encoding it.
684    ///
685    /// The Huffman code implemented is the one defined for HPACK (RFC7541).
686    #[cfg(feature = "huffman_hpack")]
687    pub fn put_huffman_encoded<const LOWER_CASE: bool>(
688        &mut self, v: &[u8],
689    ) -> Result<()> {
690        <Self as OctetsWriter>::put_huffman_encoded::<LOWER_CASE>(self, v)
691    }
692
693    /// Rewinds the buffer offset by `len` elements.
694    pub fn rewind(&mut self, len: usize) -> Result<()> {
695        if self.off() < len {
696            return Err(BufferTooShortError);
697        }
698
699        self.off -= len;
700
701        Ok(())
702    }
703
704    /// Splits the buffer in two at the given absolute offset.
705    pub fn split_at(
706        &mut self, off: usize,
707    ) -> Result<(OctetsMut<'_>, OctetsMut<'_>)> {
708        if self.len() < off {
709            return Err(BufferTooShortError);
710        }
711
712        let (left, right) = self.buf.split_at_mut(off);
713
714        let first = OctetsMut { buf: left, off: 0 };
715
716        let last = OctetsMut { buf: right, off: 0 };
717
718        Ok((first, last))
719    }
720
721    /// Returns a slice of `len` elements from the current offset.
722    pub fn slice(&'a mut self, len: usize) -> Result<&'a mut [u8]> {
723        if len > self.cap() {
724            return Err(BufferTooShortError);
725        }
726
727        Ok(&mut self.buf[self.off..self.off + len])
728    }
729
730    /// Returns a slice of `len` elements from the end of the buffer.
731    pub fn slice_last(&'a mut self, len: usize) -> Result<&'a mut [u8]> {
732        if len > self.cap() {
733            return Err(BufferTooShortError);
734        }
735
736        let end = self.buf.len();
737        Ok(&mut self.buf[end - len..end])
738    }
739
740    /// Advances the buffer's offset.
741    pub fn skip(&mut self, skip: usize) -> Result<()> {
742        if skip > self.cap() {
743            return Err(BufferTooShortError);
744        }
745
746        self.off += skip;
747
748        Ok(())
749    }
750
751    /// Returns the remaining capacity in the buffer.
752    pub fn cap(&self) -> usize {
753        self.buf.len() - self.off
754    }
755
756    /// Returns the total length of the buffer.
757    pub fn len(&self) -> usize {
758        self.buf.len()
759    }
760
761    /// Returns `true` if the buffer is empty.
762    pub fn is_empty(&self) -> bool {
763        self.buf.len() == 0
764    }
765
766    /// Returns the current offset of the buffer.
767    pub fn off(&self) -> usize {
768        self.off
769    }
770
771    /// Returns a reference to the internal buffer.
772    pub fn buf(&self) -> &[u8] {
773        self.buf
774    }
775
776    /// Copies the buffer from the current offset into a new `Vec<u8>`.
777    pub fn to_vec(&self) -> Vec<u8> {
778        self.as_ref().to_vec()
779    }
780}
781
782impl AsRef<[u8]> for OctetsMut<'_> {
783    fn as_ref(&self) -> &[u8] {
784        &self.buf[self.off..]
785    }
786}
787
788impl AsMut<[u8]> for OctetsMut<'_> {
789    fn as_mut(&mut self) -> &mut [u8] {
790        &mut self.buf[self.off..]
791    }
792}
793
794impl OctetsWriter for OctetsMut<'_> {
795    type Error = BufferTooShortError;
796
797    fn put_bytes(&mut self, v: &[u8]) -> Result<()> {
798        OctetsMut::put_bytes(self, v)
799    }
800}
801
802/// Returns how many bytes it would take to encode `v` as a variable-length
803/// integer.
804pub const fn varint_len(v: u64) -> usize {
805    if v <= 63 {
806        1
807    } else if v <= 16383 {
808        2
809    } else if v <= 1_073_741_823 {
810        4
811    } else if v <= MAX_VAR_INT {
812        8
813    } else {
814        unreachable!()
815    }
816}
817
818/// Returns how long the variable-length integer is, given its first byte.
819pub const fn varint_parse_len(first: u8) -> usize {
820    match first >> 6 {
821        0 => 1,
822        1 => 2,
823        2 => 4,
824        3 => 8,
825        _ => unreachable!(),
826    }
827}
828
829/// Returns how long the Huffman encoding of the given buffer will be.
830///
831/// The Huffman code implemented is the one defined for HPACK (RFC7541).
832#[cfg(feature = "huffman_hpack")]
833pub fn huffman_encoding_len<const LOWER_CASE: bool>(src: &[u8]) -> Result<usize> {
834    use self::huffman_table::ENCODE_TABLE;
835
836    let mut bits: usize = 0;
837
838    for &b in src {
839        let b = if LOWER_CASE {
840            b.to_ascii_lowercase()
841        } else {
842            b
843        };
844
845        let (nbits, _) = ENCODE_TABLE[b as usize];
846        bits += nbits;
847    }
848
849    let mut len = bits / 8;
850
851    if bits & 7 != 0 {
852        len += 1;
853    }
854
855    if len > src.len() {
856        return Err(BufferTooShortError);
857    }
858
859    Ok(len)
860}
861
862#[cfg(feature = "huffman_hpack")]
863fn huffman_encode_with<const LOWER_CASE: bool, F, E>(
864    src: &[u8], mut write: F,
865) -> std::result::Result<(), E>
866where
867    F: FnMut(&[u8]) -> std::result::Result<(), E>,
868{
869    use self::huffman_table::ENCODE_TABLE;
870
871    let mut bits: u64 = 0;
872    let mut pending = 0;
873
874    for &b in src {
875        let b = if LOWER_CASE {
876            b.to_ascii_lowercase()
877        } else {
878            b
879        };
880        let (nbits, code) = ENCODE_TABLE[b as usize];
881
882        pending += nbits;
883
884        if pending < 64 {
885            // Have room for the new token.
886            bits |= code << (64 - pending);
887            continue;
888        }
889
890        pending -= 64;
891        // Take only the bits that fit.
892        bits |= code >> pending;
893        write(&bits.to_be_bytes())?;
894
895        bits = if pending == 0 {
896            0
897        } else {
898            code << (64 - pending)
899        };
900    }
901
902    if pending == 0 {
903        return Ok(());
904    }
905
906    bits |= u64::MAX >> pending;
907    // TODO: replace with `next_multiple_of(8)` when stable.
908    pending = (pending + 7) & !7; // Round up to a byte.
909    bits >>= 64 - pending;
910
911    if pending >= 32 {
912        pending -= 32;
913        write(&((bits >> pending) as u32).to_be_bytes())?;
914    }
915
916    while pending > 0 {
917        pending -= 8;
918        write(&[(bits >> pending) as u8])?;
919    }
920
921    Ok(())
922}
923
924/// The functions in this mod test the compile time assertions in the
925/// `put_u` and `peek_u` macros. If you compile this crate with
926/// `--cfg test_invalid_len_compilation_fail`, e.g., by using
927/// `cargo rustc  -- --cfg test_invalid_len_compilation_fail`
928/// You will get two compiler errors
929#[cfg(test_invalid_len_compilation_fail)]
930pub mod fails_to_compile {
931    use super::*;
932    pub fn peek_invalid_fails_to_compile(b: &mut Octets) -> Result<u8> {
933        peek_u!(b, u8, 2)
934    }
935
936    pub fn put_invalid_fails_to_compile<'a>(
937        b: &'a mut OctetsMut, v: u8,
938    ) -> Result<&'a mut [u8]> {
939        put_u!(b, u8, v, 2)
940    }
941}
942
943#[cfg(feature = "huffman_hpack")]
944mod huffman_table;