bytes_expand/buf/
buf.rs

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