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