bytes/buf/buf_impl.rs
1#[cfg(feature = "std")]
2use crate::buf::{reader, Reader};
3use crate::buf::{take, Chain, Take};
4#[cfg(feature = "std")]
5use crate::{min_u64_usize, saturating_sub_usize_u64};
6use crate::{panic_advance, panic_does_not_fit};
7
8#[cfg(feature = "std")]
9use std::io::IoSlice;
10
11use alloc::boxed::Box;
12
13macro_rules! buf_get_impl {
14 ($this:ident, $typ:tt::$conv:tt) => {{
15 const SIZE: usize = core::mem::size_of::<$typ>();
16
17 if $this.remaining() < SIZE {
18 panic_advance(SIZE, $this.remaining());
19 }
20
21 // try to convert directly from the bytes
22 // this Option<ret> trick is to avoid keeping a borrow on self
23 // when advance() is called (mut borrow) and to call bytes() only once
24 let ret = $this
25 .chunk()
26 .get(..SIZE)
27 .map(|src| unsafe { $typ::$conv(*(src as *const _ as *const [_; SIZE])) });
28
29 if let Some(ret) = ret {
30 // if the direct conversion was possible, advance and return
31 $this.advance(SIZE);
32 return ret;
33 } else {
34 // if not we copy the bytes in a temp buffer then convert
35 let mut buf = [0; SIZE];
36 $this.copy_to_slice(&mut buf); // (do the advance)
37 return $typ::$conv(buf);
38 }
39 }};
40 (le => $this:ident, $typ:tt, $len_to_read:expr) => {{
41 const SIZE: usize = core::mem::size_of::<$typ>();
42
43 // The same trick as above does not improve the best case speed.
44 // It seems to be linked to the way the method is optimised by the compiler
45 let mut buf = [0; SIZE];
46
47 let subslice = match buf.get_mut(..$len_to_read) {
48 Some(subslice) => subslice,
49 None => panic_does_not_fit(SIZE, $len_to_read),
50 };
51
52 $this.copy_to_slice(subslice);
53 return $typ::from_le_bytes(buf);
54 }};
55 (be => $this:ident, $typ:tt, $len_to_read:expr) => {{
56 const SIZE: usize = core::mem::size_of::<$typ>();
57
58 let slice_at = match SIZE.checked_sub($len_to_read) {
59 Some(slice_at) => slice_at,
60 None => panic_does_not_fit(SIZE, $len_to_read),
61 };
62
63 let mut buf = [0; SIZE];
64 $this.copy_to_slice(&mut buf[slice_at..]);
65 return $typ::from_be_bytes(buf);
66 }};
67}
68
69// https://en.wikipedia.org/wiki/Sign_extension
70fn sign_extend(val: u64, nbytes: usize) -> i64 {
71 let shift = (8 - nbytes) * 8;
72 (val << shift) as i64 >> shift
73}
74
75/// Read bytes from a buffer.
76///
77/// A buffer stores bytes in memory such that read operations are infallible.
78/// The underlying storage may or may not be in contiguous memory. A `Buf` value
79/// is a cursor into the buffer. Reading from `Buf` advances the cursor
80/// position. It can be thought of as an efficient `Iterator` for collections of
81/// bytes.
82///
83/// The simplest `Buf` is a `&[u8]`.
84///
85/// ```
86/// use bytes::Buf;
87///
88/// let mut buf = &b"hello world"[..];
89///
90/// assert_eq!(b'h', buf.get_u8());
91/// assert_eq!(b'e', buf.get_u8());
92/// assert_eq!(b'l', buf.get_u8());
93///
94/// let mut rest = [0; 8];
95/// buf.copy_to_slice(&mut rest);
96///
97/// assert_eq!(&rest[..], &b"lo world"[..]);
98/// ```
99pub trait Buf {
100 /// Returns the number of bytes between the current position and the end of
101 /// the buffer.
102 ///
103 /// This value is greater than or equal to the length of the slice returned
104 /// by `chunk()`.
105 ///
106 /// # Examples
107 ///
108 /// ```
109 /// use bytes::Buf;
110 ///
111 /// let mut buf = &b"hello world"[..];
112 ///
113 /// assert_eq!(buf.remaining(), 11);
114 ///
115 /// buf.get_u8();
116 ///
117 /// assert_eq!(buf.remaining(), 10);
118 /// ```
119 ///
120 /// # Implementer notes
121 ///
122 /// Implementations of `remaining` should ensure that the return value does
123 /// not change unless a call is made to `advance` or any other function that
124 /// is documented to change the `Buf`'s current position.
125 fn remaining(&self) -> usize;
126
127 /// Returns a slice starting at the current position and of length between 0
128 /// and `Buf::remaining()`. Note that this *can* return a shorter slice (this
129 /// allows non-continuous internal representation).
130 ///
131 /// This is a lower level function. Most operations are done with other
132 /// functions.
133 ///
134 /// # Examples
135 ///
136 /// ```
137 /// use bytes::Buf;
138 ///
139 /// let mut buf = &b"hello world"[..];
140 ///
141 /// assert_eq!(buf.chunk(), &b"hello world"[..]);
142 ///
143 /// buf.advance(6);
144 ///
145 /// assert_eq!(buf.chunk(), &b"world"[..]);
146 /// ```
147 ///
148 /// # Implementer notes
149 ///
150 /// This function should never panic. `chunk()` should return an empty
151 /// slice **if and only if** `remaining()` returns 0. In other words,
152 /// `chunk()` returning an empty slice implies that `remaining()` will
153 /// return 0 and `remaining()` returning 0 implies that `chunk()` will
154 /// return an empty slice.
155 // The `chunk` method was previously called `bytes`. This alias makes the rename
156 // more easily discoverable.
157 #[cfg_attr(docsrs, doc(alias = "bytes"))]
158 fn chunk(&self) -> &[u8];
159
160 /// Fills `dst` with potentially multiple slices starting at `self`'s
161 /// current position.
162 ///
163 /// If the `Buf` is backed by disjoint slices of bytes, `chunk_vectored` enables
164 /// fetching more than one slice at once. `dst` is a slice of `IoSlice`
165 /// references, enabling the slice to be directly used with [`writev`]
166 /// without any further conversion. The sum of the lengths of all the
167 /// buffers in `dst` will be less than or equal to `Buf::remaining()`.
168 ///
169 /// The entries in `dst` will be overwritten, but the data **contained** by
170 /// the slices **will not** be modified. If `chunk_vectored` does not fill every
171 /// entry in `dst`, then `dst` is guaranteed to contain all remaining slices
172 /// in `self.
173 ///
174 /// This is a lower level function. Most operations are done with other
175 /// functions.
176 ///
177 /// # Implementer notes
178 ///
179 /// This function should never panic. Once the end of the buffer is reached,
180 /// i.e., `Buf::remaining` returns 0, calls to `chunk_vectored` must return 0
181 /// without mutating `dst`.
182 ///
183 /// Implementations should also take care to properly handle being called
184 /// with `dst` being a zero length slice.
185 ///
186 /// [`writev`]: http://man7.org/linux/man-pages/man2/readv.2.html
187 #[cfg(feature = "std")]
188 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
189 fn chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize {
190 if dst.is_empty() {
191 return 0;
192 }
193
194 if self.has_remaining() {
195 dst[0] = IoSlice::new(self.chunk());
196 1
197 } else {
198 0
199 }
200 }
201
202 /// Advance the internal cursor of the Buf
203 ///
204 /// The next call to `chunk()` will return a slice starting `cnt` bytes
205 /// further into the underlying buffer.
206 ///
207 /// # Examples
208 ///
209 /// ```
210 /// use bytes::Buf;
211 ///
212 /// let mut buf = &b"hello world"[..];
213 ///
214 /// assert_eq!(buf.chunk(), &b"hello world"[..]);
215 ///
216 /// buf.advance(6);
217 ///
218 /// assert_eq!(buf.chunk(), &b"world"[..]);
219 /// ```
220 ///
221 /// # Panics
222 ///
223 /// This function **may** panic if `cnt > self.remaining()`.
224 ///
225 /// # Implementer notes
226 ///
227 /// It is recommended for implementations of `advance` to panic if `cnt >
228 /// self.remaining()`. If the implementation does not panic, the call must
229 /// behave as if `cnt == self.remaining()`.
230 ///
231 /// A call with `cnt == 0` should never panic and be a no-op.
232 fn advance(&mut self, cnt: usize);
233
234 /// Returns true if there are any more bytes to consume
235 ///
236 /// This is equivalent to `self.remaining() != 0`.
237 ///
238 /// # Examples
239 ///
240 /// ```
241 /// use bytes::Buf;
242 ///
243 /// let mut buf = &b"a"[..];
244 ///
245 /// assert!(buf.has_remaining());
246 ///
247 /// buf.get_u8();
248 ///
249 /// assert!(!buf.has_remaining());
250 /// ```
251 fn has_remaining(&self) -> bool {
252 self.remaining() > 0
253 }
254
255 /// Copies bytes from `self` into `dst`.
256 ///
257 /// The cursor is advanced by the number of bytes copied. `self` must have
258 /// enough remaining bytes to fill `dst`.
259 ///
260 /// # Examples
261 ///
262 /// ```
263 /// use bytes::Buf;
264 ///
265 /// let mut buf = &b"hello world"[..];
266 /// let mut dst = [0; 5];
267 ///
268 /// buf.copy_to_slice(&mut dst);
269 /// assert_eq!(&b"hello"[..], &dst);
270 /// assert_eq!(6, buf.remaining());
271 /// ```
272 ///
273 /// # Panics
274 ///
275 /// This function panics if `self.remaining() < dst.len()`.
276 fn copy_to_slice(&mut self, mut dst: &mut [u8]) {
277 if self.remaining() < dst.len() {
278 panic_advance(dst.len(), self.remaining());
279 }
280
281 while !dst.is_empty() {
282 let src = self.chunk();
283 let cnt = usize::min(src.len(), dst.len());
284
285 dst[..cnt].copy_from_slice(&src[..cnt]);
286 dst = &mut dst[cnt..];
287
288 self.advance(cnt);
289 }
290 }
291
292 /// Gets an unsigned 8 bit integer from `self`.
293 ///
294 /// The current position is advanced by 1.
295 ///
296 /// # Examples
297 ///
298 /// ```
299 /// use bytes::Buf;
300 ///
301 /// let mut buf = &b"\x08 hello"[..];
302 /// assert_eq!(8, buf.get_u8());
303 /// ```
304 ///
305 /// # Panics
306 ///
307 /// This function panics if there is no more remaining data in `self`.
308 fn get_u8(&mut self) -> u8 {
309 if self.remaining() < 1 {
310 panic_advance(1, 0);
311 }
312 let ret = self.chunk()[0];
313 self.advance(1);
314 ret
315 }
316
317 /// Gets a signed 8 bit integer from `self`.
318 ///
319 /// The current position is advanced by 1.
320 ///
321 /// # Examples
322 ///
323 /// ```
324 /// use bytes::Buf;
325 ///
326 /// let mut buf = &b"\x08 hello"[..];
327 /// assert_eq!(8, buf.get_i8());
328 /// ```
329 ///
330 /// # Panics
331 ///
332 /// This function panics if there is no more remaining data in `self`.
333 fn get_i8(&mut self) -> i8 {
334 if self.remaining() < 1 {
335 panic_advance(1, 0);
336 }
337 let ret = self.chunk()[0] as i8;
338 self.advance(1);
339 ret
340 }
341
342 /// Gets an unsigned 16 bit integer from `self` in big-endian byte order.
343 ///
344 /// The current position is advanced by 2.
345 ///
346 /// # Examples
347 ///
348 /// ```
349 /// use bytes::Buf;
350 ///
351 /// let mut buf = &b"\x08\x09 hello"[..];
352 /// assert_eq!(0x0809, buf.get_u16());
353 /// ```
354 ///
355 /// # Panics
356 ///
357 /// This function panics if there is not enough remaining data in `self`.
358 fn get_u16(&mut self) -> u16 {
359 buf_get_impl!(self, u16::from_be_bytes);
360 }
361
362 /// Gets an unsigned 16 bit integer from `self` in little-endian byte order.
363 ///
364 /// The current position is advanced by 2.
365 ///
366 /// # Examples
367 ///
368 /// ```
369 /// use bytes::Buf;
370 ///
371 /// let mut buf = &b"\x09\x08 hello"[..];
372 /// assert_eq!(0x0809, buf.get_u16_le());
373 /// ```
374 ///
375 /// # Panics
376 ///
377 /// This function panics if there is not enough remaining data in `self`.
378 fn get_u16_le(&mut self) -> u16 {
379 buf_get_impl!(self, u16::from_le_bytes);
380 }
381
382 /// Gets an unsigned 16 bit integer from `self` in native-endian byte order.
383 ///
384 /// The current position is advanced by 2.
385 ///
386 /// # Examples
387 ///
388 /// ```
389 /// use bytes::Buf;
390 ///
391 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
392 /// true => b"\x08\x09 hello",
393 /// false => b"\x09\x08 hello",
394 /// };
395 /// assert_eq!(0x0809, buf.get_u16_ne());
396 /// ```
397 ///
398 /// # Panics
399 ///
400 /// This function panics if there is not enough remaining data in `self`.
401 fn get_u16_ne(&mut self) -> u16 {
402 buf_get_impl!(self, u16::from_ne_bytes);
403 }
404
405 /// Gets a signed 16 bit integer from `self` in big-endian byte order.
406 ///
407 /// The current position is advanced by 2.
408 ///
409 /// # Examples
410 ///
411 /// ```
412 /// use bytes::Buf;
413 ///
414 /// let mut buf = &b"\x08\x09 hello"[..];
415 /// assert_eq!(0x0809, buf.get_i16());
416 /// ```
417 ///
418 /// # Panics
419 ///
420 /// This function panics if there is not enough remaining data in `self`.
421 fn get_i16(&mut self) -> i16 {
422 buf_get_impl!(self, i16::from_be_bytes);
423 }
424
425 /// Gets a signed 16 bit integer from `self` in little-endian byte order.
426 ///
427 /// The current position is advanced by 2.
428 ///
429 /// # Examples
430 ///
431 /// ```
432 /// use bytes::Buf;
433 ///
434 /// let mut buf = &b"\x09\x08 hello"[..];
435 /// assert_eq!(0x0809, buf.get_i16_le());
436 /// ```
437 ///
438 /// # Panics
439 ///
440 /// This function panics if there is not enough remaining data in `self`.
441 fn get_i16_le(&mut self) -> i16 {
442 buf_get_impl!(self, i16::from_le_bytes);
443 }
444
445 /// Gets a signed 16 bit integer from `self` in native-endian byte order.
446 ///
447 /// The current position is advanced by 2.
448 ///
449 /// # Examples
450 ///
451 /// ```
452 /// use bytes::Buf;
453 ///
454 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
455 /// true => b"\x08\x09 hello",
456 /// false => b"\x09\x08 hello",
457 /// };
458 /// assert_eq!(0x0809, buf.get_i16_ne());
459 /// ```
460 ///
461 /// # Panics
462 ///
463 /// This function panics if there is not enough remaining data in `self`.
464 fn get_i16_ne(&mut self) -> i16 {
465 buf_get_impl!(self, i16::from_ne_bytes);
466 }
467
468 /// Gets an unsigned 32 bit integer from `self` in the big-endian byte order.
469 ///
470 /// The current position is advanced by 4.
471 ///
472 /// # Examples
473 ///
474 /// ```
475 /// use bytes::Buf;
476 ///
477 /// let mut buf = &b"\x08\x09\xA0\xA1 hello"[..];
478 /// assert_eq!(0x0809A0A1, buf.get_u32());
479 /// ```
480 ///
481 /// # Panics
482 ///
483 /// This function panics if there is not enough remaining data in `self`.
484 fn get_u32(&mut self) -> u32 {
485 buf_get_impl!(self, u32::from_be_bytes);
486 }
487
488 /// Gets an unsigned 32 bit integer from `self` in the little-endian byte order.
489 ///
490 /// The current position is advanced by 4.
491 ///
492 /// # Examples
493 ///
494 /// ```
495 /// use bytes::Buf;
496 ///
497 /// let mut buf = &b"\xA1\xA0\x09\x08 hello"[..];
498 /// assert_eq!(0x0809A0A1, buf.get_u32_le());
499 /// ```
500 ///
501 /// # Panics
502 ///
503 /// This function panics if there is not enough remaining data in `self`.
504 fn get_u32_le(&mut self) -> u32 {
505 buf_get_impl!(self, u32::from_le_bytes);
506 }
507
508 /// Gets an unsigned 32 bit integer from `self` in native-endian byte order.
509 ///
510 /// The current position is advanced by 4.
511 ///
512 /// # Examples
513 ///
514 /// ```
515 /// use bytes::Buf;
516 ///
517 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
518 /// true => b"\x08\x09\xA0\xA1 hello",
519 /// false => b"\xA1\xA0\x09\x08 hello",
520 /// };
521 /// assert_eq!(0x0809A0A1, buf.get_u32_ne());
522 /// ```
523 ///
524 /// # Panics
525 ///
526 /// This function panics if there is not enough remaining data in `self`.
527 fn get_u32_ne(&mut self) -> u32 {
528 buf_get_impl!(self, u32::from_ne_bytes);
529 }
530
531 /// Gets a signed 32 bit integer from `self` in big-endian byte order.
532 ///
533 /// The current position is advanced by 4.
534 ///
535 /// # Examples
536 ///
537 /// ```
538 /// use bytes::Buf;
539 ///
540 /// let mut buf = &b"\x08\x09\xA0\xA1 hello"[..];
541 /// assert_eq!(0x0809A0A1, buf.get_i32());
542 /// ```
543 ///
544 /// # Panics
545 ///
546 /// This function panics if there is not enough remaining data in `self`.
547 fn get_i32(&mut self) -> i32 {
548 buf_get_impl!(self, i32::from_be_bytes);
549 }
550
551 /// Gets a signed 32 bit integer from `self` in little-endian byte order.
552 ///
553 /// The current position is advanced by 4.
554 ///
555 /// # Examples
556 ///
557 /// ```
558 /// use bytes::Buf;
559 ///
560 /// let mut buf = &b"\xA1\xA0\x09\x08 hello"[..];
561 /// assert_eq!(0x0809A0A1, buf.get_i32_le());
562 /// ```
563 ///
564 /// # Panics
565 ///
566 /// This function panics if there is not enough remaining data in `self`.
567 fn get_i32_le(&mut self) -> i32 {
568 buf_get_impl!(self, i32::from_le_bytes);
569 }
570
571 /// Gets a signed 32 bit integer from `self` in native-endian byte order.
572 ///
573 /// The current position is advanced by 4.
574 ///
575 /// # Examples
576 ///
577 /// ```
578 /// use bytes::Buf;
579 ///
580 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
581 /// true => b"\x08\x09\xA0\xA1 hello",
582 /// false => b"\xA1\xA0\x09\x08 hello",
583 /// };
584 /// assert_eq!(0x0809A0A1, buf.get_i32_ne());
585 /// ```
586 ///
587 /// # Panics
588 ///
589 /// This function panics if there is not enough remaining data in `self`.
590 fn get_i32_ne(&mut self) -> i32 {
591 buf_get_impl!(self, i32::from_ne_bytes);
592 }
593
594 /// Gets an unsigned 64 bit integer from `self` in big-endian byte order.
595 ///
596 /// The current position is advanced by 8.
597 ///
598 /// # Examples
599 ///
600 /// ```
601 /// use bytes::Buf;
602 ///
603 /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08 hello"[..];
604 /// assert_eq!(0x0102030405060708, buf.get_u64());
605 /// ```
606 ///
607 /// # Panics
608 ///
609 /// This function panics if there is not enough remaining data in `self`.
610 fn get_u64(&mut self) -> u64 {
611 buf_get_impl!(self, u64::from_be_bytes);
612 }
613
614 /// Gets an unsigned 64 bit integer from `self` in little-endian byte order.
615 ///
616 /// The current position is advanced by 8.
617 ///
618 /// # Examples
619 ///
620 /// ```
621 /// use bytes::Buf;
622 ///
623 /// let mut buf = &b"\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
624 /// assert_eq!(0x0102030405060708, buf.get_u64_le());
625 /// ```
626 ///
627 /// # Panics
628 ///
629 /// This function panics if there is not enough remaining data in `self`.
630 fn get_u64_le(&mut self) -> u64 {
631 buf_get_impl!(self, u64::from_le_bytes);
632 }
633
634 /// Gets an unsigned 64 bit integer from `self` in native-endian byte order.
635 ///
636 /// The current position is advanced by 8.
637 ///
638 /// # Examples
639 ///
640 /// ```
641 /// use bytes::Buf;
642 ///
643 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
644 /// true => b"\x01\x02\x03\x04\x05\x06\x07\x08 hello",
645 /// false => b"\x08\x07\x06\x05\x04\x03\x02\x01 hello",
646 /// };
647 /// assert_eq!(0x0102030405060708, buf.get_u64_ne());
648 /// ```
649 ///
650 /// # Panics
651 ///
652 /// This function panics if there is not enough remaining data in `self`.
653 fn get_u64_ne(&mut self) -> u64 {
654 buf_get_impl!(self, u64::from_ne_bytes);
655 }
656
657 /// Gets a signed 64 bit integer from `self` in big-endian byte order.
658 ///
659 /// The current position is advanced by 8.
660 ///
661 /// # Examples
662 ///
663 /// ```
664 /// use bytes::Buf;
665 ///
666 /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08 hello"[..];
667 /// assert_eq!(0x0102030405060708, buf.get_i64());
668 /// ```
669 ///
670 /// # Panics
671 ///
672 /// This function panics if there is not enough remaining data in `self`.
673 fn get_i64(&mut self) -> i64 {
674 buf_get_impl!(self, i64::from_be_bytes);
675 }
676
677 /// Gets a signed 64 bit integer from `self` in little-endian byte order.
678 ///
679 /// The current position is advanced by 8.
680 ///
681 /// # Examples
682 ///
683 /// ```
684 /// use bytes::Buf;
685 ///
686 /// let mut buf = &b"\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
687 /// assert_eq!(0x0102030405060708, buf.get_i64_le());
688 /// ```
689 ///
690 /// # Panics
691 ///
692 /// This function panics if there is not enough remaining data in `self`.
693 fn get_i64_le(&mut self) -> i64 {
694 buf_get_impl!(self, i64::from_le_bytes);
695 }
696
697 /// Gets a signed 64 bit integer from `self` in native-endian byte order.
698 ///
699 /// The current position is advanced by 8.
700 ///
701 /// # Examples
702 ///
703 /// ```
704 /// use bytes::Buf;
705 ///
706 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
707 /// true => b"\x01\x02\x03\x04\x05\x06\x07\x08 hello",
708 /// false => b"\x08\x07\x06\x05\x04\x03\x02\x01 hello",
709 /// };
710 /// assert_eq!(0x0102030405060708, buf.get_i64_ne());
711 /// ```
712 ///
713 /// # Panics
714 ///
715 /// This function panics if there is not enough remaining data in `self`.
716 fn get_i64_ne(&mut self) -> i64 {
717 buf_get_impl!(self, i64::from_ne_bytes);
718 }
719
720 /// Gets an unsigned 128 bit integer from `self` in big-endian byte order.
721 ///
722 /// The current position is advanced by 16.
723 ///
724 /// # Examples
725 ///
726 /// ```
727 /// use bytes::Buf;
728 ///
729 /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello"[..];
730 /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128());
731 /// ```
732 ///
733 /// # Panics
734 ///
735 /// This function panics if there is not enough remaining data in `self`.
736 fn get_u128(&mut self) -> u128 {
737 buf_get_impl!(self, u128::from_be_bytes);
738 }
739
740 /// Gets an unsigned 128 bit integer from `self` in little-endian byte order.
741 ///
742 /// The current position is advanced by 16.
743 ///
744 /// # Examples
745 ///
746 /// ```
747 /// use bytes::Buf;
748 ///
749 /// let mut buf = &b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
750 /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128_le());
751 /// ```
752 ///
753 /// # Panics
754 ///
755 /// This function panics if there is not enough remaining data in `self`.
756 fn get_u128_le(&mut self) -> u128 {
757 buf_get_impl!(self, u128::from_le_bytes);
758 }
759
760 /// Gets an unsigned 128 bit integer from `self` in native-endian byte order.
761 ///
762 /// The current position is advanced by 16.
763 ///
764 /// # Examples
765 ///
766 /// ```
767 /// use bytes::Buf;
768 ///
769 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
770 /// true => b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello",
771 /// false => b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello",
772 /// };
773 /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128_ne());
774 /// ```
775 ///
776 /// # Panics
777 ///
778 /// This function panics if there is not enough remaining data in `self`.
779 fn get_u128_ne(&mut self) -> u128 {
780 buf_get_impl!(self, u128::from_ne_bytes);
781 }
782
783 /// Gets a signed 128 bit integer from `self` in big-endian byte order.
784 ///
785 /// The current position is advanced by 16.
786 ///
787 /// # Examples
788 ///
789 /// ```
790 /// use bytes::Buf;
791 ///
792 /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello"[..];
793 /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128());
794 /// ```
795 ///
796 /// # Panics
797 ///
798 /// This function panics if there is not enough remaining data in `self`.
799 fn get_i128(&mut self) -> i128 {
800 buf_get_impl!(self, i128::from_be_bytes);
801 }
802
803 /// Gets a signed 128 bit integer from `self` in little-endian byte order.
804 ///
805 /// The current position is advanced by 16.
806 ///
807 /// # Examples
808 ///
809 /// ```
810 /// use bytes::Buf;
811 ///
812 /// let mut buf = &b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
813 /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128_le());
814 /// ```
815 ///
816 /// # Panics
817 ///
818 /// This function panics if there is not enough remaining data in `self`.
819 fn get_i128_le(&mut self) -> i128 {
820 buf_get_impl!(self, i128::from_le_bytes);
821 }
822
823 /// Gets a signed 128 bit integer from `self` in native-endian byte order.
824 ///
825 /// The current position is advanced by 16.
826 ///
827 /// # Examples
828 ///
829 /// ```
830 /// use bytes::Buf;
831 ///
832 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
833 /// true => b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello",
834 /// false => b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello",
835 /// };
836 /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128_ne());
837 /// ```
838 ///
839 /// # Panics
840 ///
841 /// This function panics if there is not enough remaining data in `self`.
842 fn get_i128_ne(&mut self) -> i128 {
843 buf_get_impl!(self, i128::from_ne_bytes);
844 }
845
846 /// Gets an unsigned n-byte integer from `self` in big-endian byte order.
847 ///
848 /// The current position is advanced by `nbytes`.
849 ///
850 /// # Examples
851 ///
852 /// ```
853 /// use bytes::Buf;
854 ///
855 /// let mut buf = &b"\x01\x02\x03 hello"[..];
856 /// assert_eq!(0x010203, buf.get_uint(3));
857 /// ```
858 ///
859 /// # Panics
860 ///
861 /// This function panics if there is not enough remaining data in `self`.
862 fn get_uint(&mut self, nbytes: usize) -> u64 {
863 buf_get_impl!(be => self, u64, nbytes);
864 }
865
866 /// Gets an unsigned n-byte integer from `self` in little-endian byte order.
867 ///
868 /// The current position is advanced by `nbytes`.
869 ///
870 /// # Examples
871 ///
872 /// ```
873 /// use bytes::Buf;
874 ///
875 /// let mut buf = &b"\x03\x02\x01 hello"[..];
876 /// assert_eq!(0x010203, buf.get_uint_le(3));
877 /// ```
878 ///
879 /// # Panics
880 ///
881 /// This function panics if there is not enough remaining data in `self`.
882 fn get_uint_le(&mut self, nbytes: usize) -> u64 {
883 buf_get_impl!(le => self, u64, nbytes);
884 }
885
886 /// Gets an unsigned n-byte integer from `self` in native-endian byte order.
887 ///
888 /// The current position is advanced by `nbytes`.
889 ///
890 /// # Examples
891 ///
892 /// ```
893 /// use bytes::Buf;
894 ///
895 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
896 /// true => b"\x01\x02\x03 hello",
897 /// false => b"\x03\x02\x01 hello",
898 /// };
899 /// assert_eq!(0x010203, buf.get_uint_ne(3));
900 /// ```
901 ///
902 /// # Panics
903 ///
904 /// This function panics if there is not enough remaining data in `self`, or
905 /// if `nbytes` is greater than 8.
906 fn get_uint_ne(&mut self, nbytes: usize) -> u64 {
907 if cfg!(target_endian = "big") {
908 self.get_uint(nbytes)
909 } else {
910 self.get_uint_le(nbytes)
911 }
912 }
913
914 /// Gets a signed n-byte integer from `self` in big-endian byte order.
915 ///
916 /// The current position is advanced by `nbytes`.
917 ///
918 /// # Examples
919 ///
920 /// ```
921 /// use bytes::Buf;
922 ///
923 /// let mut buf = &b"\x01\x02\x03 hello"[..];
924 /// assert_eq!(0x010203, buf.get_int(3));
925 /// ```
926 ///
927 /// # Panics
928 ///
929 /// This function panics if there is not enough remaining data in `self`, or
930 /// if `nbytes` is greater than 8.
931 fn get_int(&mut self, nbytes: usize) -> i64 {
932 sign_extend(self.get_uint(nbytes), nbytes)
933 }
934
935 /// Gets a signed n-byte integer from `self` in little-endian byte order.
936 ///
937 /// The current position is advanced by `nbytes`.
938 ///
939 /// # Examples
940 ///
941 /// ```
942 /// use bytes::Buf;
943 ///
944 /// let mut buf = &b"\x03\x02\x01 hello"[..];
945 /// assert_eq!(0x010203, buf.get_int_le(3));
946 /// ```
947 ///
948 /// # Panics
949 ///
950 /// This function panics if there is not enough remaining data in `self`, or
951 /// if `nbytes` is greater than 8.
952 fn get_int_le(&mut self, nbytes: usize) -> i64 {
953 sign_extend(self.get_uint_le(nbytes), nbytes)
954 }
955
956 /// Gets a signed n-byte integer from `self` in native-endian byte order.
957 ///
958 /// The current position is advanced by `nbytes`.
959 ///
960 /// # Examples
961 ///
962 /// ```
963 /// use bytes::Buf;
964 ///
965 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
966 /// true => b"\x01\x02\x03 hello",
967 /// false => b"\x03\x02\x01 hello",
968 /// };
969 /// assert_eq!(0x010203, buf.get_int_ne(3));
970 /// ```
971 ///
972 /// # Panics
973 ///
974 /// This function panics if there is not enough remaining data in `self`, or
975 /// if `nbytes` is greater than 8.
976 fn get_int_ne(&mut self, nbytes: usize) -> i64 {
977 if cfg!(target_endian = "big") {
978 self.get_int(nbytes)
979 } else {
980 self.get_int_le(nbytes)
981 }
982 }
983
984 /// Gets an IEEE754 single-precision (4 bytes) floating point number from
985 /// `self` in big-endian byte order.
986 ///
987 /// The current position is advanced by 4.
988 ///
989 /// # Examples
990 ///
991 /// ```
992 /// use bytes::Buf;
993 ///
994 /// let mut buf = &b"\x3F\x99\x99\x9A hello"[..];
995 /// assert_eq!(1.2f32, buf.get_f32());
996 /// ```
997 ///
998 /// # Panics
999 ///
1000 /// This function panics if there is not enough remaining data in `self`.
1001 fn get_f32(&mut self) -> f32 {
1002 f32::from_bits(self.get_u32())
1003 }
1004
1005 /// Gets an IEEE754 single-precision (4 bytes) floating point number from
1006 /// `self` in little-endian byte order.
1007 ///
1008 /// The current position is advanced by 4.
1009 ///
1010 /// # Examples
1011 ///
1012 /// ```
1013 /// use bytes::Buf;
1014 ///
1015 /// let mut buf = &b"\x9A\x99\x99\x3F hello"[..];
1016 /// assert_eq!(1.2f32, buf.get_f32_le());
1017 /// ```
1018 ///
1019 /// # Panics
1020 ///
1021 /// This function panics if there is not enough remaining data in `self`.
1022 fn get_f32_le(&mut self) -> f32 {
1023 f32::from_bits(self.get_u32_le())
1024 }
1025
1026 /// Gets an IEEE754 single-precision (4 bytes) floating point number from
1027 /// `self` in native-endian byte order.
1028 ///
1029 /// The current position is advanced by 4.
1030 ///
1031 /// # Examples
1032 ///
1033 /// ```
1034 /// use bytes::Buf;
1035 ///
1036 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
1037 /// true => b"\x3F\x99\x99\x9A hello",
1038 /// false => b"\x9A\x99\x99\x3F hello",
1039 /// };
1040 /// assert_eq!(1.2f32, buf.get_f32_ne());
1041 /// ```
1042 ///
1043 /// # Panics
1044 ///
1045 /// This function panics if there is not enough remaining data in `self`.
1046 fn get_f32_ne(&mut self) -> f32 {
1047 f32::from_bits(self.get_u32_ne())
1048 }
1049
1050 /// Gets an IEEE754 double-precision (8 bytes) floating point number from
1051 /// `self` in big-endian byte order.
1052 ///
1053 /// The current position is advanced by 8.
1054 ///
1055 /// # Examples
1056 ///
1057 /// ```
1058 /// use bytes::Buf;
1059 ///
1060 /// let mut buf = &b"\x3F\xF3\x33\x33\x33\x33\x33\x33 hello"[..];
1061 /// assert_eq!(1.2f64, buf.get_f64());
1062 /// ```
1063 ///
1064 /// # Panics
1065 ///
1066 /// This function panics if there is not enough remaining data in `self`.
1067 fn get_f64(&mut self) -> f64 {
1068 f64::from_bits(self.get_u64())
1069 }
1070
1071 /// Gets an IEEE754 double-precision (8 bytes) floating point number from
1072 /// `self` in little-endian byte order.
1073 ///
1074 /// The current position is advanced by 8.
1075 ///
1076 /// # Examples
1077 ///
1078 /// ```
1079 /// use bytes::Buf;
1080 ///
1081 /// let mut buf = &b"\x33\x33\x33\x33\x33\x33\xF3\x3F hello"[..];
1082 /// assert_eq!(1.2f64, buf.get_f64_le());
1083 /// ```
1084 ///
1085 /// # Panics
1086 ///
1087 /// This function panics if there is not enough remaining data in `self`.
1088 fn get_f64_le(&mut self) -> f64 {
1089 f64::from_bits(self.get_u64_le())
1090 }
1091
1092 /// Gets an IEEE754 double-precision (8 bytes) floating point number from
1093 /// `self` in native-endian byte order.
1094 ///
1095 /// The current position is advanced by 8.
1096 ///
1097 /// # Examples
1098 ///
1099 /// ```
1100 /// use bytes::Buf;
1101 ///
1102 /// let mut buf: &[u8] = match cfg!(target_endian = "big") {
1103 /// true => b"\x3F\xF3\x33\x33\x33\x33\x33\x33 hello",
1104 /// false => b"\x33\x33\x33\x33\x33\x33\xF3\x3F hello",
1105 /// };
1106 /// assert_eq!(1.2f64, buf.get_f64_ne());
1107 /// ```
1108 ///
1109 /// # Panics
1110 ///
1111 /// This function panics if there is not enough remaining data in `self`.
1112 fn get_f64_ne(&mut self) -> f64 {
1113 f64::from_bits(self.get_u64_ne())
1114 }
1115
1116 /// Consumes `len` bytes inside self and returns new instance of `Bytes`
1117 /// with this data.
1118 ///
1119 /// This function may be optimized by the underlying type to avoid actual
1120 /// copies. For example, `Bytes` implementation will do a shallow copy
1121 /// (ref-count increment).
1122 ///
1123 /// # Examples
1124 ///
1125 /// ```
1126 /// use bytes::Buf;
1127 ///
1128 /// let bytes = (&b"hello world"[..]).copy_to_bytes(5);
1129 /// assert_eq!(&bytes[..], &b"hello"[..]);
1130 /// ```
1131 ///
1132 /// # Panics
1133 ///
1134 /// This function panics if `len > self.remaining()`.
1135 fn copy_to_bytes(&mut self, len: usize) -> crate::Bytes {
1136 use super::BufMut;
1137
1138 if self.remaining() < len {
1139 panic_advance(len, self.remaining());
1140 }
1141
1142 let mut ret = crate::BytesMut::with_capacity(len);
1143 ret.put(self.take(len));
1144 ret.freeze()
1145 }
1146
1147 /// Creates an adaptor which will read at most `limit` bytes from `self`.
1148 ///
1149 /// This function returns a new instance of `Buf` which will read at most
1150 /// `limit` bytes.
1151 ///
1152 /// # Examples
1153 ///
1154 /// ```
1155 /// use bytes::{Buf, BufMut};
1156 ///
1157 /// let mut buf = b"hello world"[..].take(5);
1158 /// let mut dst = vec![];
1159 ///
1160 /// dst.put(&mut buf);
1161 /// assert_eq!(dst, b"hello");
1162 ///
1163 /// let mut buf = buf.into_inner();
1164 /// dst.clear();
1165 /// dst.put(&mut buf);
1166 /// assert_eq!(dst, b" world");
1167 /// ```
1168 fn take(self, limit: usize) -> Take<Self>
1169 where
1170 Self: Sized,
1171 {
1172 take::new(self, limit)
1173 }
1174
1175 /// Creates an adaptor which will chain this buffer with another.
1176 ///
1177 /// The returned `Buf` instance will first consume all bytes from `self`.
1178 /// Afterwards the output is equivalent to the output of next.
1179 ///
1180 /// # Examples
1181 ///
1182 /// ```
1183 /// use bytes::Buf;
1184 ///
1185 /// let mut chain = b"hello "[..].chain(&b"world"[..]);
1186 ///
1187 /// let full = chain.copy_to_bytes(11);
1188 /// assert_eq!(full.chunk(), b"hello world");
1189 /// ```
1190 fn chain<U: Buf>(self, next: U) -> Chain<Self, U>
1191 where
1192 Self: Sized,
1193 {
1194 Chain::new(self, next)
1195 }
1196
1197 /// Creates an adaptor which implements the `Read` trait for `self`.
1198 ///
1199 /// This function returns a new value which implements `Read` by adapting
1200 /// the `Read` trait functions to the `Buf` trait functions. Given that
1201 /// `Buf` operations are infallible, none of the `Read` functions will
1202 /// return with `Err`.
1203 ///
1204 /// # Examples
1205 ///
1206 /// ```
1207 /// use bytes::{Bytes, Buf};
1208 /// use std::io::Read;
1209 ///
1210 /// let buf = Bytes::from("hello world");
1211 ///
1212 /// let mut reader = buf.reader();
1213 /// let mut dst = [0; 1024];
1214 ///
1215 /// let num = reader.read(&mut dst).unwrap();
1216 ///
1217 /// assert_eq!(11, num);
1218 /// assert_eq!(&dst[..11], &b"hello world"[..]);
1219 /// ```
1220 #[cfg(feature = "std")]
1221 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1222 fn reader(self) -> Reader<Self>
1223 where
1224 Self: Sized,
1225 {
1226 reader::new(self)
1227 }
1228}
1229
1230macro_rules! deref_forward_buf {
1231 () => {
1232 #[inline]
1233 fn remaining(&self) -> usize {
1234 (**self).remaining()
1235 }
1236
1237 #[inline]
1238 fn chunk(&self) -> &[u8] {
1239 (**self).chunk()
1240 }
1241
1242 #[cfg(feature = "std")]
1243 #[inline]
1244 fn chunks_vectored<'b>(&'b self, dst: &mut [IoSlice<'b>]) -> usize {
1245 (**self).chunks_vectored(dst)
1246 }
1247
1248 #[inline]
1249 fn advance(&mut self, cnt: usize) {
1250 (**self).advance(cnt)
1251 }
1252
1253 #[inline]
1254 fn has_remaining(&self) -> bool {
1255 (**self).has_remaining()
1256 }
1257
1258 #[inline]
1259 fn copy_to_slice(&mut self, dst: &mut [u8]) {
1260 (**self).copy_to_slice(dst)
1261 }
1262
1263 #[inline]
1264 fn get_u8(&mut self) -> u8 {
1265 (**self).get_u8()
1266 }
1267
1268 #[inline]
1269 fn get_i8(&mut self) -> i8 {
1270 (**self).get_i8()
1271 }
1272
1273 #[inline]
1274 fn get_u16(&mut self) -> u16 {
1275 (**self).get_u16()
1276 }
1277
1278 #[inline]
1279 fn get_u16_le(&mut self) -> u16 {
1280 (**self).get_u16_le()
1281 }
1282
1283 #[inline]
1284 fn get_u16_ne(&mut self) -> u16 {
1285 (**self).get_u16_ne()
1286 }
1287
1288 #[inline]
1289 fn get_i16(&mut self) -> i16 {
1290 (**self).get_i16()
1291 }
1292
1293 #[inline]
1294 fn get_i16_le(&mut self) -> i16 {
1295 (**self).get_i16_le()
1296 }
1297
1298 #[inline]
1299 fn get_i16_ne(&mut self) -> i16 {
1300 (**self).get_i16_ne()
1301 }
1302
1303 #[inline]
1304 fn get_u32(&mut self) -> u32 {
1305 (**self).get_u32()
1306 }
1307
1308 #[inline]
1309 fn get_u32_le(&mut self) -> u32 {
1310 (**self).get_u32_le()
1311 }
1312
1313 #[inline]
1314 fn get_u32_ne(&mut self) -> u32 {
1315 (**self).get_u32_ne()
1316 }
1317
1318 #[inline]
1319 fn get_i32(&mut self) -> i32 {
1320 (**self).get_i32()
1321 }
1322
1323 #[inline]
1324 fn get_i32_le(&mut self) -> i32 {
1325 (**self).get_i32_le()
1326 }
1327
1328 #[inline]
1329 fn get_i32_ne(&mut self) -> i32 {
1330 (**self).get_i32_ne()
1331 }
1332
1333 #[inline]
1334 fn get_u64(&mut self) -> u64 {
1335 (**self).get_u64()
1336 }
1337
1338 #[inline]
1339 fn get_u64_le(&mut self) -> u64 {
1340 (**self).get_u64_le()
1341 }
1342
1343 #[inline]
1344 fn get_u64_ne(&mut self) -> u64 {
1345 (**self).get_u64_ne()
1346 }
1347
1348 #[inline]
1349 fn get_i64(&mut self) -> i64 {
1350 (**self).get_i64()
1351 }
1352
1353 #[inline]
1354 fn get_i64_le(&mut self) -> i64 {
1355 (**self).get_i64_le()
1356 }
1357
1358 #[inline]
1359 fn get_i64_ne(&mut self) -> i64 {
1360 (**self).get_i64_ne()
1361 }
1362
1363 #[inline]
1364 fn get_uint(&mut self, nbytes: usize) -> u64 {
1365 (**self).get_uint(nbytes)
1366 }
1367
1368 #[inline]
1369 fn get_uint_le(&mut self, nbytes: usize) -> u64 {
1370 (**self).get_uint_le(nbytes)
1371 }
1372
1373 #[inline]
1374 fn get_uint_ne(&mut self, nbytes: usize) -> u64 {
1375 (**self).get_uint_ne(nbytes)
1376 }
1377
1378 #[inline]
1379 fn get_int(&mut self, nbytes: usize) -> i64 {
1380 (**self).get_int(nbytes)
1381 }
1382
1383 #[inline]
1384 fn get_int_le(&mut self, nbytes: usize) -> i64 {
1385 (**self).get_int_le(nbytes)
1386 }
1387
1388 #[inline]
1389 fn get_int_ne(&mut self, nbytes: usize) -> i64 {
1390 (**self).get_int_ne(nbytes)
1391 }
1392
1393 #[inline]
1394 fn copy_to_bytes(&mut self, len: usize) -> crate::Bytes {
1395 (**self).copy_to_bytes(len)
1396 }
1397 };
1398}
1399
1400impl<T: Buf + ?Sized> Buf for &mut T {
1401 deref_forward_buf!();
1402}
1403
1404impl<T: Buf + ?Sized> Buf for Box<T> {
1405 deref_forward_buf!();
1406}
1407
1408impl Buf for &[u8] {
1409 #[inline]
1410 fn remaining(&self) -> usize {
1411 self.len()
1412 }
1413
1414 #[inline]
1415 fn chunk(&self) -> &[u8] {
1416 self
1417 }
1418
1419 #[inline]
1420 fn advance(&mut self, cnt: usize) {
1421 if self.len() < cnt {
1422 panic_advance(cnt, self.len());
1423 }
1424
1425 *self = &self[cnt..];
1426 }
1427
1428 #[inline]
1429 fn copy_to_slice(&mut self, dst: &mut [u8]) {
1430 if self.len() < dst.len() {
1431 panic_advance(dst.len(), self.len());
1432 }
1433
1434 dst.copy_from_slice(&self[..dst.len()]);
1435 self.advance(dst.len());
1436 }
1437}
1438
1439#[cfg(feature = "std")]
1440impl<T: AsRef<[u8]>> Buf for std::io::Cursor<T> {
1441 #[inline]
1442 fn remaining(&self) -> usize {
1443 saturating_sub_usize_u64(self.get_ref().as_ref().len(), self.position())
1444 }
1445
1446 #[inline]
1447 fn chunk(&self) -> &[u8] {
1448 let slice = self.get_ref().as_ref();
1449 let pos = min_u64_usize(self.position(), slice.len());
1450 &slice[pos..]
1451 }
1452
1453 #[inline]
1454 fn advance(&mut self, cnt: usize) {
1455 let len = self.get_ref().as_ref().len();
1456 let pos = self.position();
1457
1458 // We intentionally allow `cnt == 0` here even if `pos > len`.
1459 let max_cnt = saturating_sub_usize_u64(len, pos);
1460 if cnt > max_cnt {
1461 panic_advance(cnt, max_cnt);
1462 }
1463
1464 // This will not overflow because either `cnt == 0` or the sum is not
1465 // greater than `len`.
1466 self.set_position(pos + cnt as u64);
1467 }
1468}
1469
1470// The existence of this function makes the compiler catch if the Buf
1471// trait is "object-safe" or not.
1472fn _assert_trait_object(_b: &dyn Buf) {}