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