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        let src = [n as u8];
284        self.put_slice(&src)
285    }
286
287    /// Writes an unsigned 16 bit integer to `self` in big-endian byte order.
288    ///
289    /// The current position is advanced by 2.
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// use ntex_bytes::BufMut;
295    ///
296    /// let mut buf = vec![];
297    /// buf.put_u16(0x0809);
298    /// assert_eq!(buf, b"\x08\x09");
299    /// ```
300    ///
301    /// # Panics
302    ///
303    /// This function panics if there is not enough remaining capacity in
304    /// `self`.
305    #[inline]
306    fn put_u16(&mut self, n: u16) {
307        self.put_slice(&n.to_be_bytes())
308    }
309
310    /// Writes an unsigned 16 bit integer to `self` in little-endian byte order.
311    ///
312    /// The current position is advanced by 2.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// use ntex_bytes::BufMut;
318    ///
319    /// let mut buf = vec![];
320    /// buf.put_u16_le(0x0809);
321    /// assert_eq!(buf, b"\x09\x08");
322    /// ```
323    ///
324    /// # Panics
325    ///
326    /// This function panics if there is not enough remaining capacity in
327    /// `self`.
328    #[inline]
329    fn put_u16_le(&mut self, n: u16) {
330        self.put_slice(&n.to_le_bytes())
331    }
332
333    /// Writes a signed 16 bit integer to `self` in big-endian byte order.
334    ///
335    /// The current position is advanced by 2.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// use ntex_bytes::BufMut;
341    ///
342    /// let mut buf = vec![];
343    /// buf.put_i16(0x0809);
344    /// assert_eq!(buf, b"\x08\x09");
345    /// ```
346    ///
347    /// # Panics
348    ///
349    /// This function panics if there is not enough remaining capacity in
350    /// `self`.
351    #[inline]
352    fn put_i16(&mut self, n: i16) {
353        self.put_slice(&n.to_be_bytes())
354    }
355
356    /// Writes a signed 16 bit integer to `self` in little-endian byte order.
357    ///
358    /// The current position is advanced by 2.
359    ///
360    /// # Examples
361    ///
362    /// ```
363    /// use ntex_bytes::BufMut;
364    ///
365    /// let mut buf = vec![];
366    /// buf.put_i16_le(0x0809);
367    /// assert_eq!(buf, b"\x09\x08");
368    /// ```
369    ///
370    /// # Panics
371    ///
372    /// This function panics if there is not enough remaining capacity in
373    /// `self`.
374    #[inline]
375    fn put_i16_le(&mut self, n: i16) {
376        self.put_slice(&n.to_le_bytes())
377    }
378
379    /// Writes an unsigned 32 bit integer to `self` in big-endian byte order.
380    ///
381    /// The current position is advanced by 4.
382    ///
383    /// # Examples
384    ///
385    /// ```
386    /// use ntex_bytes::BufMut;
387    ///
388    /// let mut buf = vec![];
389    /// buf.put_u32(0x0809A0A1);
390    /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
391    /// ```
392    ///
393    /// # Panics
394    ///
395    /// This function panics if there is not enough remaining capacity in
396    /// `self`.
397    #[inline]
398    fn put_u32(&mut self, n: u32) {
399        self.put_slice(&n.to_be_bytes())
400    }
401
402    /// Writes an unsigned 32 bit integer to `self` in little-endian byte order.
403    ///
404    /// The current position is advanced by 4.
405    ///
406    /// # Examples
407    ///
408    /// ```
409    /// use ntex_bytes::BufMut;
410    ///
411    /// let mut buf = vec![];
412    /// buf.put_u32_le(0x0809A0A1);
413    /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
414    /// ```
415    ///
416    /// # Panics
417    ///
418    /// This function panics if there is not enough remaining capacity in
419    /// `self`.
420    #[inline]
421    fn put_u32_le(&mut self, n: u32) {
422        self.put_slice(&n.to_le_bytes())
423    }
424
425    /// Writes a signed 32 bit integer to `self` in big-endian byte order.
426    ///
427    /// The current position is advanced by 4.
428    ///
429    /// # Examples
430    ///
431    /// ```
432    /// use ntex_bytes::BufMut;
433    ///
434    /// let mut buf = vec![];
435    /// buf.put_i32(0x0809A0A1);
436    /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
437    /// ```
438    ///
439    /// # Panics
440    ///
441    /// This function panics if there is not enough remaining capacity in
442    /// `self`.
443    #[inline]
444    fn put_i32(&mut self, n: i32) {
445        self.put_slice(&n.to_be_bytes())
446    }
447
448    /// Writes a signed 32 bit integer to `self` in little-endian byte order.
449    ///
450    /// The current position is advanced by 4.
451    ///
452    /// # Examples
453    ///
454    /// ```
455    /// use ntex_bytes::BufMut;
456    ///
457    /// let mut buf = vec![];
458    /// buf.put_i32_le(0x0809A0A1);
459    /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
460    /// ```
461    ///
462    /// # Panics
463    ///
464    /// This function panics if there is not enough remaining capacity in
465    /// `self`.
466    #[inline]
467    fn put_i32_le(&mut self, n: i32) {
468        self.put_slice(&n.to_le_bytes())
469    }
470
471    /// Writes an unsigned 64 bit integer to `self` in the big-endian byte order.
472    ///
473    /// The current position is advanced by 8.
474    ///
475    /// # Examples
476    ///
477    /// ```
478    /// use ntex_bytes::BufMut;
479    ///
480    /// let mut buf = vec![];
481    /// buf.put_u64(0x0102030405060708);
482    /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
483    /// ```
484    ///
485    /// # Panics
486    ///
487    /// This function panics if there is not enough remaining capacity in
488    /// `self`.
489    #[inline]
490    fn put_u64(&mut self, n: u64) {
491        self.put_slice(&n.to_be_bytes())
492    }
493
494    /// Writes an unsigned 64 bit integer to `self` in little-endian byte order.
495    ///
496    /// The current position is advanced by 8.
497    ///
498    /// # Examples
499    ///
500    /// ```
501    /// use ntex_bytes::BufMut;
502    ///
503    /// let mut buf = vec![];
504    /// buf.put_u64_le(0x0102030405060708);
505    /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
506    /// ```
507    ///
508    /// # Panics
509    ///
510    /// This function panics if there is not enough remaining capacity in
511    /// `self`.
512    #[inline]
513    fn put_u64_le(&mut self, n: u64) {
514        self.put_slice(&n.to_le_bytes())
515    }
516
517    /// Writes a signed 64 bit integer to `self` in the big-endian byte order.
518    ///
519    /// The current position is advanced by 8.
520    ///
521    /// # Examples
522    ///
523    /// ```
524    /// use ntex_bytes::BufMut;
525    ///
526    /// let mut buf = vec![];
527    /// buf.put_i64(0x0102030405060708);
528    /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
529    /// ```
530    ///
531    /// # Panics
532    ///
533    /// This function panics if there is not enough remaining capacity in
534    /// `self`.
535    #[inline]
536    fn put_i64(&mut self, n: i64) {
537        self.put_slice(&n.to_be_bytes())
538    }
539
540    /// Writes a signed 64 bit integer to `self` in little-endian byte order.
541    ///
542    /// The current position is advanced by 8.
543    ///
544    /// # Examples
545    ///
546    /// ```
547    /// use ntex_bytes::BufMut;
548    ///
549    /// let mut buf = vec![];
550    /// buf.put_i64_le(0x0102030405060708);
551    /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
552    /// ```
553    ///
554    /// # Panics
555    ///
556    /// This function panics if there is not enough remaining capacity in
557    /// `self`.
558    #[inline]
559    fn put_i64_le(&mut self, n: i64) {
560        self.put_slice(&n.to_le_bytes())
561    }
562
563    /// Writes an unsigned 128 bit integer to `self` in the big-endian byte order.
564    ///
565    /// The current position is advanced by 16.
566    ///
567    /// # Examples
568    ///
569    /// ```
570    /// use ntex_bytes::BufMut;
571    ///
572    /// let mut buf = vec![];
573    /// buf.put_u128(0x01020304050607080910111213141516);
574    /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
575    /// ```
576    ///
577    /// # Panics
578    ///
579    /// This function panics if there is not enough remaining capacity in
580    /// `self`.
581    #[inline]
582    fn put_u128(&mut self, n: u128) {
583        self.put_slice(&n.to_be_bytes())
584    }
585
586    /// Writes an unsigned 128 bit integer to `self` in little-endian byte order.
587    ///
588    /// The current position is advanced by 16.
589    ///
590    /// # Examples
591    ///
592    /// ```
593    /// use ntex_bytes::BufMut;
594    ///
595    /// let mut buf = vec![];
596    /// buf.put_u128_le(0x01020304050607080910111213141516);
597    /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
598    /// ```
599    ///
600    /// # Panics
601    ///
602    /// This function panics if there is not enough remaining capacity in
603    /// `self`.
604    #[inline]
605    fn put_u128_le(&mut self, n: u128) {
606        self.put_slice(&n.to_le_bytes())
607    }
608
609    /// Writes a signed 128 bit integer to `self` in the big-endian byte order.
610    ///
611    /// The current position is advanced by 16.
612    ///
613    /// # Examples
614    ///
615    /// ```
616    /// use ntex_bytes::BufMut;
617    ///
618    /// let mut buf = vec![];
619    /// buf.put_i128(0x01020304050607080910111213141516);
620    /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
621    /// ```
622    ///
623    /// # Panics
624    ///
625    /// This function panics if there is not enough remaining capacity in
626    /// `self`.
627    #[inline]
628    fn put_i128(&mut self, n: i128) {
629        self.put_slice(&n.to_be_bytes())
630    }
631
632    /// Writes a signed 128 bit integer to `self` in little-endian byte order.
633    ///
634    /// The current position is advanced by 16.
635    ///
636    /// # Examples
637    ///
638    /// ```
639    /// use ntex_bytes::BufMut;
640    ///
641    /// let mut buf = vec![];
642    /// buf.put_i128_le(0x01020304050607080910111213141516);
643    /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
644    /// ```
645    ///
646    /// # Panics
647    ///
648    /// This function panics if there is not enough remaining capacity in
649    /// `self`.
650    #[inline]
651    fn put_i128_le(&mut self, n: i128) {
652        self.put_slice(&n.to_le_bytes())
653    }
654
655    /// Writes an unsigned n-byte integer to `self` in big-endian byte order.
656    ///
657    /// The current position is advanced by `nbytes`.
658    ///
659    /// # Examples
660    ///
661    /// ```
662    /// use ntex_bytes::BufMut;
663    ///
664    /// let mut buf = vec![];
665    /// buf.put_uint(0x010203, 3);
666    /// assert_eq!(buf, b"\x01\x02\x03");
667    /// ```
668    ///
669    /// # Panics
670    ///
671    /// This function panics if there is not enough remaining capacity in
672    /// `self`.
673    #[inline]
674    fn put_uint(&mut self, n: u64, nbytes: usize) {
675        self.put_slice(&n.to_be_bytes()[mem::size_of_val(&n) - nbytes..]);
676    }
677
678    /// Writes an unsigned n-byte integer to `self` in the little-endian byte order.
679    ///
680    /// The current position is advanced by `nbytes`.
681    ///
682    /// # Examples
683    ///
684    /// ```
685    /// use ntex_bytes::BufMut;
686    ///
687    /// let mut buf = vec![];
688    /// buf.put_uint_le(0x010203, 3);
689    /// assert_eq!(buf, b"\x03\x02\x01");
690    /// ```
691    ///
692    /// # Panics
693    ///
694    /// This function panics if there is not enough remaining capacity in
695    /// `self`.
696    #[inline]
697    fn put_uint_le(&mut self, n: u64, nbytes: usize) {
698        self.put_slice(&n.to_le_bytes()[0..nbytes]);
699    }
700
701    /// Writes a signed n-byte integer to `self` in big-endian byte order.
702    ///
703    /// The current position is advanced by `nbytes`.
704    ///
705    /// # Examples
706    ///
707    /// ```
708    /// use ntex_bytes::BufMut;
709    ///
710    /// let mut buf = vec![];
711    /// buf.put_int(0x010203, 3);
712    /// assert_eq!(buf, b"\x01\x02\x03");
713    /// ```
714    ///
715    /// # Panics
716    ///
717    /// This function panics if there is not enough remaining capacity in
718    /// `self`.
719    #[inline]
720    fn put_int(&mut self, n: i64, nbytes: usize) {
721        self.put_slice(&n.to_be_bytes()[mem::size_of_val(&n) - nbytes..]);
722    }
723
724    /// Writes a signed n-byte integer to `self` in little-endian byte order.
725    ///
726    /// The current position is advanced by `nbytes`.
727    ///
728    /// # Examples
729    ///
730    /// ```
731    /// use ntex_bytes::BufMut;
732    ///
733    /// let mut buf = vec![];
734    /// buf.put_int_le(0x010203, 3);
735    /// assert_eq!(buf, b"\x03\x02\x01");
736    /// ```
737    ///
738    /// # Panics
739    ///
740    /// This function panics if there is not enough remaining capacity in
741    /// `self`.
742    #[inline]
743    fn put_int_le(&mut self, n: i64, nbytes: usize) {
744        self.put_slice(&n.to_le_bytes()[0..nbytes]);
745    }
746
747    /// Writes  an IEEE754 single-precision (4 bytes) floating point number to
748    /// `self` in big-endian byte order.
749    ///
750    /// The current position is advanced by 4.
751    ///
752    /// # Examples
753    ///
754    /// ```
755    /// use ntex_bytes::BufMut;
756    ///
757    /// let mut buf = vec![];
758    /// buf.put_f32(1.2f32);
759    /// assert_eq!(buf, b"\x3F\x99\x99\x9A");
760    /// ```
761    ///
762    /// # Panics
763    ///
764    /// This function panics if there is not enough remaining capacity in
765    /// `self`.
766    #[inline]
767    fn put_f32(&mut self, n: f32) {
768        self.put_u32(n.to_bits());
769    }
770
771    /// Writes  an IEEE754 single-precision (4 bytes) floating point number to
772    /// `self` in little-endian byte order.
773    ///
774    /// The current position is advanced by 4.
775    ///
776    /// # Examples
777    ///
778    /// ```
779    /// use ntex_bytes::BufMut;
780    ///
781    /// let mut buf = vec![];
782    /// buf.put_f32_le(1.2f32);
783    /// assert_eq!(buf, b"\x9A\x99\x99\x3F");
784    /// ```
785    ///
786    /// # Panics
787    ///
788    /// This function panics if there is not enough remaining capacity in
789    /// `self`.
790    #[inline]
791    fn put_f32_le(&mut self, n: f32) {
792        self.put_u32_le(n.to_bits());
793    }
794
795    /// Writes  an IEEE754 double-precision (8 bytes) floating point number to
796    /// `self` in big-endian byte order.
797    ///
798    /// The current position is advanced by 8.
799    ///
800    /// # Examples
801    ///
802    /// ```
803    /// use ntex_bytes::BufMut;
804    ///
805    /// let mut buf = vec![];
806    /// buf.put_f64(1.2f64);
807    /// assert_eq!(buf, b"\x3F\xF3\x33\x33\x33\x33\x33\x33");
808    /// ```
809    ///
810    /// # Panics
811    ///
812    /// This function panics if there is not enough remaining capacity in
813    /// `self`.
814    #[inline]
815    fn put_f64(&mut self, n: f64) {
816        self.put_u64(n.to_bits());
817    }
818
819    /// Writes  an IEEE754 double-precision (8 bytes) floating point number to
820    /// `self` in little-endian byte order.
821    ///
822    /// The current position is advanced by 8.
823    ///
824    /// # Examples
825    ///
826    /// ```
827    /// use ntex_bytes::BufMut;
828    ///
829    /// let mut buf = vec![];
830    /// buf.put_f64_le(1.2f64);
831    /// assert_eq!(buf, b"\x33\x33\x33\x33\x33\x33\xF3\x3F");
832    /// ```
833    ///
834    /// # Panics
835    ///
836    /// This function panics if there is not enough remaining capacity in
837    /// `self`.
838    #[inline]
839    fn put_f64_le(&mut self, n: f64) {
840        self.put_u64_le(n.to_bits());
841    }
842
843    /// Creates an adaptor which implements the `Write` trait for `self`.
844    ///
845    /// This function returns a new value which implements `Write` by adapting
846    /// the `Write` trait functions to the `BufMut` trait functions. Given that
847    /// `BufMut` operations are infallible, none of the `Write` functions will
848    /// return with `Err`.
849    ///
850    /// # Examples
851    ///
852    /// ```
853    /// use ntex_bytes::BufMut;
854    /// use std::io::Write;
855    ///
856    /// let mut buf = vec![].writer();
857    ///
858    /// let num = buf.write(&b"hello world"[..]).unwrap();
859    /// assert_eq!(11, num);
860    ///
861    /// let buf = buf.into_inner();
862    ///
863    /// assert_eq!(*buf, b"hello world"[..]);
864    /// ```
865    fn writer(self) -> Writer<Self>
866    where
867        Self: Sized,
868    {
869        super::writer::new(self)
870    }
871}
872
873impl<T: BufMut + ?Sized> BufMut for &mut T {
874    fn remaining_mut(&self) -> usize {
875        (**self).remaining_mut()
876    }
877
878    fn chunk_mut(&mut self) -> &mut UninitSlice {
879        (**self).chunk_mut()
880    }
881
882    unsafe fn advance_mut(&mut self, cnt: usize) {
883        (**self).advance_mut(cnt)
884    }
885}
886
887impl<T: BufMut + ?Sized> BufMut for Box<T> {
888    fn remaining_mut(&self) -> usize {
889        (**self).remaining_mut()
890    }
891
892    fn chunk_mut(&mut self) -> &mut UninitSlice {
893        (**self).chunk_mut()
894    }
895
896    unsafe fn advance_mut(&mut self, cnt: usize) {
897        (**self).advance_mut(cnt)
898    }
899}
900
901impl BufMut for Vec<u8> {
902    #[inline]
903    fn remaining_mut(&self) -> usize {
904        usize::MAX - self.len()
905    }
906
907    #[inline]
908    unsafe fn advance_mut(&mut self, cnt: usize) {
909        let len = self.len();
910        let remaining = self.capacity() - len;
911        if cnt > remaining {
912            // Reserve additional capacity, and ensure that the total length
913            // will not overflow usize.
914            self.reserve(cnt);
915        }
916
917        self.set_len(len + cnt);
918    }
919
920    #[inline]
921    fn chunk_mut(&mut self) -> &mut UninitSlice {
922        if self.capacity() == self.len() {
923            self.reserve(64); // Grow the vec
924        }
925
926        let cap = self.capacity();
927        let len = self.len();
928
929        let ptr = self.as_mut_ptr();
930        unsafe { &mut UninitSlice::from_raw_parts_mut(ptr, cap)[len..] }
931    }
932}
933
934impl BufMut for &mut [u8] {
935    #[inline]
936    fn remaining_mut(&self) -> usize {
937        self.len()
938    }
939
940    #[inline]
941    fn chunk_mut(&mut self) -> &mut UninitSlice {
942        // UninitSlice is repr(transparent), so safe to transmute
943        unsafe { &mut *(*self as *mut [u8] as *mut _) }
944    }
945
946    #[inline]
947    unsafe fn advance_mut(&mut self, cnt: usize) {
948        // Lifetime dance taken from `impl Write for &mut [u8]`.
949        let (_, b) = core::mem::take(self).split_at_mut(cnt);
950        *self = b;
951    }
952
953    #[inline]
954    fn put_slice(&mut self, src: &[u8]) {
955        self[..src.len()].copy_from_slice(src);
956        unsafe {
957            self.advance_mut(src.len());
958        }
959    }
960}
961
962// The existence of this function makes the compiler catch if the BufMut
963// trait is "object-safe" or not.
964fn _assert_trait_object(_b: &dyn BufMut) {}
965
966#[cfg(test)]
967#[allow(unused_allocation, warnings)]
968mod tests {
969    use super::*;
970    use crate::BytesMut;
971
972    #[test]
973    #[allow(clippy::needless_borrow)]
974    fn buf_mut_tests() {
975        let mut buf = vec![];
976        buf.put_u8(0x01);
977        assert_eq!(buf, b"\x01");
978
979        assert_eq!(buf.remaining_mut(), usize::MAX - 1);
980        assert_eq!((&buf).remaining_mut(), usize::MAX - 1);
981        assert_eq!(Box::new(buf).remaining_mut(), usize::MAX - 1);
982
983        let mut buf = [b'1'; 10];
984        let mut b = buf.as_mut();
985        assert_eq!(b.remaining_mut(), 10);
986        assert!(b.has_remaining_mut());
987        b.put_slice(b"123");
988        assert_eq!(&buf[..], b"1231111111");
989
990        let mut b: &mut [u8] = buf.as_mut();
991        let chunk = b.chunk_mut();
992        chunk.write_byte(0, b'9');
993        assert_eq!(&buf[..], b"9231111111");
994
995        let mut b = buf.as_mut();
996        let chunk = b.chunk_mut();
997        chunk.copy_from_slice(b"0000000000");
998        assert_eq!(&buf[..], b"0000000000");
999
1000        let mut b = buf.as_mut();
1001        assert_eq!(format!("{:?}", b.chunk_mut()), "UninitSlice[...]");
1002
1003        let b = buf.as_mut();
1004        let mut bb = Box::new(b);
1005        unsafe { bb.advance_mut(1) };
1006        let chunk = bb.chunk_mut();
1007        chunk.copy_from_slice(b"111111111");
1008        assert_eq!(&buf[..], b"0111111111");
1009
1010        let mut buf = BytesMut::new();
1011        buf.put_u8(0x01);
1012        assert_eq!(buf, b"\x01"[..]);
1013
1014        let mut buf = BytesMut::new();
1015        buf.put_u8(0x01);
1016        assert_eq!(buf, b"\x01"[..]);
1017
1018        let mut buf = vec![];
1019        buf.put_i8(0x01);
1020        assert_eq!(buf, b"\x01");
1021
1022        let mut buf = BytesMut::new();
1023        buf.put_i8(0x01);
1024        assert_eq!(buf, b"\x01"[..]);
1025
1026        let mut buf = BytesMut::new();
1027        buf.put_i8(0x01);
1028        assert_eq!(buf, b"\x01"[..]);
1029        assert_eq!((&mut buf).remaining_mut(), 107);
1030        let chunk = (&mut buf).chunk_mut();
1031        chunk.write_byte(0, b'9');
1032        unsafe { (&mut buf).advance_mut(1) };
1033        assert_eq!((&mut buf).remaining_mut(), 106);
1034
1035        let mut buf = vec![];
1036        buf.put_i16(0x0809);
1037        assert_eq!(buf, b"\x08\x09");
1038
1039        let mut buf = vec![];
1040        buf.put_i16_le(0x0809);
1041        assert_eq!(buf, b"\x09\x08");
1042
1043        let mut buf = vec![];
1044        buf.put_u32(0x0809A0A1);
1045        assert_eq!(buf, b"\x08\x09\xA0\xA1");
1046
1047        let mut buf = vec![];
1048        buf.put_i32(0x0809A0A1);
1049        assert_eq!(buf, b"\x08\x09\xA0\xA1");
1050
1051        let mut buf = vec![];
1052        buf.put_i32_le(0x0809A0A1);
1053        assert_eq!(buf, b"\xA1\xA0\x09\x08");
1054
1055        let mut buf = vec![];
1056        buf.put_u64(0x0102030405060708);
1057        assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
1058
1059        let mut buf = vec![];
1060        buf.put_u64_le(0x0102030405060708);
1061        assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
1062
1063        let mut buf = vec![];
1064        buf.put_i64(0x0102030405060708);
1065        assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
1066
1067        let mut buf = vec![];
1068        buf.put_i64_le(0x0102030405060708);
1069        assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
1070
1071        let mut buf = vec![];
1072        buf.put_u128(0x01020304050607080910111213141516);
1073        assert_eq!(
1074            buf,
1075            b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16"
1076        );
1077
1078        let mut buf = vec![];
1079        buf.put_u128_le(0x01020304050607080910111213141516);
1080        assert_eq!(
1081            buf,
1082            b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01"
1083        );
1084
1085        let mut buf = vec![];
1086        buf.put_i128(0x01020304050607080910111213141516);
1087        assert_eq!(
1088            buf,
1089            b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16"
1090        );
1091
1092        let mut buf = vec![];
1093        buf.put_i128_le(0x01020304050607080910111213141516);
1094        assert_eq!(
1095            buf,
1096            b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01"
1097        );
1098
1099        let mut buf = vec![];
1100        buf.put_uint(0x010203, 3);
1101        assert_eq!(buf, b"\x01\x02\x03");
1102
1103        let mut buf = vec![];
1104        buf.put_uint_le(0x010203, 3);
1105        assert_eq!(buf, b"\x03\x02\x01");
1106
1107        let mut buf = vec![];
1108        buf.put_int(0x010203, 3);
1109        assert_eq!(buf, b"\x01\x02\x03");
1110
1111        let mut buf = vec![];
1112        buf.put_int_le(0x010203, 3);
1113        assert_eq!(buf, b"\x03\x02\x01");
1114
1115        let mut buf = vec![];
1116        buf.put_f32(1.2f32);
1117        assert_eq!(buf, b"\x3F\x99\x99\x9A");
1118
1119        let mut buf = vec![];
1120        buf.put_f32_le(1.2f32);
1121        assert_eq!(buf, b"\x9A\x99\x99\x3F");
1122
1123        let mut buf = vec![];
1124        buf.put_f64(1.2f64);
1125        assert_eq!(buf, b"\x3F\xF3\x33\x33\x33\x33\x33\x33");
1126
1127        let mut buf = vec![];
1128        buf.put_f64_le(1.2f64);
1129        assert_eq!(buf, b"\x33\x33\x33\x33\x33\x33\xF3\x3F");
1130    }
1131}