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.
chunk(&self) -> &[u8]130 fn chunk(&self) -> &[u8];
131
132 /// Fills `dst` with potentially multiple slices starting at `self`'s
133 /// current position.
134 ///
135 /// If the `Buf` is backed by disjoint slices of bytes, `chunk_vectored` enables
136 /// fetching more than one slice at once. `dst` is a slice of `IoSlice`
137 /// references, enabling the slice to be directly used with [`writev`]
138 /// without any further conversion. The sum of the lengths of all the
139 /// buffers in `dst` will be less than or equal to `Buf::remaining()`.
140 ///
141 /// The entries in `dst` will be overwritten, but the data **contained** by
142 /// the slices **will not** be modified. If `chunk_vectored` does not fill every
143 /// entry in `dst`, then `dst` is guaranteed to contain all remaining slices
144 /// in `self.
145 ///
146 /// This is a lower level function. Most operations are done with other
147 /// functions.
148 ///
149 /// # Implementer notes
150 ///
151 /// This function should never panic. Once the end of the buffer is reached,
152 /// i.e., `Buf::remaining` returns 0, calls to `chunk_vectored` must return 0
153 /// without mutating `dst`.
154 ///
155 /// Implementations should also take care to properly handle being called
156 /// with `dst` being a zero length slice.
157 ///
158 /// [`writev`]: http://man7.org/linux/man-pages/man2/readv.2.html
159 #[cfg(feature = "std")]
chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize160 fn chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize {
161 if dst.is_empty() {
162 return 0;
163 }
164
165 if self.has_remaining() {
166 dst[0] = IoSlice::new(self.chunk());
167 1
168 } else {
169 0
170 }
171 }
172
173 /// Advance the internal cursor of the Buf
174 ///
175 /// The next call to `chunk()` will return a slice starting `cnt` bytes
176 /// further into the underlying buffer.
177 ///
178 /// # Examples
179 ///
180 /// ```
181 /// use bytes::Buf;
182 ///
183 /// let mut buf = &b"hello world"[..];
184 ///
185 /// assert_eq!(buf.chunk(), &b"hello world"[..]);
186 ///
187 /// buf.advance(6);
188 ///
189 /// assert_eq!(buf.chunk(), &b"world"[..]);
190 /// ```
191 ///
192 /// # Panics
193 ///
194 /// This function **may** panic if `cnt > self.remaining()`.
195 ///
196 /// # Implementer notes
197 ///
198 /// It is recommended for implementations of `advance` to panic if `cnt >
199 /// self.remaining()`. If the implementation does not panic, the call must
200 /// behave as if `cnt == self.remaining()`.
201 ///
202 /// A call with `cnt == 0` should never panic and be a no-op.
advance(&mut self, cnt: usize)203 fn advance(&mut self, cnt: usize);
204
205 /// Returns true if there are any more bytes to consume
206 ///
207 /// This is equivalent to `self.remaining() != 0`.
208 ///
209 /// # Examples
210 ///
211 /// ```
212 /// use bytes::Buf;
213 ///
214 /// let mut buf = &b"a"[..];
215 ///
216 /// assert!(buf.has_remaining());
217 ///
218 /// buf.get_u8();
219 ///
220 /// assert!(!buf.has_remaining());
221 /// ```
has_remaining(&self) -> bool222 fn has_remaining(&self) -> bool {
223 self.remaining() > 0
224 }
225
226 /// Copies bytes from `self` into `dst`.
227 ///
228 /// The cursor is advanced by the number of bytes copied. `self` must have
229 /// enough remaining bytes to fill `dst`.
230 ///
231 /// # Examples
232 ///
233 /// ```
234 /// use bytes::Buf;
235 ///
236 /// let mut buf = &b"hello world"[..];
237 /// let mut dst = [0; 5];
238 ///
239 /// buf.copy_to_slice(&mut dst);
240 /// assert_eq!(&b"hello"[..], &dst);
241 /// assert_eq!(6, buf.remaining());
242 /// ```
243 ///
244 /// # Panics
245 ///
246 /// This function panics if `self.remaining() < dst.len()`
copy_to_slice(&mut self, dst: &mut [u8])247 fn copy_to_slice(&mut self, dst: &mut [u8]) {
248 let mut off = 0;
249
250 assert!(self.remaining() >= dst.len());
251
252 while off < dst.len() {
253 let cnt;
254
255 unsafe {
256 let src = self.chunk();
257 cnt = cmp::min(src.len(), dst.len() - off);
258
259 ptr::copy_nonoverlapping(src.as_ptr(), dst[off..].as_mut_ptr(), cnt);
260
261 off += cnt;
262 }
263
264 self.advance(cnt);
265 }
266 }
267
268 /// Gets an unsigned 8 bit integer from `self`.
269 ///
270 /// The current position is advanced by 1.
271 ///
272 /// # Examples
273 ///
274 /// ```
275 /// use bytes::Buf;
276 ///
277 /// let mut buf = &b"\x08 hello"[..];
278 /// assert_eq!(8, buf.get_u8());
279 /// ```
280 ///
281 /// # Panics
282 ///
283 /// This function panics if there is no more remaining data in `self`.
get_u8(&mut self) -> u8284 fn get_u8(&mut self) -> u8 {
285 assert!(self.remaining() >= 1);
286 let ret = self.chunk()[0];
287 self.advance(1);
288 ret
289 }
290
291 /// Gets a signed 8 bit integer from `self`.
292 ///
293 /// The current position is advanced by 1.
294 ///
295 /// # Examples
296 ///
297 /// ```
298 /// use bytes::Buf;
299 ///
300 /// let mut buf = &b"\x08 hello"[..];
301 /// assert_eq!(8, buf.get_i8());
302 /// ```
303 ///
304 /// # Panics
305 ///
306 /// This function panics if there is no more remaining data in `self`.
get_i8(&mut self) -> i8307 fn get_i8(&mut self) -> i8 {
308 assert!(self.remaining() >= 1);
309 let ret = self.chunk()[0] as i8;
310 self.advance(1);
311 ret
312 }
313
314 /// Gets an unsigned 16 bit integer from `self` in big-endian byte order.
315 ///
316 /// The current position is advanced by 2.
317 ///
318 /// # Examples
319 ///
320 /// ```
321 /// use bytes::Buf;
322 ///
323 /// let mut buf = &b"\x08\x09 hello"[..];
324 /// assert_eq!(0x0809, buf.get_u16());
325 /// ```
326 ///
327 /// # Panics
328 ///
329 /// This function panics if there is not enough remaining data in `self`.
get_u16(&mut self) -> u16330 fn get_u16(&mut self) -> u16 {
331 buf_get_impl!(self, u16::from_be_bytes);
332 }
333
334 /// Gets an unsigned 16 bit integer from `self` in little-endian byte order.
335 ///
336 /// The current position is advanced by 2.
337 ///
338 /// # Examples
339 ///
340 /// ```
341 /// use bytes::Buf;
342 ///
343 /// let mut buf = &b"\x09\x08 hello"[..];
344 /// assert_eq!(0x0809, buf.get_u16_le());
345 /// ```
346 ///
347 /// # Panics
348 ///
349 /// This function panics if there is not enough remaining data in `self`.
get_u16_le(&mut self) -> u16350 fn get_u16_le(&mut self) -> u16 {
351 buf_get_impl!(self, u16::from_le_bytes);
352 }
353
354 /// Gets a signed 16 bit integer from `self` in big-endian byte order.
355 ///
356 /// The current position is advanced by 2.
357 ///
358 /// # Examples
359 ///
360 /// ```
361 /// use bytes::Buf;
362 ///
363 /// let mut buf = &b"\x08\x09 hello"[..];
364 /// assert_eq!(0x0809, buf.get_i16());
365 /// ```
366 ///
367 /// # Panics
368 ///
369 /// This function panics if there is not enough remaining data in `self`.
get_i16(&mut self) -> i16370 fn get_i16(&mut self) -> i16 {
371 buf_get_impl!(self, i16::from_be_bytes);
372 }
373
374 /// Gets a signed 16 bit integer from `self` in little-endian byte order.
375 ///
376 /// The current position is advanced by 2.
377 ///
378 /// # Examples
379 ///
380 /// ```
381 /// use bytes::Buf;
382 ///
383 /// let mut buf = &b"\x09\x08 hello"[..];
384 /// assert_eq!(0x0809, buf.get_i16_le());
385 /// ```
386 ///
387 /// # Panics
388 ///
389 /// This function panics if there is not enough remaining data in `self`.
get_i16_le(&mut self) -> i16390 fn get_i16_le(&mut self) -> i16 {
391 buf_get_impl!(self, i16::from_le_bytes);
392 }
393
394 /// Gets an unsigned 32 bit integer from `self` in the big-endian byte order.
395 ///
396 /// The current position is advanced by 4.
397 ///
398 /// # Examples
399 ///
400 /// ```
401 /// use bytes::Buf;
402 ///
403 /// let mut buf = &b"\x08\x09\xA0\xA1 hello"[..];
404 /// assert_eq!(0x0809A0A1, buf.get_u32());
405 /// ```
406 ///
407 /// # Panics
408 ///
409 /// This function panics if there is not enough remaining data in `self`.
get_u32(&mut self) -> u32410 fn get_u32(&mut self) -> u32 {
411 buf_get_impl!(self, u32::from_be_bytes);
412 }
413
414 /// Gets an unsigned 32 bit integer from `self` in the little-endian byte order.
415 ///
416 /// The current position is advanced by 4.
417 ///
418 /// # Examples
419 ///
420 /// ```
421 /// use bytes::Buf;
422 ///
423 /// let mut buf = &b"\xA1\xA0\x09\x08 hello"[..];
424 /// assert_eq!(0x0809A0A1, buf.get_u32_le());
425 /// ```
426 ///
427 /// # Panics
428 ///
429 /// This function panics if there is not enough remaining data in `self`.
get_u32_le(&mut self) -> u32430 fn get_u32_le(&mut self) -> u32 {
431 buf_get_impl!(self, u32::from_le_bytes);
432 }
433
434 /// Gets a signed 32 bit integer from `self` in big-endian byte order.
435 ///
436 /// The current position is advanced by 4.
437 ///
438 /// # Examples
439 ///
440 /// ```
441 /// use bytes::Buf;
442 ///
443 /// let mut buf = &b"\x08\x09\xA0\xA1 hello"[..];
444 /// assert_eq!(0x0809A0A1, buf.get_i32());
445 /// ```
446 ///
447 /// # Panics
448 ///
449 /// This function panics if there is not enough remaining data in `self`.
get_i32(&mut self) -> i32450 fn get_i32(&mut self) -> i32 {
451 buf_get_impl!(self, i32::from_be_bytes);
452 }
453
454 /// Gets a signed 32 bit integer from `self` in little-endian byte order.
455 ///
456 /// The current position is advanced by 4.
457 ///
458 /// # Examples
459 ///
460 /// ```
461 /// use bytes::Buf;
462 ///
463 /// let mut buf = &b"\xA1\xA0\x09\x08 hello"[..];
464 /// assert_eq!(0x0809A0A1, buf.get_i32_le());
465 /// ```
466 ///
467 /// # Panics
468 ///
469 /// This function panics if there is not enough remaining data in `self`.
get_i32_le(&mut self) -> i32470 fn get_i32_le(&mut self) -> i32 {
471 buf_get_impl!(self, i32::from_le_bytes);
472 }
473
474 /// Gets an unsigned 64 bit integer from `self` in big-endian byte order.
475 ///
476 /// The current position is advanced by 8.
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use bytes::Buf;
482 ///
483 /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08 hello"[..];
484 /// assert_eq!(0x0102030405060708, buf.get_u64());
485 /// ```
486 ///
487 /// # Panics
488 ///
489 /// This function panics if there is not enough remaining data in `self`.
get_u64(&mut self) -> u64490 fn get_u64(&mut self) -> u64 {
491 buf_get_impl!(self, u64::from_be_bytes);
492 }
493
494 /// Gets an unsigned 64 bit integer from `self` in little-endian byte order.
495 ///
496 /// The current position is advanced by 8.
497 ///
498 /// # Examples
499 ///
500 /// ```
501 /// use bytes::Buf;
502 ///
503 /// let mut buf = &b"\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
504 /// assert_eq!(0x0102030405060708, buf.get_u64_le());
505 /// ```
506 ///
507 /// # Panics
508 ///
509 /// This function panics if there is not enough remaining data in `self`.
get_u64_le(&mut self) -> u64510 fn get_u64_le(&mut self) -> u64 {
511 buf_get_impl!(self, u64::from_le_bytes);
512 }
513
514 /// Gets a signed 64 bit integer from `self` in big-endian byte order.
515 ///
516 /// The current position is advanced by 8.
517 ///
518 /// # Examples
519 ///
520 /// ```
521 /// use bytes::Buf;
522 ///
523 /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08 hello"[..];
524 /// assert_eq!(0x0102030405060708, buf.get_i64());
525 /// ```
526 ///
527 /// # Panics
528 ///
529 /// This function panics if there is not enough remaining data in `self`.
get_i64(&mut self) -> i64530 fn get_i64(&mut self) -> i64 {
531 buf_get_impl!(self, i64::from_be_bytes);
532 }
533
534 /// Gets a signed 64 bit integer from `self` in little-endian byte order.
535 ///
536 /// The current position is advanced by 8.
537 ///
538 /// # Examples
539 ///
540 /// ```
541 /// use bytes::Buf;
542 ///
543 /// let mut buf = &b"\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
544 /// assert_eq!(0x0102030405060708, buf.get_i64_le());
545 /// ```
546 ///
547 /// # Panics
548 ///
549 /// This function panics if there is not enough remaining data in `self`.
get_i64_le(&mut self) -> i64550 fn get_i64_le(&mut self) -> i64 {
551 buf_get_impl!(self, i64::from_le_bytes);
552 }
553
554 /// Gets an unsigned 128 bit integer from `self` in big-endian byte order.
555 ///
556 /// The current position is advanced by 16.
557 ///
558 /// # Examples
559 ///
560 /// ```
561 /// use bytes::Buf;
562 ///
563 /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello"[..];
564 /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128());
565 /// ```
566 ///
567 /// # Panics
568 ///
569 /// This function panics if there is not enough remaining data in `self`.
get_u128(&mut self) -> u128570 fn get_u128(&mut self) -> u128 {
571 buf_get_impl!(self, u128::from_be_bytes);
572 }
573
574 /// Gets an unsigned 128 bit integer from `self` in little-endian byte order.
575 ///
576 /// The current position is advanced by 16.
577 ///
578 /// # Examples
579 ///
580 /// ```
581 /// use bytes::Buf;
582 ///
583 /// let mut buf = &b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
584 /// assert_eq!(0x01020304050607080910111213141516, buf.get_u128_le());
585 /// ```
586 ///
587 /// # Panics
588 ///
589 /// This function panics if there is not enough remaining data in `self`.
get_u128_le(&mut self) -> u128590 fn get_u128_le(&mut self) -> u128 {
591 buf_get_impl!(self, u128::from_le_bytes);
592 }
593
594 /// Gets a signed 128 bit integer from `self` in big-endian byte order.
595 ///
596 /// The current position is advanced by 16.
597 ///
598 /// # Examples
599 ///
600 /// ```
601 /// use bytes::Buf;
602 ///
603 /// let mut buf = &b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16 hello"[..];
604 /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128());
605 /// ```
606 ///
607 /// # Panics
608 ///
609 /// This function panics if there is not enough remaining data in `self`.
get_i128(&mut self) -> i128610 fn get_i128(&mut self) -> i128 {
611 buf_get_impl!(self, i128::from_be_bytes);
612 }
613
614 /// Gets a signed 128 bit integer from `self` in little-endian byte order.
615 ///
616 /// The current position is advanced by 16.
617 ///
618 /// # Examples
619 ///
620 /// ```
621 /// use bytes::Buf;
622 ///
623 /// let mut buf = &b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01 hello"[..];
624 /// assert_eq!(0x01020304050607080910111213141516, buf.get_i128_le());
625 /// ```
626 ///
627 /// # Panics
628 ///
629 /// This function panics if there is not enough remaining data in `self`.
get_i128_le(&mut self) -> i128630 fn get_i128_le(&mut self) -> i128 {
631 buf_get_impl!(self, i128::from_le_bytes);
632 }
633
634 /// Gets an unsigned n-byte integer from `self` in big-endian byte order.
635 ///
636 /// The current position is advanced by `nbytes`.
637 ///
638 /// # Examples
639 ///
640 /// ```
641 /// use bytes::Buf;
642 ///
643 /// let mut buf = &b"\x01\x02\x03 hello"[..];
644 /// assert_eq!(0x010203, buf.get_uint(3));
645 /// ```
646 ///
647 /// # Panics
648 ///
649 /// This function panics if there is not enough remaining data in `self`.
get_uint(&mut self, nbytes: usize) -> u64650 fn get_uint(&mut self, nbytes: usize) -> u64 {
651 buf_get_impl!(be => self, u64, nbytes);
652 }
653
654 /// Gets an unsigned n-byte integer from `self` in little-endian byte order.
655 ///
656 /// The current position is advanced by `nbytes`.
657 ///
658 /// # Examples
659 ///
660 /// ```
661 /// use bytes::Buf;
662 ///
663 /// let mut buf = &b"\x03\x02\x01 hello"[..];
664 /// assert_eq!(0x010203, buf.get_uint_le(3));
665 /// ```
666 ///
667 /// # Panics
668 ///
669 /// This function panics if there is not enough remaining data in `self`.
get_uint_le(&mut self, nbytes: usize) -> u64670 fn get_uint_le(&mut self, nbytes: usize) -> u64 {
671 buf_get_impl!(le => self, u64, nbytes);
672 }
673
674 /// Gets a signed n-byte integer from `self` in big-endian byte order.
675 ///
676 /// The current position is advanced by `nbytes`.
677 ///
678 /// # Examples
679 ///
680 /// ```
681 /// use bytes::Buf;
682 ///
683 /// let mut buf = &b"\x01\x02\x03 hello"[..];
684 /// assert_eq!(0x010203, buf.get_int(3));
685 /// ```
686 ///
687 /// # Panics
688 ///
689 /// This function panics if there is not enough remaining data in `self`.
get_int(&mut self, nbytes: usize) -> i64690 fn get_int(&mut self, nbytes: usize) -> i64 {
691 buf_get_impl!(be => self, i64, nbytes);
692 }
693
694 /// Gets a signed n-byte integer from `self` in little-endian byte order.
695 ///
696 /// The current position is advanced by `nbytes`.
697 ///
698 /// # Examples
699 ///
700 /// ```
701 /// use bytes::Buf;
702 ///
703 /// let mut buf = &b"\x03\x02\x01 hello"[..];
704 /// assert_eq!(0x010203, buf.get_int_le(3));
705 /// ```
706 ///
707 /// # Panics
708 ///
709 /// This function panics if there is not enough remaining data in `self`.
get_int_le(&mut self, nbytes: usize) -> i64710 fn get_int_le(&mut self, nbytes: usize) -> i64 {
711 buf_get_impl!(le => self, i64, nbytes);
712 }
713
714 /// Gets an IEEE754 single-precision (4 bytes) floating point number from
715 /// `self` in big-endian byte order.
716 ///
717 /// The current position is advanced by 4.
718 ///
719 /// # Examples
720 ///
721 /// ```
722 /// use bytes::Buf;
723 ///
724 /// let mut buf = &b"\x3F\x99\x99\x9A hello"[..];
725 /// assert_eq!(1.2f32, buf.get_f32());
726 /// ```
727 ///
728 /// # Panics
729 ///
730 /// This function panics if there is not enough remaining data in `self`.
get_f32(&mut self) -> f32731 fn get_f32(&mut self) -> f32 {
732 f32::from_bits(Self::get_u32(self))
733 }
734
735 /// Gets an IEEE754 single-precision (4 bytes) floating point number from
736 /// `self` in little-endian byte order.
737 ///
738 /// The current position is advanced by 4.
739 ///
740 /// # Examples
741 ///
742 /// ```
743 /// use bytes::Buf;
744 ///
745 /// let mut buf = &b"\x9A\x99\x99\x3F hello"[..];
746 /// assert_eq!(1.2f32, buf.get_f32_le());
747 /// ```
748 ///
749 /// # Panics
750 ///
751 /// This function panics if there is not enough remaining data in `self`.
get_f32_le(&mut self) -> f32752 fn get_f32_le(&mut self) -> f32 {
753 f32::from_bits(Self::get_u32_le(self))
754 }
755
756 /// Gets an IEEE754 double-precision (8 bytes) floating point number from
757 /// `self` in big-endian byte order.
758 ///
759 /// The current position is advanced by 8.
760 ///
761 /// # Examples
762 ///
763 /// ```
764 /// use bytes::Buf;
765 ///
766 /// let mut buf = &b"\x3F\xF3\x33\x33\x33\x33\x33\x33 hello"[..];
767 /// assert_eq!(1.2f64, buf.get_f64());
768 /// ```
769 ///
770 /// # Panics
771 ///
772 /// This function panics if there is not enough remaining data in `self`.
get_f64(&mut self) -> f64773 fn get_f64(&mut self) -> f64 {
774 f64::from_bits(Self::get_u64(self))
775 }
776
777 /// Gets an IEEE754 double-precision (8 bytes) floating point number from
778 /// `self` in little-endian byte order.
779 ///
780 /// The current position is advanced by 8.
781 ///
782 /// # Examples
783 ///
784 /// ```
785 /// use bytes::Buf;
786 ///
787 /// let mut buf = &b"\x33\x33\x33\x33\x33\x33\xF3\x3F hello"[..];
788 /// assert_eq!(1.2f64, buf.get_f64_le());
789 /// ```
790 ///
791 /// # Panics
792 ///
793 /// This function panics if there is not enough remaining data in `self`.
get_f64_le(&mut self) -> f64794 fn get_f64_le(&mut self) -> f64 {
795 f64::from_bits(Self::get_u64_le(self))
796 }
797
798 /// Consumes `len` bytes inside self and returns new instance of `Bytes`
799 /// with this data.
800 ///
801 /// This function may be optimized by the underlying type to avoid actual
802 /// copies. For example, `Bytes` implementation will do a shallow copy
803 /// (ref-count increment).
804 ///
805 /// # Examples
806 ///
807 /// ```
808 /// use bytes::Buf;
809 ///
810 /// let bytes = (&b"hello world"[..]).copy_to_bytes(5);
811 /// assert_eq!(&bytes[..], &b"hello"[..]);
812 /// ```
copy_to_bytes(&mut self, len: usize) -> crate::Bytes813 fn copy_to_bytes(&mut self, len: usize) -> crate::Bytes {
814 use super::BufMut;
815
816 assert!(len <= self.remaining(), "`len` greater than remaining");
817
818 let mut ret = crate::BytesMut::with_capacity(len);
819 ret.put(self.take(len));
820 ret.freeze()
821 }
822
823 /// Creates an adaptor which will read at most `limit` bytes from `self`.
824 ///
825 /// This function returns a new instance of `Buf` which will read at most
826 /// `limit` bytes.
827 ///
828 /// # Examples
829 ///
830 /// ```
831 /// use bytes::{Buf, BufMut};
832 ///
833 /// let mut buf = b"hello world"[..].take(5);
834 /// let mut dst = vec![];
835 ///
836 /// dst.put(&mut buf);
837 /// assert_eq!(dst, b"hello");
838 ///
839 /// let mut buf = buf.into_inner();
840 /// dst.clear();
841 /// dst.put(&mut buf);
842 /// assert_eq!(dst, b" world");
843 /// ```
take(self, limit: usize) -> Take<Self> where Self: Sized,844 fn take(self, limit: usize) -> Take<Self>
845 where
846 Self: Sized,
847 {
848 take::new(self, limit)
849 }
850
851 /// Creates an adaptor which will chain this buffer with another.
852 ///
853 /// The returned `Buf` instance will first consume all bytes from `self`.
854 /// Afterwards the output is equivalent to the output of next.
855 ///
856 /// # Examples
857 ///
858 /// ```
859 /// use bytes::Buf;
860 ///
861 /// let mut chain = b"hello "[..].chain(&b"world"[..]);
862 ///
863 /// let full = chain.copy_to_bytes(11);
864 /// assert_eq!(full.chunk(), b"hello world");
865 /// ```
chain<U: Buf>(self, next: U) -> Chain<Self, U> where Self: Sized,866 fn chain<U: Buf>(self, next: U) -> Chain<Self, U>
867 where
868 Self: Sized,
869 {
870 Chain::new(self, next)
871 }
872
873 /// Creates an adaptor which implements the `Read` trait for `self`.
874 ///
875 /// This function returns a new value which implements `Read` by adapting
876 /// the `Read` trait functions to the `Buf` trait functions. Given that
877 /// `Buf` operations are infallible, none of the `Read` functions will
878 /// return with `Err`.
879 ///
880 /// # Examples
881 ///
882 /// ```
883 /// use bytes::{Bytes, Buf};
884 /// use std::io::Read;
885 ///
886 /// let buf = Bytes::from("hello world");
887 ///
888 /// let mut reader = buf.reader();
889 /// let mut dst = [0; 1024];
890 ///
891 /// let num = reader.read(&mut dst).unwrap();
892 ///
893 /// assert_eq!(11, num);
894 /// assert_eq!(&dst[..11], &b"hello world"[..]);
895 /// ```
896 #[cfg(feature = "std")]
reader(self) -> Reader<Self> where Self: Sized,897 fn reader(self) -> Reader<Self>
898 where
899 Self: Sized,
900 {
901 reader::new(self)
902 }
903 }
904
905 macro_rules! deref_forward_buf {
906 () => {
907 fn remaining(&self) -> usize {
908 (**self).remaining()
909 }
910
911 fn chunk(&self) -> &[u8] {
912 (**self).chunk()
913 }
914
915 #[cfg(feature = "std")]
916 fn chunks_vectored<'b>(&'b self, dst: &mut [IoSlice<'b>]) -> usize {
917 (**self).chunks_vectored(dst)
918 }
919
920 fn advance(&mut self, cnt: usize) {
921 (**self).advance(cnt)
922 }
923
924 fn has_remaining(&self) -> bool {
925 (**self).has_remaining()
926 }
927
928 fn copy_to_slice(&mut self, dst: &mut [u8]) {
929 (**self).copy_to_slice(dst)
930 }
931
932 fn get_u8(&mut self) -> u8 {
933 (**self).get_u8()
934 }
935
936 fn get_i8(&mut self) -> i8 {
937 (**self).get_i8()
938 }
939
940 fn get_u16(&mut self) -> u16 {
941 (**self).get_u16()
942 }
943
944 fn get_u16_le(&mut self) -> u16 {
945 (**self).get_u16_le()
946 }
947
948 fn get_i16(&mut self) -> i16 {
949 (**self).get_i16()
950 }
951
952 fn get_i16_le(&mut self) -> i16 {
953 (**self).get_i16_le()
954 }
955
956 fn get_u32(&mut self) -> u32 {
957 (**self).get_u32()
958 }
959
960 fn get_u32_le(&mut self) -> u32 {
961 (**self).get_u32_le()
962 }
963
964 fn get_i32(&mut self) -> i32 {
965 (**self).get_i32()
966 }
967
968 fn get_i32_le(&mut self) -> i32 {
969 (**self).get_i32_le()
970 }
971
972 fn get_u64(&mut self) -> u64 {
973 (**self).get_u64()
974 }
975
976 fn get_u64_le(&mut self) -> u64 {
977 (**self).get_u64_le()
978 }
979
980 fn get_i64(&mut self) -> i64 {
981 (**self).get_i64()
982 }
983
984 fn get_i64_le(&mut self) -> i64 {
985 (**self).get_i64_le()
986 }
987
988 fn get_uint(&mut self, nbytes: usize) -> u64 {
989 (**self).get_uint(nbytes)
990 }
991
992 fn get_uint_le(&mut self, nbytes: usize) -> u64 {
993 (**self).get_uint_le(nbytes)
994 }
995
996 fn get_int(&mut self, nbytes: usize) -> i64 {
997 (**self).get_int(nbytes)
998 }
999
1000 fn get_int_le(&mut self, nbytes: usize) -> i64 {
1001 (**self).get_int_le(nbytes)
1002 }
1003
1004 fn copy_to_bytes(&mut self, len: usize) -> crate::Bytes {
1005 (**self).copy_to_bytes(len)
1006 }
1007 };
1008 }
1009
1010 impl<T: Buf + ?Sized> Buf for &mut T {
1011 deref_forward_buf!();
1012 }
1013
1014 impl<T: Buf + ?Sized> Buf for Box<T> {
1015 deref_forward_buf!();
1016 }
1017
1018 impl Buf for &[u8] {
1019 #[inline]
remaining(&self) -> usize1020 fn remaining(&self) -> usize {
1021 self.len()
1022 }
1023
1024 #[inline]
chunk(&self) -> &[u8]1025 fn chunk(&self) -> &[u8] {
1026 self
1027 }
1028
1029 #[inline]
advance(&mut self, cnt: usize)1030 fn advance(&mut self, cnt: usize) {
1031 *self = &self[cnt..];
1032 }
1033 }
1034
1035 #[cfg(feature = "std")]
1036 impl<T: AsRef<[u8]>> Buf for std::io::Cursor<T> {
remaining(&self) -> usize1037 fn remaining(&self) -> usize {
1038 let len = self.get_ref().as_ref().len();
1039 let pos = self.position();
1040
1041 if pos >= len as u64 {
1042 return 0;
1043 }
1044
1045 len - pos as usize
1046 }
1047
chunk(&self) -> &[u8]1048 fn chunk(&self) -> &[u8] {
1049 let len = self.get_ref().as_ref().len();
1050 let pos = self.position();
1051
1052 if pos >= len as u64 {
1053 return &[];
1054 }
1055
1056 &self.get_ref().as_ref()[pos as usize..]
1057 }
1058
advance(&mut self, cnt: usize)1059 fn advance(&mut self, cnt: usize) {
1060 let pos = (self.position() as usize)
1061 .checked_add(cnt)
1062 .expect("overflow");
1063
1064 assert!(pos <= self.get_ref().as_ref().len());
1065 self.set_position(pos as u64);
1066 }
1067 }
1068
1069 // The existence of this function makes the compiler catch if the Buf
1070 // trait is "object-safe" or not.
_assert_trait_object(_b: &dyn Buf)1071 fn _assert_trait_object(_b: &dyn Buf) {}
1072