• 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")]
163     #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize164     fn chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize {
165         if dst.is_empty() {
166             return 0;
167         }
168 
169         if self.has_remaining() {
170             dst[0] = IoSlice::new(self.chunk());
171             1
172         } else {
173             0
174         }
175     }
176 
177     /// Advance the internal cursor of the Buf
178     ///
179     /// The next call to `chunk()` will return a slice starting `cnt` bytes
180     /// further into the underlying buffer.
181     ///
182     /// # Examples
183     ///
184     /// ```
185     /// use bytes::Buf;
186     ///
187     /// let mut buf = &b"hello world"[..];
188     ///
189     /// assert_eq!(buf.chunk(), &b"hello world"[..]);
190     ///
191     /// buf.advance(6);
192     ///
193     /// assert_eq!(buf.chunk(), &b"world"[..]);
194     /// ```
195     ///
196     /// # Panics
197     ///
198     /// This function **may** panic if `cnt > self.remaining()`.
199     ///
200     /// # Implementer notes
201     ///
202     /// It is recommended for implementations of `advance` to panic if `cnt >
203     /// self.remaining()`. If the implementation does not panic, the call must
204     /// behave as if `cnt == self.remaining()`.
205     ///
206     /// A call with `cnt == 0` should never panic and be a no-op.
advance(&mut self, cnt: usize)207     fn advance(&mut self, cnt: usize);
208 
209     /// Returns true if there are any more bytes to consume
210     ///
211     /// This is equivalent to `self.remaining() != 0`.
212     ///
213     /// # Examples
214     ///
215     /// ```
216     /// use bytes::Buf;
217     ///
218     /// let mut buf = &b"a"[..];
219     ///
220     /// assert!(buf.has_remaining());
221     ///
222     /// buf.get_u8();
223     ///
224     /// assert!(!buf.has_remaining());
225     /// ```
has_remaining(&self) -> bool226     fn has_remaining(&self) -> bool {
227         self.remaining() > 0
228     }
229 
230     /// Copies bytes from `self` into `dst`.
231     ///
232     /// The cursor is advanced by the number of bytes copied. `self` must have
233     /// enough remaining bytes to fill `dst`.
234     ///
235     /// # Examples
236     ///
237     /// ```
238     /// use bytes::Buf;
239     ///
240     /// let mut buf = &b"hello world"[..];
241     /// let mut dst = [0; 5];
242     ///
243     /// buf.copy_to_slice(&mut dst);
244     /// assert_eq!(&b"hello"[..], &dst);
245     /// assert_eq!(6, buf.remaining());
246     /// ```
247     ///
248     /// # Panics
249     ///
250     /// This function panics if `self.remaining() < dst.len()`
copy_to_slice(&mut self, dst: &mut [u8])251     fn copy_to_slice(&mut self, dst: &mut [u8]) {
252         let mut off = 0;
253 
254         assert!(self.remaining() >= dst.len());
255 
256         while off < dst.len() {
257             let cnt;
258 
259             unsafe {
260                 let src = self.chunk();
261                 cnt = cmp::min(src.len(), dst.len() - off);
262 
263                 ptr::copy_nonoverlapping(src.as_ptr(), dst[off..].as_mut_ptr(), cnt);
264 
265                 off += cnt;
266             }
267 
268             self.advance(cnt);
269         }
270     }
271 
272     /// Gets an unsigned 8 bit integer from `self`.
273     ///
274     /// The current position is advanced by 1.
275     ///
276     /// # Examples
277     ///
278     /// ```
279     /// use bytes::Buf;
280     ///
281     /// let mut buf = &b"\x08 hello"[..];
282     /// assert_eq!(8, buf.get_u8());
283     /// ```
284     ///
285     /// # Panics
286     ///
287     /// This function panics if there is no more remaining data in `self`.
get_u8(&mut self) -> u8288     fn get_u8(&mut self) -> u8 {
289         assert!(self.remaining() >= 1);
290         let ret = self.chunk()[0];
291         self.advance(1);
292         ret
293     }
294 
295     /// Gets a signed 8 bit integer from `self`.
296     ///
297     /// The current position is advanced by 1.
298     ///
299     /// # Examples
300     ///
301     /// ```
302     /// use bytes::Buf;
303     ///
304     /// let mut buf = &b"\x08 hello"[..];
305     /// assert_eq!(8, buf.get_i8());
306     /// ```
307     ///
308     /// # Panics
309     ///
310     /// This function panics if there is no more remaining data in `self`.
get_i8(&mut self) -> i8311     fn get_i8(&mut self) -> i8 {
312         assert!(self.remaining() >= 1);
313         let ret = self.chunk()[0] as i8;
314         self.advance(1);
315         ret
316     }
317 
318     /// Gets an unsigned 16 bit integer from `self` in big-endian byte order.
319     ///
320     /// The current position is advanced by 2.
321     ///
322     /// # Examples
323     ///
324     /// ```
325     /// use bytes::Buf;
326     ///
327     /// let mut buf = &b"\x08\x09 hello"[..];
328     /// assert_eq!(0x0809, buf.get_u16());
329     /// ```
330     ///
331     /// # Panics
332     ///
333     /// This function panics if there is not enough remaining data in `self`.
get_u16(&mut self) -> u16334     fn get_u16(&mut self) -> u16 {
335         buf_get_impl!(self, u16::from_be_bytes);
336     }
337 
338     /// Gets an unsigned 16 bit integer from `self` in little-endian byte order.
339     ///
340     /// The current position is advanced by 2.
341     ///
342     /// # Examples
343     ///
344     /// ```
345     /// use bytes::Buf;
346     ///
347     /// let mut buf = &b"\x09\x08 hello"[..];
348     /// assert_eq!(0x0809, buf.get_u16_le());
349     /// ```
350     ///
351     /// # Panics
352     ///
353     /// This function panics if there is not enough remaining data in `self`.
get_u16_le(&mut self) -> u16354     fn get_u16_le(&mut self) -> u16 {
355         buf_get_impl!(self, u16::from_le_bytes);
356     }
357 
358     /// Gets an unsigned 16 bit integer from `self` in native-endian byte order.
359     ///
360     /// The current position is advanced by 2.
361     ///
362     /// # Examples
363     ///
364     /// ```
365     /// use bytes::Buf;
366     ///
367     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
368     ///     true => b"\x08\x09 hello",
369     ///     false => b"\x09\x08 hello",
370     /// };
371     /// assert_eq!(0x0809, buf.get_u16_ne());
372     /// ```
373     ///
374     /// # Panics
375     ///
376     /// This function panics if there is not enough remaining data in `self`.
get_u16_ne(&mut self) -> u16377     fn get_u16_ne(&mut self) -> u16 {
378         buf_get_impl!(self, u16::from_ne_bytes);
379     }
380 
381     /// Gets a signed 16 bit integer from `self` in big-endian byte order.
382     ///
383     /// The current position is advanced by 2.
384     ///
385     /// # Examples
386     ///
387     /// ```
388     /// use bytes::Buf;
389     ///
390     /// let mut buf = &b"\x08\x09 hello"[..];
391     /// assert_eq!(0x0809, buf.get_i16());
392     /// ```
393     ///
394     /// # Panics
395     ///
396     /// This function panics if there is not enough remaining data in `self`.
get_i16(&mut self) -> i16397     fn get_i16(&mut self) -> i16 {
398         buf_get_impl!(self, i16::from_be_bytes);
399     }
400 
401     /// Gets a signed 16 bit integer from `self` in little-endian byte order.
402     ///
403     /// The current position is advanced by 2.
404     ///
405     /// # Examples
406     ///
407     /// ```
408     /// use bytes::Buf;
409     ///
410     /// let mut buf = &b"\x09\x08 hello"[..];
411     /// assert_eq!(0x0809, buf.get_i16_le());
412     /// ```
413     ///
414     /// # Panics
415     ///
416     /// This function panics if there is not enough remaining data in `self`.
get_i16_le(&mut self) -> i16417     fn get_i16_le(&mut self) -> i16 {
418         buf_get_impl!(self, i16::from_le_bytes);
419     }
420 
421     /// Gets a signed 16 bit integer from `self` in native-endian byte order.
422     ///
423     /// The current position is advanced by 2.
424     ///
425     /// # Examples
426     ///
427     /// ```
428     /// use bytes::Buf;
429     ///
430     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
431     ///     true => b"\x08\x09 hello",
432     ///     false => b"\x09\x08 hello",
433     /// };
434     /// assert_eq!(0x0809, buf.get_i16_ne());
435     /// ```
436     ///
437     /// # Panics
438     ///
439     /// This function panics if there is not enough remaining data in `self`.
get_i16_ne(&mut self) -> i16440     fn get_i16_ne(&mut self) -> i16 {
441         buf_get_impl!(self, i16::from_ne_bytes);
442     }
443 
444     /// Gets an unsigned 32 bit integer from `self` in the big-endian byte order.
445     ///
446     /// The current position is advanced by 4.
447     ///
448     /// # Examples
449     ///
450     /// ```
451     /// use bytes::Buf;
452     ///
453     /// let mut buf = &b"\x08\x09\xA0\xA1 hello"[..];
454     /// assert_eq!(0x0809A0A1, buf.get_u32());
455     /// ```
456     ///
457     /// # Panics
458     ///
459     /// This function panics if there is not enough remaining data in `self`.
get_u32(&mut self) -> u32460     fn get_u32(&mut self) -> u32 {
461         buf_get_impl!(self, u32::from_be_bytes);
462     }
463 
464     /// Gets an unsigned 32 bit integer from `self` in the little-endian byte order.
465     ///
466     /// The current position is advanced by 4.
467     ///
468     /// # Examples
469     ///
470     /// ```
471     /// use bytes::Buf;
472     ///
473     /// let mut buf = &b"\xA1\xA0\x09\x08 hello"[..];
474     /// assert_eq!(0x0809A0A1, buf.get_u32_le());
475     /// ```
476     ///
477     /// # Panics
478     ///
479     /// This function panics if there is not enough remaining data in `self`.
get_u32_le(&mut self) -> u32480     fn get_u32_le(&mut self) -> u32 {
481         buf_get_impl!(self, u32::from_le_bytes);
482     }
483 
484     /// Gets an unsigned 32 bit integer from `self` in native-endian byte order.
485     ///
486     /// The current position is advanced by 4.
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// use bytes::Buf;
492     ///
493     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
494     ///     true => b"\x08\x09\xA0\xA1 hello",
495     ///     false => b"\xA1\xA0\x09\x08 hello",
496     /// };
497     /// assert_eq!(0x0809A0A1, buf.get_u32_ne());
498     /// ```
499     ///
500     /// # Panics
501     ///
502     /// This function panics if there is not enough remaining data in `self`.
get_u32_ne(&mut self) -> u32503     fn get_u32_ne(&mut self) -> u32 {
504         buf_get_impl!(self, u32::from_ne_bytes);
505     }
506 
507     /// Gets a signed 32 bit integer from `self` in big-endian byte order.
508     ///
509     /// The current position is advanced by 4.
510     ///
511     /// # Examples
512     ///
513     /// ```
514     /// use bytes::Buf;
515     ///
516     /// let mut buf = &b"\x08\x09\xA0\xA1 hello"[..];
517     /// assert_eq!(0x0809A0A1, buf.get_i32());
518     /// ```
519     ///
520     /// # Panics
521     ///
522     /// This function panics if there is not enough remaining data in `self`.
get_i32(&mut self) -> i32523     fn get_i32(&mut self) -> i32 {
524         buf_get_impl!(self, i32::from_be_bytes);
525     }
526 
527     /// Gets a signed 32 bit integer from `self` in little-endian byte order.
528     ///
529     /// The current position is advanced by 4.
530     ///
531     /// # Examples
532     ///
533     /// ```
534     /// use bytes::Buf;
535     ///
536     /// let mut buf = &b"\xA1\xA0\x09\x08 hello"[..];
537     /// assert_eq!(0x0809A0A1, buf.get_i32_le());
538     /// ```
539     ///
540     /// # Panics
541     ///
542     /// This function panics if there is not enough remaining data in `self`.
get_i32_le(&mut self) -> i32543     fn get_i32_le(&mut self) -> i32 {
544         buf_get_impl!(self, i32::from_le_bytes);
545     }
546 
547     /// Gets a signed 32 bit integer from `self` in native-endian byte order.
548     ///
549     /// The current position is advanced by 4.
550     ///
551     /// # Examples
552     ///
553     /// ```
554     /// use bytes::Buf;
555     ///
556     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
557     ///     true => b"\x08\x09\xA0\xA1 hello",
558     ///     false => b"\xA1\xA0\x09\x08 hello",
559     /// };
560     /// assert_eq!(0x0809A0A1, buf.get_i32_ne());
561     /// ```
562     ///
563     /// # Panics
564     ///
565     /// This function panics if there is not enough remaining data in `self`.
get_i32_ne(&mut self) -> i32566     fn get_i32_ne(&mut self) -> i32 {
567         buf_get_impl!(self, i32::from_ne_bytes);
568     }
569 
570     /// Gets an unsigned 64 bit integer from `self` in big-endian byte order.
571     ///
572     /// The current position is advanced by 8.
573     ///
574     /// # Examples
575     ///
576     /// ```
577     /// use bytes::Buf;
578     ///
579     /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08 hello"[..];
580     /// assert_eq!(0x0102030405060708, buf.get_u64());
581     /// ```
582     ///
583     /// # Panics
584     ///
585     /// This function panics if there is not enough remaining data in `self`.
get_u64(&mut self) -> u64586     fn get_u64(&mut self) -> u64 {
587         buf_get_impl!(self, u64::from_be_bytes);
588     }
589 
590     /// Gets an unsigned 64 bit integer from `self` in little-endian byte order.
591     ///
592     /// The current position is advanced by 8.
593     ///
594     /// # Examples
595     ///
596     /// ```
597     /// use bytes::Buf;
598     ///
599     /// let mut buf = &b"\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
600     /// assert_eq!(0x0102030405060708, buf.get_u64_le());
601     /// ```
602     ///
603     /// # Panics
604     ///
605     /// This function panics if there is not enough remaining data in `self`.
get_u64_le(&mut self) -> u64606     fn get_u64_le(&mut self) -> u64 {
607         buf_get_impl!(self, u64::from_le_bytes);
608     }
609 
610     /// Gets an unsigned 64 bit integer from `self` in native-endian byte order.
611     ///
612     /// The current position is advanced by 8.
613     ///
614     /// # Examples
615     ///
616     /// ```
617     /// use bytes::Buf;
618     ///
619     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
620     ///     true => b"\x01\x02\x03\x04\x05\x06\x07\x08 hello",
621     ///     false => b"\x08\x07\x06\x05\x04\x03\x02\x01 hello",
622     /// };
623     /// assert_eq!(0x0102030405060708, buf.get_u64_ne());
624     /// ```
625     ///
626     /// # Panics
627     ///
628     /// This function panics if there is not enough remaining data in `self`.
get_u64_ne(&mut self) -> u64629     fn get_u64_ne(&mut self) -> u64 {
630         buf_get_impl!(self, u64::from_ne_bytes);
631     }
632 
633     /// Gets a signed 64 bit integer from `self` in big-endian byte order.
634     ///
635     /// The current position is advanced by 8.
636     ///
637     /// # Examples
638     ///
639     /// ```
640     /// use bytes::Buf;
641     ///
642     /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08 hello"[..];
643     /// assert_eq!(0x0102030405060708, buf.get_i64());
644     /// ```
645     ///
646     /// # Panics
647     ///
648     /// This function panics if there is not enough remaining data in `self`.
get_i64(&mut self) -> i64649     fn get_i64(&mut self) -> i64 {
650         buf_get_impl!(self, i64::from_be_bytes);
651     }
652 
653     /// Gets a signed 64 bit integer from `self` in little-endian byte order.
654     ///
655     /// The current position is advanced by 8.
656     ///
657     /// # Examples
658     ///
659     /// ```
660     /// use bytes::Buf;
661     ///
662     /// let mut buf = &b"\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
663     /// assert_eq!(0x0102030405060708, buf.get_i64_le());
664     /// ```
665     ///
666     /// # Panics
667     ///
668     /// This function panics if there is not enough remaining data in `self`.
get_i64_le(&mut self) -> i64669     fn get_i64_le(&mut self) -> i64 {
670         buf_get_impl!(self, i64::from_le_bytes);
671     }
672 
673     /// Gets a signed 64 bit integer from `self` in native-endian byte order.
674     ///
675     /// The current position is advanced by 8.
676     ///
677     /// # Examples
678     ///
679     /// ```
680     /// use bytes::Buf;
681     ///
682     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
683     ///     true => b"\x01\x02\x03\x04\x05\x06\x07\x08 hello",
684     ///     false => b"\x08\x07\x06\x05\x04\x03\x02\x01 hello",
685     /// };
686     /// assert_eq!(0x0102030405060708, buf.get_i64_ne());
687     /// ```
688     ///
689     /// # Panics
690     ///
691     /// This function panics if there is not enough remaining data in `self`.
get_i64_ne(&mut self) -> i64692     fn get_i64_ne(&mut self) -> i64 {
693         buf_get_impl!(self, i64::from_ne_bytes);
694     }
695 
696     /// Gets an unsigned 128 bit integer from `self` in big-endian byte order.
697     ///
698     /// The current position is advanced by 16.
699     ///
700     /// # Examples
701     ///
702     /// ```
703     /// use bytes::Buf;
704     ///
705     /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello"[..];
706     /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128());
707     /// ```
708     ///
709     /// # Panics
710     ///
711     /// This function panics if there is not enough remaining data in `self`.
get_u128(&mut self) -> u128712     fn get_u128(&mut self) -> u128 {
713         buf_get_impl!(self, u128::from_be_bytes);
714     }
715 
716     /// Gets an unsigned 128 bit integer from `self` in little-endian byte order.
717     ///
718     /// The current position is advanced by 16.
719     ///
720     /// # Examples
721     ///
722     /// ```
723     /// use bytes::Buf;
724     ///
725     /// let mut buf = &b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
726     /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128_le());
727     /// ```
728     ///
729     /// # Panics
730     ///
731     /// This function panics if there is not enough remaining data in `self`.
get_u128_le(&mut self) -> u128732     fn get_u128_le(&mut self) -> u128 {
733         buf_get_impl!(self, u128::from_le_bytes);
734     }
735 
736     /// Gets an unsigned 128 bit integer from `self` in native-endian byte order.
737     ///
738     /// The current position is advanced by 16.
739     ///
740     /// # Examples
741     ///
742     /// ```
743     /// use bytes::Buf;
744     ///
745     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
746     ///     true => b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello",
747     ///     false => b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello",
748     /// };
749     /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128_ne());
750     /// ```
751     ///
752     /// # Panics
753     ///
754     /// This function panics if there is not enough remaining data in `self`.
get_u128_ne(&mut self) -> u128755     fn get_u128_ne(&mut self) -> u128 {
756         buf_get_impl!(self, u128::from_ne_bytes);
757     }
758 
759     /// Gets a signed 128 bit integer from `self` in big-endian byte order.
760     ///
761     /// The current position is advanced by 16.
762     ///
763     /// # Examples
764     ///
765     /// ```
766     /// use bytes::Buf;
767     ///
768     /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello"[..];
769     /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128());
770     /// ```
771     ///
772     /// # Panics
773     ///
774     /// This function panics if there is not enough remaining data in `self`.
get_i128(&mut self) -> i128775     fn get_i128(&mut self) -> i128 {
776         buf_get_impl!(self, i128::from_be_bytes);
777     }
778 
779     /// Gets a signed 128 bit integer from `self` in little-endian byte order.
780     ///
781     /// The current position is advanced by 16.
782     ///
783     /// # Examples
784     ///
785     /// ```
786     /// use bytes::Buf;
787     ///
788     /// let mut buf = &b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
789     /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128_le());
790     /// ```
791     ///
792     /// # Panics
793     ///
794     /// This function panics if there is not enough remaining data in `self`.
get_i128_le(&mut self) -> i128795     fn get_i128_le(&mut self) -> i128 {
796         buf_get_impl!(self, i128::from_le_bytes);
797     }
798 
799     /// Gets a signed 128 bit integer from `self` in native-endian byte order.
800     ///
801     /// The current position is advanced by 16.
802     ///
803     /// # Examples
804     ///
805     /// ```
806     /// use bytes::Buf;
807     ///
808     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
809     ///     true => b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello",
810     ///     false => b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello",
811     /// };
812     /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128_ne());
813     /// ```
814     ///
815     /// # Panics
816     ///
817     /// This function panics if there is not enough remaining data in `self`.
get_i128_ne(&mut self) -> i128818     fn get_i128_ne(&mut self) -> i128 {
819         buf_get_impl!(self, i128::from_ne_bytes);
820     }
821 
822     /// Gets an unsigned n-byte integer from `self` in big-endian byte order.
823     ///
824     /// The current position is advanced by `nbytes`.
825     ///
826     /// # Examples
827     ///
828     /// ```
829     /// use bytes::Buf;
830     ///
831     /// let mut buf = &b"\x01\x02\x03 hello"[..];
832     /// assert_eq!(0x010203, buf.get_uint(3));
833     /// ```
834     ///
835     /// # Panics
836     ///
837     /// This function panics if there is not enough remaining data in `self`.
get_uint(&mut self, nbytes: usize) -> u64838     fn get_uint(&mut self, nbytes: usize) -> u64 {
839         buf_get_impl!(be => self, u64, nbytes);
840     }
841 
842     /// Gets an unsigned n-byte integer from `self` in little-endian byte order.
843     ///
844     /// The current position is advanced by `nbytes`.
845     ///
846     /// # Examples
847     ///
848     /// ```
849     /// use bytes::Buf;
850     ///
851     /// let mut buf = &b"\x03\x02\x01 hello"[..];
852     /// assert_eq!(0x010203, buf.get_uint_le(3));
853     /// ```
854     ///
855     /// # Panics
856     ///
857     /// This function panics if there is not enough remaining data in `self`.
get_uint_le(&mut self, nbytes: usize) -> u64858     fn get_uint_le(&mut self, nbytes: usize) -> u64 {
859         buf_get_impl!(le => self, u64, nbytes);
860     }
861 
862     /// Gets an unsigned n-byte integer from `self` in native-endian byte order.
863     ///
864     /// The current position is advanced by `nbytes`.
865     ///
866     /// # Examples
867     ///
868     /// ```
869     /// use bytes::Buf;
870     ///
871     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
872     ///     true => b"\x01\x02\x03 hello",
873     ///     false => b"\x03\x02\x01 hello",
874     /// };
875     /// assert_eq!(0x010203, buf.get_uint_ne(3));
876     /// ```
877     ///
878     /// # Panics
879     ///
880     /// This function panics if there is not enough remaining data in `self`.
get_uint_ne(&mut self, nbytes: usize) -> u64881     fn get_uint_ne(&mut self, nbytes: usize) -> u64 {
882         if cfg!(target_endian = "big") {
883             self.get_uint(nbytes)
884         } else {
885             self.get_uint_le(nbytes)
886         }
887     }
888 
889     /// Gets a signed n-byte integer from `self` in big-endian byte order.
890     ///
891     /// The current position is advanced by `nbytes`.
892     ///
893     /// # Examples
894     ///
895     /// ```
896     /// use bytes::Buf;
897     ///
898     /// let mut buf = &b"\x01\x02\x03 hello"[..];
899     /// assert_eq!(0x010203, buf.get_int(3));
900     /// ```
901     ///
902     /// # Panics
903     ///
904     /// This function panics if there is not enough remaining data in `self`.
get_int(&mut self, nbytes: usize) -> i64905     fn get_int(&mut self, nbytes: usize) -> i64 {
906         buf_get_impl!(be => self, i64, nbytes);
907     }
908 
909     /// Gets a signed n-byte integer from `self` in little-endian byte order.
910     ///
911     /// The current position is advanced by `nbytes`.
912     ///
913     /// # Examples
914     ///
915     /// ```
916     /// use bytes::Buf;
917     ///
918     /// let mut buf = &b"\x03\x02\x01 hello"[..];
919     /// assert_eq!(0x010203, buf.get_int_le(3));
920     /// ```
921     ///
922     /// # Panics
923     ///
924     /// This function panics if there is not enough remaining data in `self`.
get_int_le(&mut self, nbytes: usize) -> i64925     fn get_int_le(&mut self, nbytes: usize) -> i64 {
926         buf_get_impl!(le => self, i64, nbytes);
927     }
928 
929     /// Gets a signed n-byte integer from `self` in native-endian byte order.
930     ///
931     /// The current position is advanced by `nbytes`.
932     ///
933     /// # Examples
934     ///
935     /// ```
936     /// use bytes::Buf;
937     ///
938     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
939     ///     true => b"\x01\x02\x03 hello",
940     ///     false => b"\x03\x02\x01 hello",
941     /// };
942     /// assert_eq!(0x010203, buf.get_int_ne(3));
943     /// ```
944     ///
945     /// # Panics
946     ///
947     /// This function panics if there is not enough remaining data in `self`.
get_int_ne(&mut self, nbytes: usize) -> i64948     fn get_int_ne(&mut self, nbytes: usize) -> i64 {
949         if cfg!(target_endian = "big") {
950             self.get_int(nbytes)
951         } else {
952             self.get_int_le(nbytes)
953         }
954     }
955 
956     /// Gets an IEEE754 single-precision (4 bytes) floating point number from
957     /// `self` in big-endian byte order.
958     ///
959     /// The current position is advanced by 4.
960     ///
961     /// # Examples
962     ///
963     /// ```
964     /// use bytes::Buf;
965     ///
966     /// let mut buf = &b"\x3F\x99\x99\x9A hello"[..];
967     /// assert_eq!(1.2f32, buf.get_f32());
968     /// ```
969     ///
970     /// # Panics
971     ///
972     /// This function panics if there is not enough remaining data in `self`.
get_f32(&mut self) -> f32973     fn get_f32(&mut self) -> f32 {
974         f32::from_bits(Self::get_u32(self))
975     }
976 
977     /// Gets an IEEE754 single-precision (4 bytes) floating point number from
978     /// `self` in little-endian byte order.
979     ///
980     /// The current position is advanced by 4.
981     ///
982     /// # Examples
983     ///
984     /// ```
985     /// use bytes::Buf;
986     ///
987     /// let mut buf = &b"\x9A\x99\x99\x3F hello"[..];
988     /// assert_eq!(1.2f32, buf.get_f32_le());
989     /// ```
990     ///
991     /// # Panics
992     ///
993     /// This function panics if there is not enough remaining data in `self`.
get_f32_le(&mut self) -> f32994     fn get_f32_le(&mut self) -> f32 {
995         f32::from_bits(Self::get_u32_le(self))
996     }
997 
998     /// Gets an IEEE754 single-precision (4 bytes) floating point number from
999     /// `self` in native-endian byte order.
1000     ///
1001     /// The current position is advanced by 4.
1002     ///
1003     /// # Examples
1004     ///
1005     /// ```
1006     /// use bytes::Buf;
1007     ///
1008     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
1009     ///     true => b"\x3F\x99\x99\x9A hello",
1010     ///     false => b"\x9A\x99\x99\x3F hello",
1011     /// };
1012     /// assert_eq!(1.2f32, buf.get_f32_ne());
1013     /// ```
1014     ///
1015     /// # Panics
1016     ///
1017     /// This function panics if there is not enough remaining data in `self`.
get_f32_ne(&mut self) -> f321018     fn get_f32_ne(&mut self) -> f32 {
1019         f32::from_bits(Self::get_u32_ne(self))
1020     }
1021 
1022     /// Gets an IEEE754 double-precision (8 bytes) floating point number from
1023     /// `self` in big-endian byte order.
1024     ///
1025     /// The current position is advanced by 8.
1026     ///
1027     /// # Examples
1028     ///
1029     /// ```
1030     /// use bytes::Buf;
1031     ///
1032     /// let mut buf = &b"\x3F\xF3\x33\x33\x33\x33\x33\x33 hello"[..];
1033     /// assert_eq!(1.2f64, buf.get_f64());
1034     /// ```
1035     ///
1036     /// # Panics
1037     ///
1038     /// This function panics if there is not enough remaining data in `self`.
get_f64(&mut self) -> f641039     fn get_f64(&mut self) -> f64 {
1040         f64::from_bits(Self::get_u64(self))
1041     }
1042 
1043     /// Gets an IEEE754 double-precision (8 bytes) floating point number from
1044     /// `self` in little-endian byte order.
1045     ///
1046     /// The current position is advanced by 8.
1047     ///
1048     /// # Examples
1049     ///
1050     /// ```
1051     /// use bytes::Buf;
1052     ///
1053     /// let mut buf = &b"\x33\x33\x33\x33\x33\x33\xF3\x3F hello"[..];
1054     /// assert_eq!(1.2f64, buf.get_f64_le());
1055     /// ```
1056     ///
1057     /// # Panics
1058     ///
1059     /// This function panics if there is not enough remaining data in `self`.
get_f64_le(&mut self) -> f641060     fn get_f64_le(&mut self) -> f64 {
1061         f64::from_bits(Self::get_u64_le(self))
1062     }
1063 
1064     /// Gets an IEEE754 double-precision (8 bytes) floating point number from
1065     /// `self` in native-endian byte order.
1066     ///
1067     /// The current position is advanced by 8.
1068     ///
1069     /// # Examples
1070     ///
1071     /// ```
1072     /// use bytes::Buf;
1073     ///
1074     /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
1075     ///     true => b"\x3F\xF3\x33\x33\x33\x33\x33\x33 hello",
1076     ///     false => b"\x33\x33\x33\x33\x33\x33\xF3\x3F hello",
1077     /// };
1078     /// assert_eq!(1.2f64, buf.get_f64_ne());
1079     /// ```
1080     ///
1081     /// # Panics
1082     ///
1083     /// This function panics if there is not enough remaining data in `self`.
get_f64_ne(&mut self) -> f641084     fn get_f64_ne(&mut self) -> f64 {
1085         f64::from_bits(Self::get_u64_ne(self))
1086     }
1087 
1088     /// Consumes `len` bytes inside self and returns new instance of `Bytes`
1089     /// with this data.
1090     ///
1091     /// This function may be optimized by the underlying type to avoid actual
1092     /// copies. For example, `Bytes` implementation will do a shallow copy
1093     /// (ref-count increment).
1094     ///
1095     /// # Examples
1096     ///
1097     /// ```
1098     /// use bytes::Buf;
1099     ///
1100     /// let bytes = (&b"hello world"[..]).copy_to_bytes(5);
1101     /// assert_eq!(&bytes[..], &b"hello"[..]);
1102     /// ```
copy_to_bytes(&mut self, len: usize) -> crate::Bytes1103     fn copy_to_bytes(&mut self, len: usize) -> crate::Bytes {
1104         use super::BufMut;
1105 
1106         assert!(len <= self.remaining(), "`len` greater than remaining");
1107 
1108         let mut ret = crate::BytesMut::with_capacity(len);
1109         ret.put(self.take(len));
1110         ret.freeze()
1111     }
1112 
1113     /// Creates an adaptor which will read at most `limit` bytes from `self`.
1114     ///
1115     /// This function returns a new instance of `Buf` which will read at most
1116     /// `limit` bytes.
1117     ///
1118     /// # Examples
1119     ///
1120     /// ```
1121     /// use bytes::{Buf, BufMut};
1122     ///
1123     /// let mut buf = b"hello world"[..].take(5);
1124     /// let mut dst = vec![];
1125     ///
1126     /// dst.put(&mut buf);
1127     /// assert_eq!(dst, b"hello");
1128     ///
1129     /// let mut buf = buf.into_inner();
1130     /// dst.clear();
1131     /// dst.put(&mut buf);
1132     /// assert_eq!(dst, b" world");
1133     /// ```
take(self, limit: usize) -> Take<Self> where Self: Sized,1134     fn take(self, limit: usize) -> Take<Self>
1135     where
1136         Self: Sized,
1137     {
1138         take::new(self, limit)
1139     }
1140 
1141     /// Creates an adaptor which will chain this buffer with another.
1142     ///
1143     /// The returned `Buf` instance will first consume all bytes from `self`.
1144     /// Afterwards the output is equivalent to the output of next.
1145     ///
1146     /// # Examples
1147     ///
1148     /// ```
1149     /// use bytes::Buf;
1150     ///
1151     /// let mut chain = b"hello "[..].chain(&b"world"[..]);
1152     ///
1153     /// let full = chain.copy_to_bytes(11);
1154     /// assert_eq!(full.chunk(), b"hello world");
1155     /// ```
chain<U: Buf>(self, next: U) -> Chain<Self, U> where Self: Sized,1156     fn chain<U: Buf>(self, next: U) -> Chain<Self, U>
1157     where
1158         Self: Sized,
1159     {
1160         Chain::new(self, next)
1161     }
1162 
1163     /// Creates an adaptor which implements the `Read` trait for `self`.
1164     ///
1165     /// This function returns a new value which implements `Read` by adapting
1166     /// the `Read` trait functions to the `Buf` trait functions. Given that
1167     /// `Buf` operations are infallible, none of the `Read` functions will
1168     /// return with `Err`.
1169     ///
1170     /// # Examples
1171     ///
1172     /// ```
1173     /// use bytes::{Bytes, Buf};
1174     /// use std::io::Read;
1175     ///
1176     /// let buf = Bytes::from("hello world");
1177     ///
1178     /// let mut reader = buf.reader();
1179     /// let mut dst = [0; 1024];
1180     ///
1181     /// let num = reader.read(&mut dst).unwrap();
1182     ///
1183     /// assert_eq!(11, num);
1184     /// assert_eq!(&dst[..11], &b"hello world"[..]);
1185     /// ```
1186     #[cfg(feature = "std")]
1187     #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
reader(self) -> Reader<Self> where Self: Sized,1188     fn reader(self) -> Reader<Self>
1189     where
1190         Self: Sized,
1191     {
1192         reader::new(self)
1193     }
1194 }
1195 
1196 macro_rules! deref_forward_buf {
1197     () => {
1198         fn remaining(&self) -> usize {
1199             (**self).remaining()
1200         }
1201 
1202         fn chunk(&self) -> &[u8] {
1203             (**self).chunk()
1204         }
1205 
1206         #[cfg(feature = "std")]
1207         fn chunks_vectored<'b>(&'b self, dst: &mut [IoSlice<'b>]) -> usize {
1208             (**self).chunks_vectored(dst)
1209         }
1210 
1211         fn advance(&mut self, cnt: usize) {
1212             (**self).advance(cnt)
1213         }
1214 
1215         fn has_remaining(&self) -> bool {
1216             (**self).has_remaining()
1217         }
1218 
1219         fn copy_to_slice(&mut self, dst: &mut [u8]) {
1220             (**self).copy_to_slice(dst)
1221         }
1222 
1223         fn get_u8(&mut self) -> u8 {
1224             (**self).get_u8()
1225         }
1226 
1227         fn get_i8(&mut self) -> i8 {
1228             (**self).get_i8()
1229         }
1230 
1231         fn get_u16(&mut self) -> u16 {
1232             (**self).get_u16()
1233         }
1234 
1235         fn get_u16_le(&mut self) -> u16 {
1236             (**self).get_u16_le()
1237         }
1238 
1239         fn get_u16_ne(&mut self) -> u16 {
1240             (**self).get_u16_ne()
1241         }
1242 
1243         fn get_i16(&mut self) -> i16 {
1244             (**self).get_i16()
1245         }
1246 
1247         fn get_i16_le(&mut self) -> i16 {
1248             (**self).get_i16_le()
1249         }
1250 
1251         fn get_i16_ne(&mut self) -> i16 {
1252             (**self).get_i16_ne()
1253         }
1254 
1255         fn get_u32(&mut self) -> u32 {
1256             (**self).get_u32()
1257         }
1258 
1259         fn get_u32_le(&mut self) -> u32 {
1260             (**self).get_u32_le()
1261         }
1262 
1263         fn get_u32_ne(&mut self) -> u32 {
1264             (**self).get_u32_ne()
1265         }
1266 
1267         fn get_i32(&mut self) -> i32 {
1268             (**self).get_i32()
1269         }
1270 
1271         fn get_i32_le(&mut self) -> i32 {
1272             (**self).get_i32_le()
1273         }
1274 
1275         fn get_i32_ne(&mut self) -> i32 {
1276             (**self).get_i32_ne()
1277         }
1278 
1279         fn get_u64(&mut self) -> u64 {
1280             (**self).get_u64()
1281         }
1282 
1283         fn get_u64_le(&mut self) -> u64 {
1284             (**self).get_u64_le()
1285         }
1286 
1287         fn get_u64_ne(&mut self) -> u64 {
1288             (**self).get_u64_ne()
1289         }
1290 
1291         fn get_i64(&mut self) -> i64 {
1292             (**self).get_i64()
1293         }
1294 
1295         fn get_i64_le(&mut self) -> i64 {
1296             (**self).get_i64_le()
1297         }
1298 
1299         fn get_i64_ne(&mut self) -> i64 {
1300             (**self).get_i64_ne()
1301         }
1302 
1303         fn get_uint(&mut self, nbytes: usize) -> u64 {
1304             (**self).get_uint(nbytes)
1305         }
1306 
1307         fn get_uint_le(&mut self, nbytes: usize) -> u64 {
1308             (**self).get_uint_le(nbytes)
1309         }
1310 
1311         fn get_uint_ne(&mut self, nbytes: usize) -> u64 {
1312             (**self).get_uint_ne(nbytes)
1313         }
1314 
1315         fn get_int(&mut self, nbytes: usize) -> i64 {
1316             (**self).get_int(nbytes)
1317         }
1318 
1319         fn get_int_le(&mut self, nbytes: usize) -> i64 {
1320             (**self).get_int_le(nbytes)
1321         }
1322 
1323         fn get_int_ne(&mut self, nbytes: usize) -> i64 {
1324             (**self).get_int_ne(nbytes)
1325         }
1326 
1327         fn copy_to_bytes(&mut self, len: usize) -> crate::Bytes {
1328             (**self).copy_to_bytes(len)
1329         }
1330     };
1331 }
1332 
1333 impl<T: Buf + ?Sized> Buf for &mut T {
1334     deref_forward_buf!();
1335 }
1336 
1337 impl<T: Buf + ?Sized> Buf for Box<T> {
1338     deref_forward_buf!();
1339 }
1340 
1341 impl Buf for &[u8] {
1342     #[inline]
remaining(&self) -> usize1343     fn remaining(&self) -> usize {
1344         self.len()
1345     }
1346 
1347     #[inline]
chunk(&self) -> &[u8]1348     fn chunk(&self) -> &[u8] {
1349         self
1350     }
1351 
1352     #[inline]
advance(&mut self, cnt: usize)1353     fn advance(&mut self, cnt: usize) {
1354         *self = &self[cnt..];
1355     }
1356 }
1357 
1358 #[cfg(feature = "std")]
1359 impl<T: AsRef<[u8]>> Buf for std::io::Cursor<T> {
remaining(&self) -> usize1360     fn remaining(&self) -> usize {
1361         let len = self.get_ref().as_ref().len();
1362         let pos = self.position();
1363 
1364         if pos >= len as u64 {
1365             return 0;
1366         }
1367 
1368         len - pos as usize
1369     }
1370 
chunk(&self) -> &[u8]1371     fn chunk(&self) -> &[u8] {
1372         let len = self.get_ref().as_ref().len();
1373         let pos = self.position();
1374 
1375         if pos >= len as u64 {
1376             return &[];
1377         }
1378 
1379         &self.get_ref().as_ref()[pos as usize..]
1380     }
1381 
advance(&mut self, cnt: usize)1382     fn advance(&mut self, cnt: usize) {
1383         let pos = (self.position() as usize)
1384             .checked_add(cnt)
1385             .expect("overflow");
1386 
1387         assert!(pos <= self.get_ref().as_ref().len());
1388         self.set_position(pos as u64);
1389     }
1390 }
1391 
1392 // The existence of this function makes the compiler catch if the Buf
1393 // trait is "object-safe" or not.
_assert_trait_object(_b: &dyn Buf)1394 fn _assert_trait_object(_b: &dyn Buf) {}
1395