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