Skip to main content

ntex_bytes/buf/
buf_impl.rs

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