• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #[cfg(feature = "std")]
2 use crate::buf::{reader, Reader};
3 use crate::buf::{take, Chain, Take};
4 
5 use core::{cmp, mem, ptr};
6 
7 #[cfg(feature = "std")]
8 use std::io::IoSlice;
9 
10 use alloc::boxed::Box;
11 
12 macro_rules! buf_get_impl {
13     ($this:ident, $typ:tt::$conv:tt) => {{
14         const SIZE: usize = mem::size_of::<$typ>();
15         // try to convert directly from the bytes
16         // this Option<ret> trick is to avoid keeping a borrow on self
17         // when advance() is called (mut borrow) and to call bytes() only once
18         let ret = $this
19             .chunk()
20             .get(..SIZE)
21             .map(|src| unsafe { $typ::$conv(*(src as *const _ as *const [_; SIZE])) });
22 
23         if let Some(ret) = ret {
24             // if the direct conversion was possible, advance and return
25             $this.advance(SIZE);
26             return ret;
27         } else {
28             // if not we copy the bytes in a temp buffer then convert
29             let mut buf = [0; SIZE];
30             $this.copy_to_slice(&mut buf); // (do the advance)
31             return $typ::$conv(buf);
32         }
33     }};
34     (le => $this:ident, $typ:tt, $len_to_read:expr) => {{
35         debug_assert!(mem::size_of::<$typ>() >= $len_to_read);
36 
37         // The same trick as above does not improve the best case speed.
38         // It seems to be linked to the way the method is optimised by the compiler
39         let mut buf = [0; (mem::size_of::<$typ>())];
40         $this.copy_to_slice(&mut buf[..($len_to_read)]);
41         return $typ::from_le_bytes(buf);
42     }};
43     (be => $this:ident, $typ:tt, $len_to_read:expr) => {{
44         debug_assert!(mem::size_of::<$typ>() >= $len_to_read);
45 
46         let mut buf = [0; (mem::size_of::<$typ>())];
47         $this.copy_to_slice(&mut buf[mem::size_of::<$typ>() - ($len_to_read)..]);
48         return $typ::from_be_bytes(buf);
49     }};
50 }
51 
52 /// Read bytes from a buffer.
53 ///
54 /// A buffer stores bytes in memory such that read operations are infallible.
55 /// The underlying storage may or may not be in contiguous memory. A `Buf` value
56 /// is a cursor into the buffer. Reading from `Buf` advances the cursor
57 /// position. It can be thought of as an efficient `Iterator` for collections of
58 /// bytes.
59 ///
60 /// The simplest `Buf` is a `&[u8]`.
61 ///
62 /// ```
63 /// use bytes::Buf;
64 ///
65 /// let mut buf = &b"hello world"[..];
66 ///
67 /// assert_eq!(b'h', buf.get_u8());
68 /// assert_eq!(b'e', buf.get_u8());
69 /// assert_eq!(b'l', buf.get_u8());
70 ///
71 /// let mut rest = [0; 8];
72 /// buf.copy_to_slice(&mut rest);
73 ///
74 /// assert_eq!(&rest[..], &b"lo world"[..]);
75 /// ```
76 pub trait Buf {
77     /// Returns the number of bytes between the current position and the end of
78     /// the buffer.
79     ///
80     /// This value is greater than or equal to the length of the slice returned
81     /// by `chunk()`.
82     ///
83     /// # Examples
84     ///
85     /// ```
86     /// use bytes::Buf;
87     ///
88     /// let mut buf = &b"hello world"[..];
89     ///
90     /// assert_eq!(buf.remaining(), 11);
91     ///
92     /// buf.get_u8();
93     ///
94     /// assert_eq!(buf.remaining(), 10);
95     /// ```
96     ///
97     /// # Implementer notes
98     ///
99     /// Implementations of `remaining` should ensure that the return value does
100     /// not change unless a call is made to `advance` or any other function that
101     /// is documented to change the `Buf`'s current position.
remaining(&self) -> usize102     fn remaining(&self) -> usize;
103 
104     /// Returns a slice starting at the current position and of length between 0
105     /// and `Buf::remaining()`. Note that this *can* return shorter slice (this allows
106     /// non-continuous internal representation).
107     ///
108     /// This is a lower level function. Most operations are done with other
109     /// functions.
110     ///
111     /// # Examples
112     ///
113     /// ```
114     /// use bytes::Buf;
115     ///
116     /// let mut buf = &b"hello world"[..];
117     ///
118     /// assert_eq!(buf.chunk(), &b"hello world"[..]);
119     ///
120     /// buf.advance(6);
121     ///
122     /// assert_eq!(buf.chunk(), &b"world"[..]);
123     /// ```
124     ///
125     /// # Implementer notes
126     ///
127     /// This function should never panic. Once the end of the buffer is reached,
128     /// i.e., `Buf::remaining` returns 0, calls to `chunk()` should return an
129     /// empty slice.
130     // The `chunk` method was previously called `bytes`. This alias makes the rename
131     // more easily discoverable.
132     #[cfg_attr(docsrs, doc(alias = "bytes"))]
chunk(&self) -> &[u8]133     fn chunk(&self) -> &[u8];
134 
135     /// Fills `dst` with potentially multiple slices starting at `self`'s
136     /// current position.
137     ///
138     /// If the `Buf` is backed by disjoint slices of bytes, `chunk_vectored` enables
139     /// fetching more than one slice at once. `dst` is a slice of `IoSlice`
140     /// references, enabling the slice to be directly used with [`writev`]
141     /// without any further conversion. The sum of the lengths of all the
142     /// buffers in `dst` will be less than or equal to `Buf::remaining()`.
143     ///
144     /// The entries in `dst` will be overwritten, but the data **contained** by
145     /// the slices **will not** be modified. If `chunk_vectored` does not fill every
146     /// entry in `dst`, then `dst` is guaranteed to contain all remaining slices
147     /// in `self.
148     ///
149     /// This is a lower level function. Most operations are done with other
150     /// functions.
151     ///
152     /// # Implementer notes
153     ///
154     /// This function should never panic. Once the end of the buffer is reached,
155     /// i.e., `Buf::remaining` returns 0, calls to `chunk_vectored` must return 0
156     /// without mutating `dst`.
157     ///
158     /// Implementations should also take care to properly handle being called
159     /// with `dst` being a zero length slice.
160     ///
161     /// [`writev`]: http://man7.org/linux/man-pages/man2/readv.2.html
162     #[cfg(feature = "std")]
chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize163     fn chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize {
164         if dst.is_empty() {
165             return 0;
166         }
167 
168         if self.has_remaining() {
169             dst[0] = IoSlice::new(self.chunk());
170             1
171         } else {
172             0
173         }
174     }
175 
176     /// Advance the internal cursor of the Buf
177     ///
178     /// The next call to `chunk()` will return a slice starting `cnt` bytes
179     /// further into the underlying buffer.
180     ///
181     /// # Examples
182     ///
183     /// ```
184     /// use bytes::Buf;
185     ///
186     /// let mut buf = &b"hello world"[..];
187     ///
188     /// assert_eq!(buf.chunk(), &b"hello world"[..]);
189     ///
190     /// buf.advance(6);
191     ///
192     /// assert_eq!(buf.chunk(), &b"world"[..]);
193     /// ```
194     ///
195     /// # Panics
196     ///
197     /// This function **may** panic if `cnt > self.remaining()`.
198     ///
199     /// # Implementer notes
200     ///
201     /// It is recommended for implementations of `advance` to panic if `cnt >
202     /// self.remaining()`. If the implementation does not panic, the call must
203     /// behave as if `cnt == self.remaining()`.
204     ///
205     /// A call with `cnt == 0` should never panic and be a no-op.
advance(&mut self, cnt: usize)206     fn advance(&mut self, cnt: usize);
207 
208     /// Returns true if there are any more bytes to consume
209     ///
210     /// This is equivalent to `self.remaining() != 0`.
211     ///
212     /// # Examples
213     ///
214     /// ```
215     /// use bytes::Buf;
216     ///
217     /// let mut buf = &b"a"[..];
218     ///
219     /// assert!(buf.has_remaining());
220     ///
221     /// buf.get_u8();
222     ///
223     /// assert!(!buf.has_remaining());
224     /// ```
has_remaining(&self) -> bool225     fn has_remaining(&self) -> bool {
226         self.remaining() > 0
227     }
228 
229     /// Copies bytes from `self` into `dst`.
230     ///
231     /// The cursor is advanced by the number of bytes copied. `self` must have
232     /// enough remaining bytes to fill `dst`.
233     ///
234     /// # Examples
235     ///
236     /// ```
237     /// use bytes::Buf;
238     ///
239     /// let mut buf = &b"hello world"[..];
240     /// let mut dst = [0; 5];
241     ///
242     /// buf.copy_to_slice(&mut dst);
243     /// assert_eq!(&b"hello"[..], &dst);
244     /// assert_eq!(6, buf.remaining());
245     /// ```
246     ///
247     /// # Panics
248     ///
249     /// This function panics if `self.remaining() < dst.len()`
copy_to_slice(&mut self, dst: &mut [u8])250     fn copy_to_slice(&mut self, dst: &mut [u8]) {
251         let mut off = 0;
252 
253         assert!(self.remaining() >= dst.len());
254 
255         while off < dst.len() {
256             let cnt;
257 
258             unsafe {
259                 let src = self.chunk();
260                 cnt = cmp::min(src.len(), dst.len() - off);
261 
262                 ptr::copy_nonoverlapping(src.as_ptr(), dst[off..].as_mut_ptr(), cnt);
263 
264                 off += cnt;
265             }
266 
267             self.advance(cnt);
268         }
269     }
270 
271     /// Gets an unsigned 8 bit integer from `self`.
272     ///
273     /// The current position is advanced by 1.
274     ///
275     /// # Examples
276     ///
277     /// ```
278     /// use bytes::Buf;
279     ///
280     /// let mut buf = &b"\x08 hello"[..];
281     /// assert_eq!(8, buf.get_u8());
282     /// ```
283     ///
284     /// # Panics
285     ///
286     /// This function panics if there is no more remaining data in `self`.
get_u8(&mut self) -> u8287     fn get_u8(&mut self) -> u8 {
288         assert!(self.remaining() >= 1);
289         let ret = self.chunk()[0];
290         self.advance(1);
291         ret
292     }
293 
294     /// Gets a signed 8 bit integer from `self`.
295     ///
296     /// The current position is advanced by 1.
297     ///
298     /// # Examples
299     ///
300     /// ```
301     /// use bytes::Buf;
302     ///
303     /// let mut buf = &b"\x08 hello"[..];
304     /// assert_eq!(8, buf.get_i8());
305     /// ```
306     ///
307     /// # Panics
308     ///
309     /// This function panics if there is no more remaining data in `self`.
get_i8(&mut self) -> i8310     fn get_i8(&mut self) -> i8 {
311         assert!(self.remaining() >= 1);
312         let ret = self.chunk()[0] as i8;
313         self.advance(1);
314         ret
315     }
316 
317     /// Gets an unsigned 16 bit integer from `self` in big-endian byte order.
318     ///
319     /// The current position is advanced by 2.
320     ///
321     /// # Examples
322     ///
323     /// ```
324     /// use bytes::Buf;
325     ///
326     /// let mut buf = &b"\x08\x09 hello"[..];
327     /// assert_eq!(0x0809, buf.get_u16());
328     /// ```
329     ///
330     /// # Panics
331     ///
332     /// This function panics if there is not enough remaining data in `self`.
get_u16(&mut self) -> u16333     fn get_u16(&mut self) -> u16 {
334         buf_get_impl!(self, u16::from_be_bytes);
335     }
336 
337     /// Gets an unsigned 16 bit integer from `self` in little-endian byte order.
338     ///
339     /// The current position is advanced by 2.
340     ///
341     /// # Examples
342     ///
343     /// ```
344     /// use bytes::Buf;
345     ///
346     /// let mut buf = &b"\x09\x08 hello"[..];
347     /// assert_eq!(0x0809, buf.get_u16_le());
348     /// ```
349     ///
350     /// # Panics
351     ///
352     /// This function panics if there is not enough remaining data in `self`.
get_u16_le(&mut self) -> u16353     fn get_u16_le(&mut self) -> u16 {
354         buf_get_impl!(self, u16::from_le_bytes);
355     }
356 
357     /// Gets a signed 16 bit integer from `self` in big-endian byte order.
358     ///
359     /// The current position is advanced by 2.
360     ///
361     /// # Examples
362     ///
363     /// ```
364     /// use bytes::Buf;
365     ///
366     /// let mut buf = &b"\x08\x09 hello"[..];
367     /// assert_eq!(0x0809, buf.get_i16());
368     /// ```
369     ///
370     /// # Panics
371     ///
372     /// This function panics if there is not enough remaining data in `self`.
get_i16(&mut self) -> i16373     fn get_i16(&mut self) -> i16 {
374         buf_get_impl!(self, i16::from_be_bytes);
375     }
376 
377     /// Gets a signed 16 bit integer from `self` in little-endian byte order.
378     ///
379     /// The current position is advanced by 2.
380     ///
381     /// # Examples
382     ///
383     /// ```
384     /// use bytes::Buf;
385     ///
386     /// let mut buf = &b"\x09\x08 hello"[..];
387     /// assert_eq!(0x0809, buf.get_i16_le());
388     /// ```
389     ///
390     /// # Panics
391     ///
392     /// This function panics if there is not enough remaining data in `self`.
get_i16_le(&mut self) -> i16393     fn get_i16_le(&mut self) -> i16 {
394         buf_get_impl!(self, i16::from_le_bytes);
395     }
396 
397     /// Gets an unsigned 32 bit integer from `self` in the big-endian byte order.
398     ///
399     /// The current position is advanced by 4.
400     ///
401     /// # Examples
402     ///
403     /// ```
404     /// use bytes::Buf;
405     ///
406     /// let mut buf = &b"\x08\x09\xA0\xA1 hello"[..];
407     /// assert_eq!(0x0809A0A1, buf.get_u32());
408     /// ```
409     ///
410     /// # Panics
411     ///
412     /// This function panics if there is not enough remaining data in `self`.
get_u32(&mut self) -> u32413     fn get_u32(&mut self) -> u32 {
414         buf_get_impl!(self, u32::from_be_bytes);
415     }
416 
417     /// Gets an unsigned 32 bit integer from `self` in the little-endian byte order.
418     ///
419     /// The current position is advanced by 4.
420     ///
421     /// # Examples
422     ///
423     /// ```
424     /// use bytes::Buf;
425     ///
426     /// let mut buf = &b"\xA1\xA0\x09\x08 hello"[..];
427     /// assert_eq!(0x0809A0A1, buf.get_u32_le());
428     /// ```
429     ///
430     /// # Panics
431     ///
432     /// This function panics if there is not enough remaining data in `self`.
get_u32_le(&mut self) -> u32433     fn get_u32_le(&mut self) -> u32 {
434         buf_get_impl!(self, u32::from_le_bytes);
435     }
436 
437     /// Gets a signed 32 bit integer from `self` in big-endian byte order.
438     ///
439     /// The current position is advanced by 4.
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// use bytes::Buf;
445     ///
446     /// let mut buf = &b"\x08\x09\xA0\xA1 hello"[..];
447     /// assert_eq!(0x0809A0A1, buf.get_i32());
448     /// ```
449     ///
450     /// # Panics
451     ///
452     /// This function panics if there is not enough remaining data in `self`.
get_i32(&mut self) -> i32453     fn get_i32(&mut self) -> i32 {
454         buf_get_impl!(self, i32::from_be_bytes);
455     }
456 
457     /// Gets a signed 32 bit integer from `self` in little-endian byte order.
458     ///
459     /// The current position is advanced by 4.
460     ///
461     /// # Examples
462     ///
463     /// ```
464     /// use bytes::Buf;
465     ///
466     /// let mut buf = &b"\xA1\xA0\x09\x08 hello"[..];
467     /// assert_eq!(0x0809A0A1, buf.get_i32_le());
468     /// ```
469     ///
470     /// # Panics
471     ///
472     /// This function panics if there is not enough remaining data in `self`.
get_i32_le(&mut self) -> i32473     fn get_i32_le(&mut self) -> i32 {
474         buf_get_impl!(self, i32::from_le_bytes);
475     }
476 
477     /// Gets an unsigned 64 bit integer from `self` in big-endian byte order.
478     ///
479     /// The current position is advanced by 8.
480     ///
481     /// # Examples
482     ///
483     /// ```
484     /// use bytes::Buf;
485     ///
486     /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08 hello"[..];
487     /// assert_eq!(0x0102030405060708, buf.get_u64());
488     /// ```
489     ///
490     /// # Panics
491     ///
492     /// This function panics if there is not enough remaining data in `self`.
get_u64(&mut self) -> u64493     fn get_u64(&mut self) -> u64 {
494         buf_get_impl!(self, u64::from_be_bytes);
495     }
496 
497     /// Gets an unsigned 64 bit integer from `self` in little-endian byte order.
498     ///
499     /// The current position is advanced by 8.
500     ///
501     /// # Examples
502     ///
503     /// ```
504     /// use bytes::Buf;
505     ///
506     /// let mut buf = &b"\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
507     /// assert_eq!(0x0102030405060708, buf.get_u64_le());
508     /// ```
509     ///
510     /// # Panics
511     ///
512     /// This function panics if there is not enough remaining data in `self`.
get_u64_le(&mut self) -> u64513     fn get_u64_le(&mut self) -> u64 {
514         buf_get_impl!(self, u64::from_le_bytes);
515     }
516 
517     /// Gets a signed 64 bit integer from `self` in big-endian byte order.
518     ///
519     /// The current position is advanced by 8.
520     ///
521     /// # Examples
522     ///
523     /// ```
524     /// use bytes::Buf;
525     ///
526     /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08 hello"[..];
527     /// assert_eq!(0x0102030405060708, buf.get_i64());
528     /// ```
529     ///
530     /// # Panics
531     ///
532     /// This function panics if there is not enough remaining data in `self`.
get_i64(&mut self) -> i64533     fn get_i64(&mut self) -> i64 {
534         buf_get_impl!(self, i64::from_be_bytes);
535     }
536 
537     /// Gets a signed 64 bit integer from `self` in little-endian byte order.
538     ///
539     /// The current position is advanced by 8.
540     ///
541     /// # Examples
542     ///
543     /// ```
544     /// use bytes::Buf;
545     ///
546     /// let mut buf = &b"\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
547     /// assert_eq!(0x0102030405060708, buf.get_i64_le());
548     /// ```
549     ///
550     /// # Panics
551     ///
552     /// This function panics if there is not enough remaining data in `self`.
get_i64_le(&mut self) -> i64553     fn get_i64_le(&mut self) -> i64 {
554         buf_get_impl!(self, i64::from_le_bytes);
555     }
556 
557     /// Gets an unsigned 128 bit integer from `self` in big-endian byte order.
558     ///
559     /// The current position is advanced by 16.
560     ///
561     /// # Examples
562     ///
563     /// ```
564     /// use bytes::Buf;
565     ///
566     /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello"[..];
567     /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128());
568     /// ```
569     ///
570     /// # Panics
571     ///
572     /// This function panics if there is not enough remaining data in `self`.
get_u128(&mut self) -> u128573     fn get_u128(&mut self) -> u128 {
574         buf_get_impl!(self, u128::from_be_bytes);
575     }
576 
577     /// Gets an unsigned 128 bit integer from `self` in little-endian byte order.
578     ///
579     /// The current position is advanced by 16.
580     ///
581     /// # Examples
582     ///
583     /// ```
584     /// use bytes::Buf;
585     ///
586     /// let mut buf = &b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
587     /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128_le());
588     /// ```
589     ///
590     /// # Panics
591     ///
592     /// This function panics if there is not enough remaining data in `self`.
get_u128_le(&mut self) -> u128593     fn get_u128_le(&mut self) -> u128 {
594         buf_get_impl!(self, u128::from_le_bytes);
595     }
596 
597     /// Gets a signed 128 bit integer from `self` in big-endian byte order.
598     ///
599     /// The current position is advanced by 16.
600     ///
601     /// # Examples
602     ///
603     /// ```
604     /// use bytes::Buf;
605     ///
606     /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello"[..];
607     /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128());
608     /// ```
609     ///
610     /// # Panics
611     ///
612     /// This function panics if there is not enough remaining data in `self`.
get_i128(&mut self) -> i128613     fn get_i128(&mut self) -> i128 {
614         buf_get_impl!(self, i128::from_be_bytes);
615     }
616 
617     /// Gets a signed 128 bit integer from `self` in little-endian byte order.
618     ///
619     /// The current position is advanced by 16.
620     ///
621     /// # Examples
622     ///
623     /// ```
624     /// use bytes::Buf;
625     ///
626     /// let mut buf = &b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
627     /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128_le());
628     /// ```
629     ///
630     /// # Panics
631     ///
632     /// This function panics if there is not enough remaining data in `self`.
get_i128_le(&mut self) -> i128633     fn get_i128_le(&mut self) -> i128 {
634         buf_get_impl!(self, i128::from_le_bytes);
635     }
636 
637     /// Gets an unsigned n-byte integer from `self` in big-endian byte order.
638     ///
639     /// The current position is advanced by `nbytes`.
640     ///
641     /// # Examples
642     ///
643     /// ```
644     /// use bytes::Buf;
645     ///
646     /// let mut buf = &b"\x01\x02\x03 hello"[..];
647     /// assert_eq!(0x010203, buf.get_uint(3));
648     /// ```
649     ///
650     /// # Panics
651     ///
652     /// This function panics if there is not enough remaining data in `self`.
get_uint(&mut self, nbytes: usize) -> u64653     fn get_uint(&mut self, nbytes: usize) -> u64 {
654         buf_get_impl!(be => self, u64, nbytes);
655     }
656 
657     /// Gets an unsigned n-byte integer from `self` in little-endian byte order.
658     ///
659     /// The current position is advanced by `nbytes`.
660     ///
661     /// # Examples
662     ///
663     /// ```
664     /// use bytes::Buf;
665     ///
666     /// let mut buf = &b"\x03\x02\x01 hello"[..];
667     /// assert_eq!(0x010203, buf.get_uint_le(3));
668     /// ```
669     ///
670     /// # Panics
671     ///
672     /// This function panics if there is not enough remaining data in `self`.
get_uint_le(&mut self, nbytes: usize) -> u64673     fn get_uint_le(&mut self, nbytes: usize) -> u64 {
674         buf_get_impl!(le => self, u64, nbytes);
675     }
676 
677     /// Gets a signed n-byte integer from `self` in big-endian byte order.
678     ///
679     /// The current position is advanced by `nbytes`.
680     ///
681     /// # Examples
682     ///
683     /// ```
684     /// use bytes::Buf;
685     ///
686     /// let mut buf = &b"\x01\x02\x03 hello"[..];
687     /// assert_eq!(0x010203, buf.get_int(3));
688     /// ```
689     ///
690     /// # Panics
691     ///
692     /// This function panics if there is not enough remaining data in `self`.
get_int(&mut self, nbytes: usize) -> i64693     fn get_int(&mut self, nbytes: usize) -> i64 {
694         buf_get_impl!(be => self, i64, nbytes);
695     }
696 
697     /// Gets a signed n-byte integer from `self` in little-endian byte order.
698     ///
699     /// The current position is advanced by `nbytes`.
700     ///
701     /// # Examples
702     ///
703     /// ```
704     /// use bytes::Buf;
705     ///
706     /// let mut buf = &b"\x03\x02\x01 hello"[..];
707     /// assert_eq!(0x010203, buf.get_int_le(3));
708     /// ```
709     ///
710     /// # Panics
711     ///
712     /// This function panics if there is not enough remaining data in `self`.
get_int_le(&mut self, nbytes: usize) -> i64713     fn get_int_le(&mut self, nbytes: usize) -> i64 {
714         buf_get_impl!(le => self, i64, nbytes);
715     }
716 
717     /// Gets an IEEE754 single-precision (4 bytes) floating point number from
718     /// `self` in big-endian byte order.
719     ///
720     /// The current position is advanced by 4.
721     ///
722     /// # Examples
723     ///
724     /// ```
725     /// use bytes::Buf;
726     ///
727     /// let mut buf = &b"\x3F\x99\x99\x9A hello"[..];
728     /// assert_eq!(1.2f32, buf.get_f32());
729     /// ```
730     ///
731     /// # Panics
732     ///
733     /// This function panics if there is not enough remaining data in `self`.
get_f32(&mut self) -> f32734     fn get_f32(&mut self) -> f32 {
735         f32::from_bits(Self::get_u32(self))
736     }
737 
738     /// Gets an IEEE754 single-precision (4 bytes) floating point number from
739     /// `self` in little-endian byte order.
740     ///
741     /// The current position is advanced by 4.
742     ///
743     /// # Examples
744     ///
745     /// ```
746     /// use bytes::Buf;
747     ///
748     /// let mut buf = &b"\x9A\x99\x99\x3F hello"[..];
749     /// assert_eq!(1.2f32, buf.get_f32_le());
750     /// ```
751     ///
752     /// # Panics
753     ///
754     /// This function panics if there is not enough remaining data in `self`.
get_f32_le(&mut self) -> f32755     fn get_f32_le(&mut self) -> f32 {
756         f32::from_bits(Self::get_u32_le(self))
757     }
758 
759     /// Gets an IEEE754 double-precision (8 bytes) floating point number from
760     /// `self` in big-endian byte order.
761     ///
762     /// The current position is advanced by 8.
763     ///
764     /// # Examples
765     ///
766     /// ```
767     /// use bytes::Buf;
768     ///
769     /// let mut buf = &b"\x3F\xF3\x33\x33\x33\x33\x33\x33 hello"[..];
770     /// assert_eq!(1.2f64, buf.get_f64());
771     /// ```
772     ///
773     /// # Panics
774     ///
775     /// This function panics if there is not enough remaining data in `self`.
get_f64(&mut self) -> f64776     fn get_f64(&mut self) -> f64 {
777         f64::from_bits(Self::get_u64(self))
778     }
779 
780     /// Gets an IEEE754 double-precision (8 bytes) floating point number from
781     /// `self` in little-endian byte order.
782     ///
783     /// The current position is advanced by 8.
784     ///
785     /// # Examples
786     ///
787     /// ```
788     /// use bytes::Buf;
789     ///
790     /// let mut buf = &b"\x33\x33\x33\x33\x33\x33\xF3\x3F hello"[..];
791     /// assert_eq!(1.2f64, buf.get_f64_le());
792     /// ```
793     ///
794     /// # Panics
795     ///
796     /// This function panics if there is not enough remaining data in `self`.
get_f64_le(&mut self) -> f64797     fn get_f64_le(&mut self) -> f64 {
798         f64::from_bits(Self::get_u64_le(self))
799     }
800 
801     /// Consumes `len` bytes inside self and returns new instance of `Bytes`
802     /// with this data.
803     ///
804     /// This function may be optimized by the underlying type to avoid actual
805     /// copies. For example, `Bytes` implementation will do a shallow copy
806     /// (ref-count increment).
807     ///
808     /// # Examples
809     ///
810     /// ```
811     /// use bytes::Buf;
812     ///
813     /// let bytes = (&b"hello world"[..]).copy_to_bytes(5);
814     /// assert_eq!(&bytes[..], &b"hello"[..]);
815     /// ```
copy_to_bytes(&mut self, len: usize) -> crate::Bytes816     fn copy_to_bytes(&mut self, len: usize) -> crate::Bytes {
817         use super::BufMut;
818 
819         assert!(len <= self.remaining(), "`len` greater than remaining");
820 
821         let mut ret = crate::BytesMut::with_capacity(len);
822         ret.put(self.take(len));
823         ret.freeze()
824     }
825 
826     /// Creates an adaptor which will read at most `limit` bytes from `self`.
827     ///
828     /// This function returns a new instance of `Buf` which will read at most
829     /// `limit` bytes.
830     ///
831     /// # Examples
832     ///
833     /// ```
834     /// use bytes::{Buf, BufMut};
835     ///
836     /// let mut buf = b"hello world"[..].take(5);
837     /// let mut dst = vec![];
838     ///
839     /// dst.put(&mut buf);
840     /// assert_eq!(dst, b"hello");
841     ///
842     /// let mut buf = buf.into_inner();
843     /// dst.clear();
844     /// dst.put(&mut buf);
845     /// assert_eq!(dst, b" world");
846     /// ```
take(self, limit: usize) -> Take<Self> where Self: Sized,847     fn take(self, limit: usize) -> Take<Self>
848     where
849         Self: Sized,
850     {
851         take::new(self, limit)
852     }
853 
854     /// Creates an adaptor which will chain this buffer with another.
855     ///
856     /// The returned `Buf` instance will first consume all bytes from `self`.
857     /// Afterwards the output is equivalent to the output of next.
858     ///
859     /// # Examples
860     ///
861     /// ```
862     /// use bytes::Buf;
863     ///
864     /// let mut chain = b"hello "[..].chain(&b"world"[..]);
865     ///
866     /// let full = chain.copy_to_bytes(11);
867     /// assert_eq!(full.chunk(), b"hello world");
868     /// ```
chain<U: Buf>(self, next: U) -> Chain<Self, U> where Self: Sized,869     fn chain<U: Buf>(self, next: U) -> Chain<Self, U>
870     where
871         Self: Sized,
872     {
873         Chain::new(self, next)
874     }
875 
876     /// Creates an adaptor which implements the `Read` trait for `self`.
877     ///
878     /// This function returns a new value which implements `Read` by adapting
879     /// the `Read` trait functions to the `Buf` trait functions. Given that
880     /// `Buf` operations are infallible, none of the `Read` functions will
881     /// return with `Err`.
882     ///
883     /// # Examples
884     ///
885     /// ```
886     /// use bytes::{Bytes, Buf};
887     /// use std::io::Read;
888     ///
889     /// let buf = Bytes::from("hello world");
890     ///
891     /// let mut reader = buf.reader();
892     /// let mut dst = [0; 1024];
893     ///
894     /// let num = reader.read(&mut dst).unwrap();
895     ///
896     /// assert_eq!(11, num);
897     /// assert_eq!(&dst[..11], &b"hello world"[..]);
898     /// ```
899     #[cfg(feature = "std")]
reader(self) -> Reader<Self> where Self: Sized,900     fn reader(self) -> Reader<Self>
901     where
902         Self: Sized,
903     {
904         reader::new(self)
905     }
906 }
907 
908 macro_rules! deref_forward_buf {
909     () => {
910         fn remaining(&self) -> usize {
911             (**self).remaining()
912         }
913 
914         fn chunk(&self) -> &[u8] {
915             (**self).chunk()
916         }
917 
918         #[cfg(feature = "std")]
919         fn chunks_vectored<'b>(&'b self, dst: &mut [IoSlice<'b>]) -> usize {
920             (**self).chunks_vectored(dst)
921         }
922 
923         fn advance(&mut self, cnt: usize) {
924             (**self).advance(cnt)
925         }
926 
927         fn has_remaining(&self) -> bool {
928             (**self).has_remaining()
929         }
930 
931         fn copy_to_slice(&mut self, dst: &mut [u8]) {
932             (**self).copy_to_slice(dst)
933         }
934 
935         fn get_u8(&mut self) -> u8 {
936             (**self).get_u8()
937         }
938 
939         fn get_i8(&mut self) -> i8 {
940             (**self).get_i8()
941         }
942 
943         fn get_u16(&mut self) -> u16 {
944             (**self).get_u16()
945         }
946 
947         fn get_u16_le(&mut self) -> u16 {
948             (**self).get_u16_le()
949         }
950 
951         fn get_i16(&mut self) -> i16 {
952             (**self).get_i16()
953         }
954 
955         fn get_i16_le(&mut self) -> i16 {
956             (**self).get_i16_le()
957         }
958 
959         fn get_u32(&mut self) -> u32 {
960             (**self).get_u32()
961         }
962 
963         fn get_u32_le(&mut self) -> u32 {
964             (**self).get_u32_le()
965         }
966 
967         fn get_i32(&mut self) -> i32 {
968             (**self).get_i32()
969         }
970 
971         fn get_i32_le(&mut self) -> i32 {
972             (**self).get_i32_le()
973         }
974 
975         fn get_u64(&mut self) -> u64 {
976             (**self).get_u64()
977         }
978 
979         fn get_u64_le(&mut self) -> u64 {
980             (**self).get_u64_le()
981         }
982 
983         fn get_i64(&mut self) -> i64 {
984             (**self).get_i64()
985         }
986 
987         fn get_i64_le(&mut self) -> i64 {
988             (**self).get_i64_le()
989         }
990 
991         fn get_uint(&mut self, nbytes: usize) -> u64 {
992             (**self).get_uint(nbytes)
993         }
994 
995         fn get_uint_le(&mut self, nbytes: usize) -> u64 {
996             (**self).get_uint_le(nbytes)
997         }
998 
999         fn get_int(&mut self, nbytes: usize) -> i64 {
1000             (**self).get_int(nbytes)
1001         }
1002 
1003         fn get_int_le(&mut self, nbytes: usize) -> i64 {
1004             (**self).get_int_le(nbytes)
1005         }
1006 
1007         fn copy_to_bytes(&mut self, len: usize) -> crate::Bytes {
1008             (**self).copy_to_bytes(len)
1009         }
1010     };
1011 }
1012 
1013 impl<T: Buf + ?Sized> Buf for &mut T {
1014     deref_forward_buf!();
1015 }
1016 
1017 impl<T: Buf + ?Sized> Buf for Box<T> {
1018     deref_forward_buf!();
1019 }
1020 
1021 impl Buf for &[u8] {
1022     #[inline]
remaining(&self) -> usize1023     fn remaining(&self) -> usize {
1024         self.len()
1025     }
1026 
1027     #[inline]
chunk(&self) -> &[u8]1028     fn chunk(&self) -> &[u8] {
1029         self
1030     }
1031 
1032     #[inline]
advance(&mut self, cnt: usize)1033     fn advance(&mut self, cnt: usize) {
1034         *self = &self[cnt..];
1035     }
1036 }
1037 
1038 #[cfg(feature = "std")]
1039 impl<T: AsRef<[u8]>> Buf for std::io::Cursor<T> {
remaining(&self) -> usize1040     fn remaining(&self) -> usize {
1041         let len = self.get_ref().as_ref().len();
1042         let pos = self.position();
1043 
1044         if pos >= len as u64 {
1045             return 0;
1046         }
1047 
1048         len - pos as usize
1049     }
1050 
chunk(&self) -> &[u8]1051     fn chunk(&self) -> &[u8] {
1052         let len = self.get_ref().as_ref().len();
1053         let pos = self.position();
1054 
1055         if pos >= len as u64 {
1056             return &[];
1057         }
1058 
1059         &self.get_ref().as_ref()[pos as usize..]
1060     }
1061 
advance(&mut self, cnt: usize)1062     fn advance(&mut self, cnt: usize) {
1063         let pos = (self.position() as usize)
1064             .checked_add(cnt)
1065             .expect("overflow");
1066 
1067         assert!(pos <= self.get_ref().as_ref().len());
1068         self.set_position(pos as u64);
1069     }
1070 }
1071 
1072 // The existence of this function makes the compiler catch if the Buf
1073 // trait is "object-safe" or not.
_assert_trait_object(_b: &dyn Buf)1074 fn _assert_trait_object(_b: &dyn Buf) {}
1075