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