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