tiny_artnet_bytes_no_atomic/buf/
buf_mut.rs

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