1 use super::{IntoBuf, Take, Reader, Iter, FromBuf, Chain};
2 use byteorder::ByteOrder;
3 use iovec::IoVec;
4 
5 use std::{cmp, io, ptr};
6 
7 /// Read bytes from a buffer.
8 ///
9 /// A buffer stores bytes in memory such that read operations are infallible.
10 /// The underlying storage may or may not be in contiguous memory. A `Buf` value
11 /// is a cursor into the buffer. Reading from `Buf` advances the cursor
12 /// position. It can be thought of as an efficient `Iterator` for collections of
13 /// bytes.
14 ///
15 /// The simplest `Buf` is a `Cursor` wrapping a `[u8]`.
16 ///
17 /// ```
18 /// use bytes::Buf;
19 /// use std::io::Cursor;
20 ///
21 /// let mut buf = Cursor::new(b"hello world");
22 ///
23 /// assert_eq!(b'h', buf.get_u8());
24 /// assert_eq!(b'e', buf.get_u8());
25 /// assert_eq!(b'l', buf.get_u8());
26 ///
27 /// let mut rest = [0; 8];
28 /// buf.copy_to_slice(&mut rest);
29 ///
30 /// assert_eq!(&rest[..], b"lo world");
31 /// ```
32 pub trait Buf {
33     /// Returns the number of bytes between the current position and the end of
34     /// the buffer.
35     ///
36     /// This value is greater than or equal to the length of the slice returned
37     /// by `bytes`.
38     ///
39     /// # Examples
40     ///
41     /// ```
42     /// use bytes::Buf;
43     /// use std::io::Cursor;
44     ///
45     /// let mut buf = Cursor::new(b"hello world");
46     ///
47     /// assert_eq!(buf.remaining(), 11);
48     ///
49     /// buf.get_u8();
50     ///
51     /// assert_eq!(buf.remaining(), 10);
52     /// ```
53     ///
54     /// # Implementer notes
55     ///
56     /// Implementations of `remaining` should ensure that the return value does
57     /// not change unless a call is made to `advance` or any other function that
58     /// is documented to change the `Buf`'s current position.
remaining(&self) -> usize59     fn remaining(&self) -> usize;
60 
61     /// Returns a slice starting at the current position and of length between 0
62     /// and `Buf::remaining()`.
63     ///
64     /// This is a lower level function. Most operations are done with other
65     /// functions.
66     ///
67     /// # Examples
68     ///
69     /// ```
70     /// use bytes::Buf;
71     /// use std::io::Cursor;
72     ///
73     /// let mut buf = Cursor::new(b"hello world");
74     ///
75     /// assert_eq!(buf.bytes(), b"hello world");
76     ///
77     /// buf.advance(6);
78     ///
79     /// assert_eq!(buf.bytes(), b"world");
80     /// ```
81     ///
82     /// # Implementer notes
83     ///
84     /// This function should never panic. Once the end of the buffer is reached,
85     /// i.e., `Buf::remaining` returns 0, calls to `bytes` should return an
86     /// empty slice.
bytes(&self) -> &[u8]87     fn bytes(&self) -> &[u8];
88 
89     /// Fills `dst` with potentially multiple slices starting at `self`'s
90     /// current position.
91     ///
92     /// If the `Buf` is backed by disjoint slices of bytes, `bytes_vec` enables
93     /// fetching more than one slice at once. `dst` is a slice of `IoVec`
94     /// references, enabling the slice to be directly used with [`writev`]
95     /// without any further conversion. The sum of the lengths of all the
96     /// buffers in `dst` will be less than or equal to `Buf::remaining()`.
97     ///
98     /// The entries in `dst` will be overwritten, but the data **contained** by
99     /// the slices **will not** be modified. If `bytes_vec` does not fill every
100     /// entry in `dst`, then `dst` is guaranteed to contain all remaining slices
101     /// in `self.
102     ///
103     /// This is a lower level function. Most operations are done with other
104     /// functions.
105     ///
106     /// # Implementer notes
107     ///
108     /// This function should never panic. Once the end of the buffer is reached,
109     /// i.e., `Buf::remaining` returns 0, calls to `bytes_vec` must return 0
110     /// without mutating `dst`.
111     ///
112     /// Implementations should also take care to properly handle being called
113     /// with `dst` being a zero length slice.
114     ///
115     /// [`writev`]: http://man7.org/linux/man-pages/man2/readv.2.html
bytes_vec<'a>(&'a self, dst: &mut [&'a IoVec]) -> usize116     fn bytes_vec<'a>(&'a self, dst: &mut [&'a IoVec]) -> usize {
117         if dst.is_empty() {
118             return 0;
119         }
120 
121         if self.has_remaining() {
122             dst[0] = self.bytes().into();
123             1
124         } else {
125             0
126         }
127     }
128 
129     /// Advance the internal cursor of the Buf
130     ///
131     /// The next call to `bytes` will return a slice starting `cnt` bytes
132     /// further into the underlying buffer.
133     ///
134     /// # Examples
135     ///
136     /// ```
137     /// use bytes::Buf;
138     /// use std::io::Cursor;
139     ///
140     /// let mut buf = Cursor::new(b"hello world");
141     ///
142     /// assert_eq!(buf.bytes(), b"hello world");
143     ///
144     /// buf.advance(6);
145     ///
146     /// assert_eq!(buf.bytes(), b"world");
147     /// ```
148     ///
149     /// # Panics
150     ///
151     /// This function **may** panic if `cnt > self.remaining()`.
152     ///
153     /// # Implementer notes
154     ///
155     /// It is recommended for implementations of `advance` to panic if `cnt >
156     /// self.remaining()`. If the implementation does not panic, the call must
157     /// behave as if `cnt == self.remaining()`.
158     ///
159     /// A call with `cnt == 0` should never panic and be a no-op.
advance(&mut self, cnt: usize)160     fn advance(&mut self, cnt: usize);
161 
162     /// Returns true if there are any more bytes to consume
163     ///
164     /// This is equivalent to `self.remaining() != 0`.
165     ///
166     /// # Examples
167     ///
168     /// ```
169     /// use bytes::Buf;
170     /// use std::io::Cursor;
171     ///
172     /// let mut buf = Cursor::new(b"a");
173     ///
174     /// assert!(buf.has_remaining());
175     ///
176     /// buf.get_u8();
177     ///
178     /// assert!(!buf.has_remaining());
179     /// ```
has_remaining(&self) -> bool180     fn has_remaining(&self) -> bool {
181         self.remaining() > 0
182     }
183 
184     /// Copies bytes from `self` into `dst`.
185     ///
186     /// The cursor is advanced by the number of bytes copied. `self` must have
187     /// enough remaining bytes to fill `dst`.
188     ///
189     /// # Examples
190     ///
191     /// ```
192     /// use bytes::Buf;
193     /// use std::io::Cursor;
194     ///
195     /// let mut buf = Cursor::new(b"hello world");
196     /// let mut dst = [0; 5];
197     ///
198     /// buf.copy_to_slice(&mut dst);
199     /// assert_eq!(b"hello", &dst);
200     /// assert_eq!(6, buf.remaining());
201     /// ```
202     ///
203     /// # Panics
204     ///
205     /// This function panics if `self.remaining() < dst.len()`
copy_to_slice(&mut self, dst: &mut [u8])206     fn copy_to_slice(&mut self, dst: &mut [u8]) {
207         let mut off = 0;
208 
209         assert!(self.remaining() >= dst.len());
210 
211         while off < dst.len() {
212             let cnt;
213 
214             unsafe {
215                 let src = self.bytes();
216                 cnt = cmp::min(src.len(), dst.len() - off);
217 
218                 ptr::copy_nonoverlapping(
219                     src.as_ptr(), dst[off..].as_mut_ptr(), cnt);
220 
221                 off += src.len();
222             }
223 
224             self.advance(cnt);
225         }
226     }
227 
228     /// Gets an unsigned 8 bit integer from `self`.
229     ///
230     /// The current position is advanced by 1.
231     ///
232     /// # Examples
233     ///
234     /// ```
235     /// use bytes::Buf;
236     /// use std::io::Cursor;
237     ///
238     /// let mut buf = Cursor::new(b"\x08 hello");
239     /// assert_eq!(8, buf.get_u8());
240     /// ```
241     ///
242     /// # Panics
243     ///
244     /// This function panics if there is no more remaining data in `self`.
get_u8(&mut self) -> u8245     fn get_u8(&mut self) -> u8 {
246         let mut buf = [0; 1];
247         self.copy_to_slice(&mut buf);
248         buf[0]
249     }
250 
251     /// Gets a signed 8 bit integer from `self`.
252     ///
253     /// The current position is advanced by 1.
254     ///
255     /// # Examples
256     ///
257     /// ```
258     /// use bytes::Buf;
259     /// use std::io::Cursor;
260     ///
261     /// let mut buf = Cursor::new(b"\x08 hello");
262     /// assert_eq!(8, buf.get_i8());
263     /// ```
264     ///
265     /// # Panics
266     ///
267     /// This function panics if there is no more remaining data in `self`.
get_i8(&mut self) -> i8268     fn get_i8(&mut self) -> i8 {
269         let mut buf = [0; 1];
270         self.copy_to_slice(&mut buf);
271         buf[0] as i8
272     }
273 
274     /// Gets an unsigned 16 bit integer from `self` in the specified byte order.
275     ///
276     /// The current position is advanced by 2.
277     ///
278     /// # Examples
279     ///
280     /// ```
281     /// use bytes::{Buf, BigEndian};
282     /// use std::io::Cursor;
283     ///
284     /// let mut buf = Cursor::new(b"\x08\x09 hello");
285     /// assert_eq!(0x0809, buf.get_u16::<BigEndian>());
286     /// ```
287     ///
288     /// # Panics
289     ///
290     /// This function panics if there is not enough remaining data in `self`.
get_u16<T: ByteOrder>(&mut self) -> u16291     fn get_u16<T: ByteOrder>(&mut self) -> u16 {
292         let mut buf = [0; 2];
293         self.copy_to_slice(&mut buf);
294         T::read_u16(&buf)
295     }
296 
297     /// Gets a signed 16 bit integer from `self` in the specified byte order.
298     ///
299     /// The current position is advanced by 2.
300     ///
301     /// # Examples
302     ///
303     /// ```
304     /// use bytes::{Buf, BigEndian};
305     /// use std::io::Cursor;
306     ///
307     /// let mut buf = Cursor::new(b"\x08\x09 hello");
308     /// assert_eq!(0x0809, buf.get_i16::<BigEndian>());
309     /// ```
310     ///
311     /// # Panics
312     ///
313     /// This function panics if there is not enough remaining data in `self`.
get_i16<T: ByteOrder>(&mut self) -> i16314     fn get_i16<T: ByteOrder>(&mut self) -> i16 {
315         let mut buf = [0; 2];
316         self.copy_to_slice(&mut buf);
317         T::read_i16(&buf)
318     }
319 
320     /// Gets an unsigned 32 bit integer from `self` in the specified byte order.
321     ///
322     /// The current position is advanced by 4.
323     ///
324     /// # Examples
325     ///
326     /// ```
327     /// use bytes::{Buf, BigEndian};
328     /// use std::io::Cursor;
329     ///
330     /// let mut buf = Cursor::new(b"\x08\x09\xA0\xA1 hello");
331     /// assert_eq!(0x0809A0A1, buf.get_u32::<BigEndian>());
332     /// ```
333     ///
334     /// # Panics
335     ///
336     /// This function panics if there is not enough remaining data in `self`.
get_u32<T: ByteOrder>(&mut self) -> u32337     fn get_u32<T: ByteOrder>(&mut self) -> u32 {
338         let mut buf = [0; 4];
339         self.copy_to_slice(&mut buf);
340         T::read_u32(&buf)
341     }
342 
343     /// Gets a signed 32 bit integer from `self` in the specified byte order.
344     ///
345     /// The current position is advanced by 4.
346     ///
347     /// # Examples
348     ///
349     /// ```
350     /// use bytes::{Buf, BigEndian};
351     /// use std::io::Cursor;
352     ///
353     /// let mut buf = Cursor::new(b"\x08\x09\xA0\xA1 hello");
354     /// assert_eq!(0x0809A0A1, buf.get_i32::<BigEndian>());
355     /// ```
356     ///
357     /// # Panics
358     ///
359     /// This function panics if there is not enough remaining data in `self`.
get_i32<T: ByteOrder>(&mut self) -> i32360     fn get_i32<T: ByteOrder>(&mut self) -> i32 {
361         let mut buf = [0; 4];
362         self.copy_to_slice(&mut buf);
363         T::read_i32(&buf)
364     }
365 
366     /// Gets an unsigned 64 bit integer from `self` in the specified byte order.
367     ///
368     /// The current position is advanced by 8.
369     ///
370     /// # Examples
371     ///
372     /// ```
373     /// use bytes::{Buf, BigEndian};
374     /// use std::io::Cursor;
375     ///
376     /// let mut buf = Cursor::new(b"\x01\x02\x03\x04\x05\x06\x07\x08 hello");
377     /// assert_eq!(0x0102030405060708, buf.get_u64::<BigEndian>());
378     /// ```
379     ///
380     /// # Panics
381     ///
382     /// This function panics if there is not enough remaining data in `self`.
get_u64<T: ByteOrder>(&mut self) -> u64383     fn get_u64<T: ByteOrder>(&mut self) -> u64 {
384         let mut buf = [0; 8];
385         self.copy_to_slice(&mut buf);
386         T::read_u64(&buf)
387     }
388 
389     /// Gets a signed 64 bit integer from `self` in the specified byte order.
390     ///
391     /// The current position is advanced by 8.
392     ///
393     /// # Examples
394     ///
395     /// ```
396     /// use bytes::{Buf, BigEndian};
397     /// use std::io::Cursor;
398     ///
399     /// let mut buf = Cursor::new(b"\x01\x02\x03\x04\x05\x06\x07\x08 hello");
400     /// assert_eq!(0x0102030405060708, buf.get_i64::<BigEndian>());
401     /// ```
402     ///
403     /// # Panics
404     ///
405     /// This function panics if there is not enough remaining data in `self`.
get_i64<T: ByteOrder>(&mut self) -> i64406     fn get_i64<T: ByteOrder>(&mut self) -> i64 {
407         let mut buf = [0; 8];
408         self.copy_to_slice(&mut buf);
409         T::read_i64(&buf)
410     }
411 
412     /// Gets an unsigned n-byte integer from `self` in the specified byte order.
413     ///
414     /// The current position is advanced by `nbytes`.
415     ///
416     /// # Examples
417     ///
418     /// ```
419     /// use bytes::{Buf, BigEndian};
420     /// use std::io::Cursor;
421     ///
422     /// let mut buf = Cursor::new(b"\x01\x02\x03 hello");
423     /// assert_eq!(0x010203, buf.get_uint::<BigEndian>(3));
424     /// ```
425     ///
426     /// # Panics
427     ///
428     /// This function panics if there is not enough remaining data in `self`.
get_uint<T: ByteOrder>(&mut self, nbytes: usize) -> u64429     fn get_uint<T: ByteOrder>(&mut self, nbytes: usize) -> u64 {
430         let mut buf = [0; 8];
431         self.copy_to_slice(&mut buf[..nbytes]);
432         T::read_uint(&buf[..nbytes], nbytes)
433     }
434 
435     /// Gets a signed n-byte integer from `self` in the specified byte order.
436     ///
437     /// The current position is advanced by `nbytes`.
438     ///
439     /// # Examples
440     ///
441     /// ```
442     /// use bytes::{Buf, BigEndian};
443     /// use std::io::Cursor;
444     ///
445     /// let mut buf = Cursor::new(b"\x01\x02\x03 hello");
446     /// assert_eq!(0x010203, buf.get_int::<BigEndian>(3));
447     /// ```
448     ///
449     /// # Panics
450     ///
451     /// This function panics if there is not enough remaining data in `self`.
get_int<T: ByteOrder>(&mut self, nbytes: usize) -> i64452     fn get_int<T: ByteOrder>(&mut self, nbytes: usize) -> i64 {
453         let mut buf = [0; 8];
454         self.copy_to_slice(&mut buf[..nbytes]);
455         T::read_int(&buf[..nbytes], nbytes)
456     }
457 
458     /// Gets an IEEE754 single-precision (4 bytes) floating point number from
459     /// `self` in the specified byte order.
460     ///
461     /// The current position is advanced by 4.
462     ///
463     /// # Examples
464     ///
465     /// ```
466     /// use bytes::{Buf, BigEndian};
467     /// use std::io::Cursor;
468     ///
469     /// let mut buf = Cursor::new(b"\x3F\x99\x99\x9A hello");
470     /// assert_eq!(1.2f32, buf.get_f32::<BigEndian>());
471     /// ```
472     ///
473     /// # Panics
474     ///
475     /// This function panics if there is not enough remaining data in `self`.
get_f32<T: ByteOrder>(&mut self) -> f32476     fn get_f32<T: ByteOrder>(&mut self) -> f32 {
477         let mut buf = [0; 4];
478         self.copy_to_slice(&mut buf);
479         T::read_f32(&buf)
480     }
481 
482     /// Gets an IEEE754 double-precision (8 bytes) floating point number from
483     /// `self` in the specified byte order.
484     ///
485     /// The current position is advanced by 8.
486     ///
487     /// # Examples
488     ///
489     /// ```
490     /// use bytes::{Buf, BigEndian};
491     /// use std::io::Cursor;
492     ///
493     /// let mut buf = Cursor::new(b"\x3F\xF3\x33\x33\x33\x33\x33\x33 hello");
494     /// assert_eq!(1.2f64, buf.get_f64::<BigEndian>());
495     /// ```
496     ///
497     /// # Panics
498     ///
499     /// This function panics if there is not enough remaining data in `self`.
get_f64<T: ByteOrder>(&mut self) -> f64500     fn get_f64<T: ByteOrder>(&mut self) -> f64 {
501         let mut buf = [0; 8];
502         self.copy_to_slice(&mut buf);
503         T::read_f64(&buf)
504     }
505 
506     /// Transforms a `Buf` into a concrete buffer.
507     ///
508     /// `collect()` can operate on any value that implements `Buf`, and turn it
509     /// into the relevent concrete buffer type.
510     ///
511     /// # Examples
512     ///
513     /// Collecting a buffer and loading the contents into a `Vec<u8>`.
514     ///
515     /// ```
516     /// use bytes::{Buf, Bytes, IntoBuf};
517     ///
518     /// let buf = Bytes::from(&b"hello world"[..]).into_buf();
519     /// let vec: Vec<u8> = buf.collect();
520     ///
521     /// assert_eq!(vec, &b"hello world"[..]);
522     /// ```
collect<B>(self) -> B where Self: Sized, B: FromBuf,523     fn collect<B>(self) -> B
524         where Self: Sized,
525               B: FromBuf,
526     {
527         B::from_buf(self)
528     }
529 
530     /// Creates an adaptor which will read at most `limit` bytes from `self`.
531     ///
532     /// This function returns a new instance of `Buf` which will read at most
533     /// `limit` bytes.
534     ///
535     /// # Examples
536     ///
537     /// ```
538     /// use bytes::{Buf, BufMut};
539     /// use std::io::Cursor;
540     ///
541     /// let mut buf = Cursor::new("hello world").take(5);
542     /// let mut dst = vec![];
543     ///
544     /// dst.put(&mut buf);
545     /// assert_eq!(dst, b"hello");
546     ///
547     /// let mut buf = buf.into_inner();
548     /// dst.clear();
549     /// dst.put(&mut buf);
550     /// assert_eq!(dst, b" world");
551     /// ```
take(self, limit: usize) -> Take<Self> where Self: Sized552     fn take(self, limit: usize) -> Take<Self>
553         where Self: Sized
554     {
555         super::take::new(self, limit)
556     }
557 
558     /// Creates an adaptor which will chain this buffer with another.
559     ///
560     /// The returned `Buf` instance will first consume all bytes from `self`.
561     /// Afterwards the output is equivalent to the output of next.
562     ///
563     /// # Examples
564     ///
565     /// ```
566     /// use bytes::{Bytes, Buf, IntoBuf};
567     /// use bytes::buf::Chain;
568     ///
569     /// let buf = Bytes::from(&b"hello "[..]).into_buf()
570     ///             .chain(Bytes::from(&b"world"[..]));
571     ///
572     /// let full: Bytes = buf.collect();
573     /// assert_eq!(full[..], b"hello world"[..]);
574     /// ```
chain<U>(self, next: U) -> Chain<Self, U::Buf> where U: IntoBuf, Self: Sized,575     fn chain<U>(self, next: U) -> Chain<Self, U::Buf>
576         where U: IntoBuf,
577               Self: Sized,
578     {
579         Chain::new(self, next.into_buf())
580     }
581 
582     /// Creates a "by reference" adaptor for this instance of `Buf`.
583     ///
584     /// The returned adaptor also implements `Buf` and will simply borrow `self`.
585     ///
586     /// # Examples
587     ///
588     /// ```
589     /// use bytes::{Buf, BufMut};
590     /// use std::io::Cursor;
591     ///
592     /// let mut buf = Cursor::new("hello world");
593     /// let mut dst = vec![];
594     ///
595     /// {
596     ///     let mut reference = buf.by_ref();
597     ///     dst.put(&mut reference.take(5));
598     ///     assert_eq!(dst, b"hello");
599     /// } // drop our &mut reference so we can use `buf` again
600     ///
601     /// dst.clear();
602     /// dst.put(&mut buf);
603     /// assert_eq!(dst, b" world");
604     /// ```
by_ref(&mut self) -> &mut Self where Self: Sized605     fn by_ref(&mut self) -> &mut Self where Self: Sized {
606         self
607     }
608 
609     /// Creates an adaptor which implements the `Read` trait for `self`.
610     ///
611     /// This function returns a new value which implements `Read` by adapting
612     /// the `Read` trait functions to the `Buf` trait functions. Given that
613     /// `Buf` operations are infallible, none of the `Read` functions will
614     /// return with `Err`.
615     ///
616     /// # Examples
617     ///
618     /// ```
619     /// use bytes::{Buf, IntoBuf, Bytes};
620     /// use std::io::Read;
621     ///
622     /// let buf = Bytes::from("hello world").into_buf();
623     ///
624     /// let mut reader = buf.reader();
625     /// let mut dst = [0; 1024];
626     ///
627     /// let num = reader.read(&mut dst).unwrap();
628     ///
629     /// assert_eq!(11, num);
630     /// assert_eq!(&dst[..11], b"hello world");
631     /// ```
reader(self) -> Reader<Self> where Self: Sized632     fn reader(self) -> Reader<Self> where Self: Sized {
633         super::reader::new(self)
634     }
635 
636     /// Returns an iterator over the bytes contained by the buffer.
637     ///
638     /// # Examples
639     ///
640     /// ```
641     /// use bytes::{Buf, IntoBuf, Bytes};
642     ///
643     /// let buf = Bytes::from(&b"abc"[..]).into_buf();
644     /// let mut iter = buf.iter();
645     ///
646     /// assert_eq!(iter.next(), Some(b'a'));
647     /// assert_eq!(iter.next(), Some(b'b'));
648     /// assert_eq!(iter.next(), Some(b'c'));
649     /// assert_eq!(iter.next(), None);
650     /// ```
iter(self) -> Iter<Self> where Self: Sized651     fn iter(self) -> Iter<Self> where Self: Sized {
652         super::iter::new(self)
653     }
654 }
655 
656 impl<'a, T: Buf + ?Sized> Buf for &'a mut T {
remaining(&self) -> usize657     fn remaining(&self) -> usize {
658         (**self).remaining()
659     }
660 
bytes(&self) -> &[u8]661     fn bytes(&self) -> &[u8] {
662         (**self).bytes()
663     }
664 
bytes_vec<'b>(&'b self, dst: &mut [&'b IoVec]) -> usize665     fn bytes_vec<'b>(&'b self, dst: &mut [&'b IoVec]) -> usize {
666         (**self).bytes_vec(dst)
667     }
668 
advance(&mut self, cnt: usize)669     fn advance(&mut self, cnt: usize) {
670         (**self).advance(cnt)
671     }
672 }
673 
674 impl<T: Buf + ?Sized> Buf for Box<T> {
remaining(&self) -> usize675     fn remaining(&self) -> usize {
676         (**self).remaining()
677     }
678 
bytes(&self) -> &[u8]679     fn bytes(&self) -> &[u8] {
680         (**self).bytes()
681     }
682 
bytes_vec<'b>(&'b self, dst: &mut [&'b IoVec]) -> usize683     fn bytes_vec<'b>(&'b self, dst: &mut [&'b IoVec]) -> usize {
684         (**self).bytes_vec(dst)
685     }
686 
advance(&mut self, cnt: usize)687     fn advance(&mut self, cnt: usize) {
688         (**self).advance(cnt)
689     }
690 }
691 
692 impl<T: AsRef<[u8]>> Buf for io::Cursor<T> {
remaining(&self) -> usize693     fn remaining(&self) -> usize {
694         let len = self.get_ref().as_ref().len();
695         let pos = self.position();
696 
697         if pos >= len as u64 {
698             return 0;
699         }
700 
701         len - pos as usize
702     }
703 
bytes(&self) -> &[u8]704     fn bytes(&self) -> &[u8] {
705         let len = self.get_ref().as_ref().len();
706         let pos = self.position() as usize;
707 
708         if pos >= len {
709             return Default::default();
710         }
711 
712         &(self.get_ref().as_ref())[pos..]
713     }
714 
advance(&mut self, cnt: usize)715     fn advance(&mut self, cnt: usize) {
716         let pos = (self.position() as usize)
717             .checked_add(cnt).expect("overflow");
718 
719         assert!(pos <= self.get_ref().as_ref().len());
720 
721         self.set_position(pos as u64);
722     }
723 }
724 
725 impl Buf for Option<[u8; 1]> {
remaining(&self) -> usize726     fn remaining(&self) -> usize {
727         if self.is_some() {
728             1
729         } else {
730             0
731         }
732     }
733 
bytes(&self) -> &[u8]734     fn bytes(&self) -> &[u8] {
735         self.as_ref().map(AsRef::as_ref)
736             .unwrap_or(Default::default())
737     }
738 
advance(&mut self, cnt: usize)739     fn advance(&mut self, cnt: usize) {
740         if cnt == 0 {
741             return;
742         }
743 
744         if self.is_none() {
745             panic!("overflow");
746         } else {
747             assert_eq!(1, cnt);
748             *self = None;
749         }
750     }
751 }
752