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