Skip to main content

ntex_bytes/buf/
buf_mut.rs

1use std::{cmp, mem, ptr};
2
3use super::{UninitSlice, Writer};
4
5/// A trait for values that provide sequential write access to bytes.
6///
7/// Write bytes to a buffer
8///
9/// A buffer stores bytes in memory such that write operations are infallible.
10/// The underlying storage may or may not be in contiguous memory. A `BufMut`
11/// value is a cursor into the buffer. Writing to `BufMut` advances the cursor
12/// position.
13///
14/// The simplest `BufMut` is a `Vec<u8>`.
15///
16/// ```
17/// use ntex_bytes::BufMut;
18///
19/// let mut buf = vec![];
20///
21/// buf.put("hello world");
22///
23/// assert_eq!(buf, b"hello world");
24/// ```
25pub trait BufMut {
26    /// Returns the number of bytes that can be written from the current
27    /// position until the end of the buffer is reached.
28    ///
29    /// This value is greater than or equal to the length of the slice returned
30    /// by `chunk_mut`.
31    ///
32    /// # Examples
33    ///
34    /// ```
35    /// use ntex_bytes::BufMut;
36    ///
37    /// let mut dst = [0; 10];
38    /// let mut buf = &mut dst[..];
39    ///
40    /// let original_remaining = buf.remaining_mut();
41    /// buf.put("hello");
42    ///
43    /// assert_eq!(original_remaining - 5, buf.remaining_mut());
44    /// ```
45    ///
46    /// # Implementer notes
47    ///
48    /// Implementations of `remaining_mut` should ensure that the return value
49    /// does not change unless a call is made to `advance_mut` or any other
50    /// function that is documented to change the `BufMut`'s current position.
51    fn remaining_mut(&self) -> usize;
52
53    /// Advance the internal cursor of the `BufMut`
54    ///
55    /// The next call to `bytes_mut` will return a slice starting `cnt` bytes
56    /// further into the underlying buffer.
57    ///
58    /// This function is unsafe because there is no guarantee that the bytes
59    /// being advanced past have been initialized.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use ntex_bytes::BufMut;
65    ///
66    /// let mut buf = Vec::with_capacity(16);
67    ///
68    /// unsafe {
69    ///     buf.chunk_mut()[0..2].copy_from_slice(b"he");
70    ///     buf.advance_mut(2);
71    ///
72    ///     buf.chunk_mut()[0..3].copy_from_slice(b"llo");
73    ///     buf.advance_mut(3);
74    /// }
75    ///
76    /// assert_eq!(5, buf.len());
77    /// assert_eq!(buf, b"hello");
78    /// ```
79    ///
80    /// # Panics
81    ///
82    /// This function **may** panic if `cnt > self.remaining_mut()`.
83    ///
84    /// # Implementer notes
85    ///
86    /// It is recommended for implementations of `advance_mut` to panic if
87    /// `cnt > self.remaining_mut()`. If the implementation does not panic,
88    /// the call must behave as if `cnt == self.remaining_mut()`.
89    ///
90    /// A call with `cnt == 0` should never panic and be a no-op.
91    #[allow(clippy::missing_safety_doc)]
92    unsafe fn advance_mut(&mut self, cnt: usize);
93
94    /// Returns true if there is space in `self` for more bytes.
95    ///
96    /// This is equivalent to `self.remaining_mut() != 0`.
97    ///
98    /// # Examples
99    ///
100    /// ```
101    /// use ntex_bytes::BufMut;
102    ///
103    /// let mut dst = [0; 5];
104    /// let mut buf = &mut dst[..];
105    ///
106    /// assert!(buf.has_remaining_mut());
107    ///
108    /// buf.put("hello");
109    ///
110    /// assert!(!buf.has_remaining_mut());
111    /// ```
112    #[inline]
113    fn has_remaining_mut(&self) -> bool {
114        self.remaining_mut() > 0
115    }
116
117    /// Returns a mutable slice starting at the current `BufMut` position and of
118    /// length between 0 and `BufMut::remaining_mut()`. Note that this *can* be shorter than the
119    /// whole remainder of the buffer (this allows non-continuous implementation).
120    ///
121    /// This is a lower level function. Most operations are done with other
122    /// functions.
123    ///
124    /// The returned byte slice may represent uninitialized memory.
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// use ntex_bytes::BufMut;
130    ///
131    /// let mut buf = Vec::with_capacity(16);
132    ///
133    /// unsafe {
134    ///     buf.chunk_mut()[0..2].copy_from_slice(b"he");
135    ///
136    ///     buf.advance_mut(2);
137    ///
138    ///     buf.chunk_mut()[0..3].copy_from_slice(b"llo");
139    ///
140    ///     buf.advance_mut(3);
141    /// }
142    ///
143    /// assert_eq!(5, buf.len());
144    /// assert_eq!(buf, b"hello");
145    /// ```
146    ///
147    /// # Implementer notes
148    ///
149    /// This function should never panic. `bytes_mut` should return an empty
150    /// slice **if and only if** `remaining_mut` returns 0. In other words,
151    /// `bytes_mut` returning an empty slice implies that `remaining_mut` will
152    /// return 0 and `remaining_mut` returning 0 implies that `bytes_mut` will
153    /// return an empty slice.
154    fn chunk_mut(&mut self) -> &mut UninitSlice;
155
156    /// Transfer bytes into `self` from `src` and advance the cursor by the
157    /// number of bytes written.
158    ///
159    /// # Examples
160    ///
161    /// ```
162    /// use ntex_bytes::BufMut;
163    ///
164    /// let mut buf = vec![];
165    ///
166    /// buf.put_u8(b'h');
167    /// buf.put(&b"ello"[..]);
168    /// buf.put(" world");
169    ///
170    /// assert_eq!(buf, b"hello world");
171    /// ```
172    ///
173    /// # Panics
174    ///
175    /// Panics if `self` does not have enough capacity to contain `src`.
176    fn put<T: super::Buf>(&mut self, mut src: T)
177    where
178        Self: Sized,
179    {
180        assert!(self.remaining_mut() >= src.remaining());
181
182        while src.has_remaining() {
183            let s = src.chunk();
184            let d = self.chunk_mut();
185            let l = cmp::min(s.len(), d.len());
186
187            unsafe {
188                ptr::copy_nonoverlapping(s.as_ptr(), d.as_mut_ptr(), l);
189            }
190
191            src.advance(l);
192            unsafe {
193                self.advance_mut(l);
194            }
195        }
196    }
197
198    /// Transfer bytes into `self` from `src` and advance the cursor by the
199    /// number of bytes written.
200    ///
201    /// `self` must have enough remaining capacity to contain all of `src`.
202    ///
203    /// ```
204    /// use ntex_bytes::BufMut;
205    ///
206    /// let mut dst = [0; 6];
207    ///
208    /// {
209    ///     let mut buf = &mut dst[..];
210    ///     buf.put_slice(b"hello");
211    ///
212    ///     assert_eq!(1, buf.remaining_mut());
213    /// }
214    ///
215    /// assert_eq!(b"hello\0", &dst);
216    /// ```
217    fn put_slice(&mut self, src: &[u8]) {
218        let mut off = 0;
219
220        assert!(self.remaining_mut() >= src.len(), "buffer overflow");
221
222        while off < src.len() {
223            let cnt;
224
225            unsafe {
226                let dst = self.chunk_mut();
227                cnt = cmp::min(dst.len(), src.len() - off);
228
229                ptr::copy_nonoverlapping(src[off..].as_ptr(), dst.as_mut_ptr(), cnt);
230
231                off += cnt;
232            }
233
234            unsafe {
235                self.advance_mut(cnt);
236            }
237        }
238    }
239
240    /// Writes an unsigned 8 bit integer to `self`.
241    ///
242    /// The current position is advanced by 1.
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// use ntex_bytes::BufMut;
248    ///
249    /// let mut buf = vec![];
250    /// buf.put_u8(0x01);
251    /// assert_eq!(buf, b"\x01");
252    /// ```
253    ///
254    /// # Panics
255    ///
256    /// This function panics if there is not enough remaining capacity in
257    /// `self`.
258    #[inline]
259    fn put_u8(&mut self, n: u8) {
260        let src = [n];
261        self.put_slice(&src);
262    }
263
264    /// Writes a signed 8 bit integer to `self`.
265    ///
266    /// The current position is advanced by 1.
267    ///
268    /// # Examples
269    ///
270    /// ```
271    /// use ntex_bytes::BufMut;
272    ///
273    /// let mut buf = vec![];
274    /// buf.put_i8(0x01);
275    /// assert_eq!(buf, b"\x01");
276    /// ```
277    ///
278    /// # Panics
279    ///
280    /// This function panics if there is not enough remaining capacity in
281    /// `self`.
282    fn put_i8(&mut self, n: i8) {
283        self.put_slice(&[n as u8]);
284    }
285
286    /// Writes an unsigned 16 bit integer to `self` in big-endian byte order.
287    ///
288    /// The current position is advanced by 2.
289    ///
290    /// # Examples
291    ///
292    /// ```
293    /// use ntex_bytes::BufMut;
294    ///
295    /// let mut buf = vec![];
296    /// buf.put_u16(0x0809);
297    /// assert_eq!(buf, b"\x08\x09");
298    /// ```
299    ///
300    /// # Panics
301    ///
302    /// This function panics if there is not enough remaining capacity in
303    /// `self`.
304    #[inline]
305    fn put_u16(&mut self, n: u16) {
306        self.put_slice(&n.to_be_bytes());
307    }
308
309    /// Writes an unsigned 16 bit integer to `self` in little-endian byte order.
310    ///
311    /// The current position is advanced by 2.
312    ///
313    /// # Examples
314    ///
315    /// ```
316    /// use ntex_bytes::BufMut;
317    ///
318    /// let mut buf = vec![];
319    /// buf.put_u16_le(0x0809);
320    /// assert_eq!(buf, b"\x09\x08");
321    /// ```
322    ///
323    /// # Panics
324    ///
325    /// This function panics if there is not enough remaining capacity in
326    /// `self`.
327    #[inline]
328    fn put_u16_le(&mut self, n: u16) {
329        self.put_slice(&n.to_le_bytes());
330    }
331
332    /// Writes a signed 16 bit integer to `self` in big-endian byte order.
333    ///
334    /// The current position is advanced by 2.
335    ///
336    /// # Examples
337    ///
338    /// ```
339    /// use ntex_bytes::BufMut;
340    ///
341    /// let mut buf = vec![];
342    /// buf.put_i16(0x0809);
343    /// assert_eq!(buf, b"\x08\x09");
344    /// ```
345    ///
346    /// # Panics
347    ///
348    /// This function panics if there is not enough remaining capacity in
349    /// `self`.
350    #[inline]
351    fn put_i16(&mut self, n: i16) {
352        self.put_slice(&n.to_be_bytes());
353    }
354
355    /// Writes a signed 16 bit integer to `self` in little-endian byte order.
356    ///
357    /// The current position is advanced by 2.
358    ///
359    /// # Examples
360    ///
361    /// ```
362    /// use ntex_bytes::BufMut;
363    ///
364    /// let mut buf = vec![];
365    /// buf.put_i16_le(0x0809);
366    /// assert_eq!(buf, b"\x09\x08");
367    /// ```
368    ///
369    /// # Panics
370    ///
371    /// This function panics if there is not enough remaining capacity in
372    /// `self`.
373    #[inline]
374    fn put_i16_le(&mut self, n: i16) {
375        self.put_slice(&n.to_le_bytes());
376    }
377
378    /// Writes an unsigned 32 bit integer to `self` in big-endian byte order.
379    ///
380    /// The current position is advanced by 4.
381    ///
382    /// # Examples
383    ///
384    /// ```
385    /// use ntex_bytes::BufMut;
386    ///
387    /// let mut buf = vec![];
388    /// buf.put_u32(0x0809A0A1);
389    /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
390    /// ```
391    ///
392    /// # Panics
393    ///
394    /// This function panics if there is not enough remaining capacity in
395    /// `self`.
396    #[inline]
397    fn put_u32(&mut self, n: u32) {
398        self.put_slice(&n.to_be_bytes());
399    }
400
401    /// Writes an unsigned 32 bit integer to `self` in little-endian byte order.
402    ///
403    /// The current position is advanced by 4.
404    ///
405    /// # Examples
406    ///
407    /// ```
408    /// use ntex_bytes::BufMut;
409    ///
410    /// let mut buf = vec![];
411    /// buf.put_u32_le(0x0809A0A1);
412    /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
413    /// ```
414    ///
415    /// # Panics
416    ///
417    /// This function panics if there is not enough remaining capacity in
418    /// `self`.
419    #[inline]
420    fn put_u32_le(&mut self, n: u32) {
421        self.put_slice(&n.to_le_bytes());
422    }
423
424    /// Writes a signed 32 bit integer to `self` in big-endian byte order.
425    ///
426    /// The current position is advanced by 4.
427    ///
428    /// # Examples
429    ///
430    /// ```
431    /// use ntex_bytes::BufMut;
432    ///
433    /// let mut buf = vec![];
434    /// buf.put_i32(0x0809A0A1);
435    /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
436    /// ```
437    ///
438    /// # Panics
439    ///
440    /// This function panics if there is not enough remaining capacity in
441    /// `self`.
442    #[inline]
443    fn put_i32(&mut self, n: i32) {
444        self.put_slice(&n.to_be_bytes());
445    }
446
447    /// Writes a signed 32 bit integer to `self` in little-endian byte order.
448    ///
449    /// The current position is advanced by 4.
450    ///
451    /// # Examples
452    ///
453    /// ```
454    /// use ntex_bytes::BufMut;
455    ///
456    /// let mut buf = vec![];
457    /// buf.put_i32_le(0x0809A0A1);
458    /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
459    /// ```
460    ///
461    /// # Panics
462    ///
463    /// This function panics if there is not enough remaining capacity in
464    /// `self`.
465    #[inline]
466    fn put_i32_le(&mut self, n: i32) {
467        self.put_slice(&n.to_le_bytes());
468    }
469
470    /// Writes an unsigned 64 bit integer to `self` in the big-endian byte order.
471    ///
472    /// The current position is advanced by 8.
473    ///
474    /// # Examples
475    ///
476    /// ```
477    /// use ntex_bytes::BufMut;
478    ///
479    /// let mut buf = vec![];
480    /// buf.put_u64(0x0102030405060708);
481    /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
482    /// ```
483    ///
484    /// # Panics
485    ///
486    /// This function panics if there is not enough remaining capacity in
487    /// `self`.
488    #[inline]
489    fn put_u64(&mut self, n: u64) {
490        self.put_slice(&n.to_be_bytes());
491    }
492
493    /// Writes an unsigned 64 bit integer to `self` in little-endian byte order.
494    ///
495    /// The current position is advanced by 8.
496    ///
497    /// # Examples
498    ///
499    /// ```
500    /// use ntex_bytes::BufMut;
501    ///
502    /// let mut buf = vec![];
503    /// buf.put_u64_le(0x0102030405060708);
504    /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
505    /// ```
506    ///
507    /// # Panics
508    ///
509    /// This function panics if there is not enough remaining capacity in
510    /// `self`.
511    #[inline]
512    fn put_u64_le(&mut self, n: u64) {
513        self.put_slice(&n.to_le_bytes());
514    }
515
516    /// Writes a signed 64 bit integer to `self` in the big-endian byte order.
517    ///
518    /// The current position is advanced by 8.
519    ///
520    /// # Examples
521    ///
522    /// ```
523    /// use ntex_bytes::BufMut;
524    ///
525    /// let mut buf = vec![];
526    /// buf.put_i64(0x0102030405060708);
527    /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
528    /// ```
529    ///
530    /// # Panics
531    ///
532    /// This function panics if there is not enough remaining capacity in
533    /// `self`.
534    #[inline]
535    fn put_i64(&mut self, n: i64) {
536        self.put_slice(&n.to_be_bytes());
537    }
538
539    /// Writes a signed 64 bit integer to `self` in little-endian byte order.
540    ///
541    /// The current position is advanced by 8.
542    ///
543    /// # Examples
544    ///
545    /// ```
546    /// use ntex_bytes::BufMut;
547    ///
548    /// let mut buf = vec![];
549    /// buf.put_i64_le(0x0102030405060708);
550    /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
551    /// ```
552    ///
553    /// # Panics
554    ///
555    /// This function panics if there is not enough remaining capacity in
556    /// `self`.
557    #[inline]
558    fn put_i64_le(&mut self, n: i64) {
559        self.put_slice(&n.to_le_bytes());
560    }
561
562    /// Writes an unsigned 128 bit integer to `self` in the big-endian byte order.
563    ///
564    /// The current position is advanced by 16.
565    ///
566    /// # Examples
567    ///
568    /// ```
569    /// use ntex_bytes::BufMut;
570    ///
571    /// let mut buf = vec![];
572    /// buf.put_u128(0x01020304050607080910111213141516);
573    /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
574    /// ```
575    ///
576    /// # Panics
577    ///
578    /// This function panics if there is not enough remaining capacity in
579    /// `self`.
580    #[inline]
581    fn put_u128(&mut self, n: u128) {
582        self.put_slice(&n.to_be_bytes());
583    }
584
585    /// Writes an unsigned 128 bit integer to `self` in little-endian byte order.
586    ///
587    /// The current position is advanced by 16.
588    ///
589    /// # Examples
590    ///
591    /// ```
592    /// use ntex_bytes::BufMut;
593    ///
594    /// let mut buf = vec![];
595    /// buf.put_u128_le(0x01020304050607080910111213141516);
596    /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
597    /// ```
598    ///
599    /// # Panics
600    ///
601    /// This function panics if there is not enough remaining capacity in
602    /// `self`.
603    #[inline]
604    fn put_u128_le(&mut self, n: u128) {
605        self.put_slice(&n.to_le_bytes());
606    }
607
608    /// Writes a signed 128 bit integer to `self` in the big-endian byte order.
609    ///
610    /// The current position is advanced by 16.
611    ///
612    /// # Examples
613    ///
614    /// ```
615    /// use ntex_bytes::BufMut;
616    ///
617    /// let mut buf = vec![];
618    /// buf.put_i128(0x01020304050607080910111213141516);
619    /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
620    /// ```
621    ///
622    /// # Panics
623    ///
624    /// This function panics if there is not enough remaining capacity in
625    /// `self`.
626    #[inline]
627    fn put_i128(&mut self, n: i128) {
628        self.put_slice(&n.to_be_bytes());
629    }
630
631    /// Writes a signed 128 bit integer to `self` in little-endian byte order.
632    ///
633    /// The current position is advanced by 16.
634    ///
635    /// # Examples
636    ///
637    /// ```
638    /// use ntex_bytes::BufMut;
639    ///
640    /// let mut buf = vec![];
641    /// buf.put_i128_le(0x01020304050607080910111213141516);
642    /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
643    /// ```
644    ///
645    /// # Panics
646    ///
647    /// This function panics if there is not enough remaining capacity in
648    /// `self`.
649    #[inline]
650    fn put_i128_le(&mut self, n: i128) {
651        self.put_slice(&n.to_le_bytes());
652    }
653
654    /// Writes an unsigned n-byte integer to `self` in big-endian byte order.
655    ///
656    /// The current position is advanced by `nbytes`.
657    ///
658    /// # Examples
659    ///
660    /// ```
661    /// use ntex_bytes::BufMut;
662    ///
663    /// let mut buf = vec![];
664    /// buf.put_uint(0x010203, 3);
665    /// assert_eq!(buf, b"\x01\x02\x03");
666    /// ```
667    ///
668    /// # Panics
669    ///
670    /// This function panics if there is not enough remaining capacity in
671    /// `self`.
672    #[inline]
673    fn put_uint(&mut self, n: u64, nbytes: usize) {
674        self.put_slice(&n.to_be_bytes()[mem::size_of_val(&n) - nbytes..]);
675    }
676
677    /// Writes an unsigned n-byte integer to `self` in the little-endian byte order.
678    ///
679    /// The current position is advanced by `nbytes`.
680    ///
681    /// # Examples
682    ///
683    /// ```
684    /// use ntex_bytes::BufMut;
685    ///
686    /// let mut buf = vec![];
687    /// buf.put_uint_le(0x010203, 3);
688    /// assert_eq!(buf, b"\x03\x02\x01");
689    /// ```
690    ///
691    /// # Panics
692    ///
693    /// This function panics if there is not enough remaining capacity in
694    /// `self`.
695    #[inline]
696    fn put_uint_le(&mut self, n: u64, nbytes: usize) {
697        self.put_slice(&n.to_le_bytes()[0..nbytes]);
698    }
699
700    /// Writes a signed n-byte integer to `self` in big-endian byte order.
701    ///
702    /// The current position is advanced by `nbytes`.
703    ///
704    /// # Examples
705    ///
706    /// ```
707    /// use ntex_bytes::BufMut;
708    ///
709    /// let mut buf = vec![];
710    /// buf.put_int(0x010203, 3);
711    /// assert_eq!(buf, b"\x01\x02\x03");
712    /// ```
713    ///
714    /// # Panics
715    ///
716    /// This function panics if there is not enough remaining capacity in
717    /// `self`.
718    #[inline]
719    fn put_int(&mut self, n: i64, nbytes: usize) {
720        self.put_slice(&n.to_be_bytes()[mem::size_of_val(&n) - nbytes..]);
721    }
722
723    /// Writes a signed n-byte integer to `self` in little-endian byte order.
724    ///
725    /// The current position is advanced by `nbytes`.
726    ///
727    /// # Examples
728    ///
729    /// ```
730    /// use ntex_bytes::BufMut;
731    ///
732    /// let mut buf = vec![];
733    /// buf.put_int_le(0x010203, 3);
734    /// assert_eq!(buf, b"\x03\x02\x01");
735    /// ```
736    ///
737    /// # Panics
738    ///
739    /// This function panics if there is not enough remaining capacity in
740    /// `self`.
741    #[inline]
742    fn put_int_le(&mut self, n: i64, nbytes: usize) {
743        self.put_slice(&n.to_le_bytes()[0..nbytes]);
744    }
745
746    /// Writes  an IEEE754 single-precision (4 bytes) floating point number to
747    /// `self` in big-endian byte order.
748    ///
749    /// The current position is advanced by 4.
750    ///
751    /// # Examples
752    ///
753    /// ```
754    /// use ntex_bytes::BufMut;
755    ///
756    /// let mut buf = vec![];
757    /// buf.put_f32(1.2f32);
758    /// assert_eq!(buf, b"\x3F\x99\x99\x9A");
759    /// ```
760    ///
761    /// # Panics
762    ///
763    /// This function panics if there is not enough remaining capacity in
764    /// `self`.
765    #[inline]
766    fn put_f32(&mut self, n: f32) {
767        self.put_u32(n.to_bits());
768    }
769
770    /// Writes  an IEEE754 single-precision (4 bytes) floating point number to
771    /// `self` in little-endian byte order.
772    ///
773    /// The current position is advanced by 4.
774    ///
775    /// # Examples
776    ///
777    /// ```
778    /// use ntex_bytes::BufMut;
779    ///
780    /// let mut buf = vec![];
781    /// buf.put_f32_le(1.2f32);
782    /// assert_eq!(buf, b"\x9A\x99\x99\x3F");
783    /// ```
784    ///
785    /// # Panics
786    ///
787    /// This function panics if there is not enough remaining capacity in
788    /// `self`.
789    #[inline]
790    fn put_f32_le(&mut self, n: f32) {
791        self.put_u32_le(n.to_bits());
792    }
793
794    /// Writes  an IEEE754 double-precision (8 bytes) floating point number to
795    /// `self` in big-endian byte order.
796    ///
797    /// The current position is advanced by 8.
798    ///
799    /// # Examples
800    ///
801    /// ```
802    /// use ntex_bytes::BufMut;
803    ///
804    /// let mut buf = vec![];
805    /// buf.put_f64(1.2f64);
806    /// assert_eq!(buf, b"\x3F\xF3\x33\x33\x33\x33\x33\x33");
807    /// ```
808    ///
809    /// # Panics
810    ///
811    /// This function panics if there is not enough remaining capacity in
812    /// `self`.
813    #[inline]
814    fn put_f64(&mut self, n: f64) {
815        self.put_u64(n.to_bits());
816    }
817
818    /// Writes  an IEEE754 double-precision (8 bytes) floating point number to
819    /// `self` in little-endian byte order.
820    ///
821    /// The current position is advanced by 8.
822    ///
823    /// # Examples
824    ///
825    /// ```
826    /// use ntex_bytes::BufMut;
827    ///
828    /// let mut buf = vec![];
829    /// buf.put_f64_le(1.2f64);
830    /// assert_eq!(buf, b"\x33\x33\x33\x33\x33\x33\xF3\x3F");
831    /// ```
832    ///
833    /// # Panics
834    ///
835    /// This function panics if there is not enough remaining capacity in
836    /// `self`.
837    #[inline]
838    fn put_f64_le(&mut self, n: f64) {
839        self.put_u64_le(n.to_bits());
840    }
841
842    /// Creates an adaptor which implements the `Write` trait for `self`.
843    ///
844    /// This function returns a new value which implements `Write` by adapting
845    /// the `Write` trait functions to the `BufMut` trait functions. Given that
846    /// `BufMut` operations are infallible, none of the `Write` functions will
847    /// return with `Err`.
848    ///
849    /// # Examples
850    ///
851    /// ```
852    /// use ntex_bytes::BufMut;
853    /// use std::io::Write;
854    ///
855    /// let mut buf = vec![].writer();
856    ///
857    /// let num = buf.write(&b"hello world"[..]).unwrap();
858    /// assert_eq!(11, num);
859    ///
860    /// let buf = buf.into_inner();
861    ///
862    /// assert_eq!(*buf, b"hello world"[..]);
863    /// ```
864    fn writer(self) -> Writer<Self>
865    where
866        Self: Sized,
867    {
868        Writer::new(self)
869    }
870}
871
872impl<T: BufMut + ?Sized> BufMut for &mut T {
873    fn remaining_mut(&self) -> usize {
874        (**self).remaining_mut()
875    }
876
877    fn chunk_mut(&mut self) -> &mut UninitSlice {
878        (**self).chunk_mut()
879    }
880
881    unsafe fn advance_mut(&mut self, cnt: usize) {
882        (**self).advance_mut(cnt);
883    }
884}
885
886impl<T: BufMut + ?Sized> BufMut for Box<T> {
887    fn remaining_mut(&self) -> usize {
888        (**self).remaining_mut()
889    }
890
891    fn chunk_mut(&mut self) -> &mut UninitSlice {
892        (**self).chunk_mut()
893    }
894
895    unsafe fn advance_mut(&mut self, cnt: usize) {
896        (**self).advance_mut(cnt);
897    }
898}
899
900impl BufMut for Vec<u8> {
901    #[inline]
902    fn remaining_mut(&self) -> usize {
903        usize::MAX - self.len()
904    }
905
906    #[inline]
907    unsafe fn advance_mut(&mut self, cnt: usize) {
908        let len = self.len();
909        let remaining = self.capacity() - len;
910        if cnt > remaining {
911            // Reserve additional capacity, and ensure that the total length
912            // will not overflow usize.
913            self.reserve(cnt);
914        }
915
916        self.set_len(len + cnt);
917    }
918
919    #[inline]
920    fn chunk_mut(&mut self) -> &mut UninitSlice {
921        if self.capacity() == self.len() {
922            self.reserve(64); // Grow the vec
923        }
924
925        let cap = self.capacity();
926        let len = self.len();
927
928        let ptr = self.as_mut_ptr();
929        unsafe { &mut UninitSlice::from_raw_parts_mut(ptr, cap)[len..] }
930    }
931}
932
933impl BufMut for &mut [u8] {
934    #[inline]
935    fn remaining_mut(&self) -> usize {
936        self.len()
937    }
938
939    #[inline]
940    fn chunk_mut(&mut self) -> &mut UninitSlice {
941        // UninitSlice is repr(transparent), so safe to transmute
942        unsafe { &mut *(ptr::from_mut::<[u8]>(*self) as *mut _) }
943    }
944
945    #[inline]
946    unsafe fn advance_mut(&mut self, cnt: usize) {
947        // Lifetime dance taken from `impl Write for &mut [u8]`.
948        let (_, b) = core::mem::take(self).split_at_mut(cnt);
949        *self = b;
950    }
951
952    #[inline]
953    fn put_slice(&mut self, src: &[u8]) {
954        self[..src.len()].copy_from_slice(src);
955        unsafe {
956            self.advance_mut(src.len());
957        }
958    }
959}
960
961// The existence of this function makes the compiler catch if the BufMut
962// trait is "object-safe" or not.
963fn _assert_trait_object(_b: &dyn BufMut) {}
964
965#[cfg(test)]
966#[allow(unused_allocation, warnings)]
967mod tests {
968    use super::*;
969    use crate::BytesMut;
970
971    #[test]
972    #[allow(clippy::needless_borrow, clippy::too_many_lines)]
973    fn buf_mut_tests() {
974        let mut buf = vec![];
975        buf.put_u8(0x01);
976        assert_eq!(buf, b"\x01");
977
978        assert_eq!(buf.remaining_mut(), usize::MAX - 1);
979        assert_eq!((&buf).remaining_mut(), usize::MAX - 1);
980        assert_eq!(Box::new(buf).remaining_mut(), usize::MAX - 1);
981
982        let mut buf = [b'1'; 10];
983        let mut b = buf.as_mut();
984        assert_eq!(b.remaining_mut(), 10);
985        assert!(b.has_remaining_mut());
986        b.put_slice(b"123");
987        assert_eq!(&buf[..], b"1231111111");
988
989        let mut b: &mut [u8] = buf.as_mut();
990        let chunk = b.chunk_mut();
991        chunk.write_byte(0, b'9');
992        assert_eq!(&buf[..], b"9231111111");
993
994        let mut b = buf.as_mut();
995        let chunk = b.chunk_mut();
996        chunk.copy_from_slice(b"0000000000");
997        assert_eq!(&buf[..], b"0000000000");
998
999        let mut b = buf.as_mut();
1000        assert_eq!(format!("{:?}", b.chunk_mut()), "UninitSlice[...]");
1001
1002        let b = buf.as_mut();
1003        let mut bb = Box::new(b);
1004        unsafe { bb.advance_mut(1) };
1005        let chunk = bb.chunk_mut();
1006        chunk.copy_from_slice(b"111111111");
1007        assert_eq!(&buf[..], b"0111111111");
1008
1009        let mut buf = BytesMut::new();
1010        buf.put_u8(0x01);
1011        assert_eq!(buf, b"\x01"[..]);
1012
1013        let mut buf = BytesMut::new();
1014        buf.put_u8(0x01);
1015        assert_eq!(buf, b"\x01"[..]);
1016
1017        let mut buf = vec![];
1018        buf.put_i8(0x01);
1019        assert_eq!(buf, b"\x01");
1020
1021        let mut buf = BytesMut::new();
1022        buf.put_i8(0x01);
1023        assert_eq!(buf, b"\x01"[..]);
1024
1025        let mut buf = BytesMut::new();
1026        buf.put_i8(0x01);
1027        assert_eq!(buf, b"\x01"[..]);
1028        assert_eq!((&mut buf).remaining_mut(), 107);
1029        let chunk = (&mut buf).chunk_mut();
1030        chunk.write_byte(0, b'9');
1031        unsafe { (&mut buf).advance_mut(1) };
1032        assert_eq!((&mut buf).remaining_mut(), 106);
1033
1034        let mut buf = vec![];
1035        buf.put_i16(0x0809);
1036        assert_eq!(buf, b"\x08\x09");
1037
1038        let mut buf = vec![];
1039        buf.put_i16_le(0x0809);
1040        assert_eq!(buf, b"\x09\x08");
1041
1042        let mut buf = vec![];
1043        buf.put_u32(0x0809_A0A1);
1044        assert_eq!(buf, b"\x08\x09\xA0\xA1");
1045
1046        let mut buf = vec![];
1047        buf.put_i32(0x0809_A0A1);
1048        assert_eq!(buf, b"\x08\x09\xA0\xA1");
1049
1050        let mut buf = vec![];
1051        buf.put_i32_le(0x0809_A0A1);
1052        assert_eq!(buf, b"\xA1\xA0\x09\x08");
1053
1054        let mut buf = vec![];
1055        buf.put_u64(0x0102_0304_0506_0708);
1056        assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
1057
1058        let mut buf = vec![];
1059        buf.put_u64_le(0x0102_0304_0506_0708);
1060        assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
1061
1062        let mut buf = vec![];
1063        buf.put_i64(0x0102_0304_0506_0708);
1064        assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
1065
1066        let mut buf = vec![];
1067        buf.put_i64_le(0x0102_0304_0506_0708);
1068        assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
1069
1070        let mut buf = vec![];
1071        buf.put_u128(0x0102_0304_0506_0708_0910_1112_1314_1516);
1072        assert_eq!(
1073            buf,
1074            b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16"
1075        );
1076
1077        let mut buf = vec![];
1078        buf.put_u128_le(0x0102_0304_0506_0708_0910_1112_1314_1516);
1079        assert_eq!(
1080            buf,
1081            b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01"
1082        );
1083
1084        let mut buf = vec![];
1085        buf.put_i128(0x0102_0304_0506_0708_0910_1112_1314_1516);
1086        assert_eq!(
1087            buf,
1088            b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16"
1089        );
1090
1091        let mut buf = vec![];
1092        buf.put_i128_le(0x0102_0304_0506_0708_0910_1112_1314_1516);
1093        assert_eq!(
1094            buf,
1095            b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01"
1096        );
1097
1098        let mut buf = vec![];
1099        buf.put_uint(0x01_0203, 3);
1100        assert_eq!(buf, b"\x01\x02\x03");
1101
1102        let mut buf = vec![];
1103        buf.put_uint_le(0x01_0203, 3);
1104        assert_eq!(buf, b"\x03\x02\x01");
1105
1106        let mut buf = vec![];
1107        buf.put_int(0x01_0203, 3);
1108        assert_eq!(buf, b"\x01\x02\x03");
1109
1110        let mut buf = vec![];
1111        buf.put_int_le(0x01_0203, 3);
1112        assert_eq!(buf, b"\x03\x02\x01");
1113
1114        let mut buf = vec![];
1115        buf.put_f32(1.2f32);
1116        assert_eq!(buf, b"\x3F\x99\x99\x9A");
1117
1118        let mut buf = vec![];
1119        buf.put_f32_le(1.2f32);
1120        assert_eq!(buf, b"\x9A\x99\x99\x3F");
1121
1122        let mut buf = vec![];
1123        buf.put_f64(1.2f64);
1124        assert_eq!(buf, b"\x3F\xF3\x33\x33\x33\x33\x33\x33");
1125
1126        let mut buf = vec![];
1127        buf.put_f64_le(1.2f64);
1128        assert_eq!(buf, b"\x33\x33\x33\x33\x33\x33\xF3\x3F");
1129    }
1130}