1 use crate::buf::{limit, Chain, Limit, UninitSlice};
2 #[cfg(feature = "std")]
3 use crate::buf::{writer, Writer};
4 
5 use core::{cmp, mem, ptr, usize};
6 
7 use 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 /// ```
29 pub 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.
remaining_mut(&self) -> usize59     fn remaining_mut(&self) -> usize;
60 
61     /// Advance the internal cursor of the BufMut
62     ///
63     /// The next call to `chunk_mut` will return a slice starting `cnt` bytes
64     /// further into the underlying buffer.
65     ///
66     /// This function is unsafe because there is no guarantee that the bytes
67     /// being advanced past have been initialized.
68     ///
69     /// # Examples
70     ///
71     /// ```
72     /// use bytes::BufMut;
73     ///
74     /// let mut buf = Vec::with_capacity(16);
75     ///
76     /// // Write some data
77     /// buf.chunk_mut()[0..2].copy_from_slice(b"he");
78     /// unsafe { buf.advance_mut(2) };
79     ///
80     /// // write more bytes
81     /// buf.chunk_mut()[0..3].copy_from_slice(b"llo");
82     ///
83     /// unsafe { buf.advance_mut(3); }
84     ///
85     /// assert_eq!(5, buf.len());
86     /// assert_eq!(buf, b"hello");
87     /// ```
88     ///
89     /// # Panics
90     ///
91     /// This function **may** panic if `cnt > self.remaining_mut()`.
92     ///
93     /// # Implementer notes
94     ///
95     /// It is recommended for implementations of `advance_mut` to panic if
96     /// `cnt > self.remaining_mut()`. If the implementation does not panic,
97     /// the call must behave as if `cnt == self.remaining_mut()`.
98     ///
99     /// A call with `cnt == 0` should never panic and be a no-op.
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.chunk_mut()[0..].as_mut_ptr().write(b'h');
143     ///     buf.chunk_mut()[1..].as_mut_ptr().write(b'e');
144     ///
145     ///     buf.advance_mut(2);
146     ///
147     ///     buf.chunk_mut()[0..].as_mut_ptr().write(b'l');
148     ///     buf.chunk_mut()[1..].as_mut_ptr().write(b'l');
149     ///     buf.chunk_mut()[2..].as_mut_ptr().write(b'o');
150     ///
151     ///     buf.advance_mut(3);
152     /// }
153     ///
154     /// assert_eq!(5, buf.len());
155     /// assert_eq!(buf, b"hello");
156     /// ```
157     ///
158     /// # Implementer notes
159     ///
160     /// This function should never panic. `chunk_mut` should return an empty
161     /// slice **if and only if** `remaining_mut()` returns 0. In other words,
162     /// `chunk_mut()` returning an empty slice implies that `remaining_mut()` will
163     /// return 0 and `remaining_mut()` returning 0 implies that `chunk_mut()` will
164     /// return an empty slice.
165     ///
166     /// This function may trigger an out-of-memory abort if it tries to allocate
167     /// memory and fails to do so.
168     // The `chunk_mut` method was previously called `bytes_mut`. This alias makes the
169     // rename more easily discoverable.
170     #[cfg_attr(docsrs, doc(alias = "bytes_mut"))]
chunk_mut(&mut self) -> &mut UninitSlice171     fn chunk_mut(&mut self) -> &mut UninitSlice;
172 
173     /// Transfer bytes into `self` from `src` and advance the cursor by the
174     /// number of bytes written.
175     ///
176     /// # Examples
177     ///
178     /// ```
179     /// use bytes::BufMut;
180     ///
181     /// let mut buf = vec![];
182     ///
183     /// buf.put_u8(b'h');
184     /// buf.put(&b"ello"[..]);
185     /// buf.put(&b" world"[..]);
186     ///
187     /// assert_eq!(buf, b"hello world");
188     /// ```
189     ///
190     /// # Panics
191     ///
192     /// Panics if `self` does not have enough capacity to contain `src`.
put<T: super::Buf>(&mut self, mut src: T) where Self: Sized,193     fn put<T: super::Buf>(&mut self, mut src: T)
194     where
195         Self: Sized,
196     {
197         assert!(self.remaining_mut() >= src.remaining());
198 
199         while src.has_remaining() {
200             let l;
201 
202             unsafe {
203                 let s = src.chunk();
204                 let d = self.chunk_mut();
205                 l = cmp::min(s.len(), d.len());
206 
207                 ptr::copy_nonoverlapping(s.as_ptr(), d.as_mut_ptr() as *mut u8, l);
208             }
209 
210             src.advance(l);
211             unsafe {
212                 self.advance_mut(l);
213             }
214         }
215     }
216 
217     /// Transfer bytes into `self` from `src` and advance the cursor by the
218     /// number of bytes written.
219     ///
220     /// `self` must have enough remaining capacity to contain all of `src`.
221     ///
222     /// ```
223     /// use bytes::BufMut;
224     ///
225     /// let mut dst = [0; 6];
226     ///
227     /// {
228     ///     let mut buf = &mut dst[..];
229     ///     buf.put_slice(b"hello");
230     ///
231     ///     assert_eq!(1, buf.remaining_mut());
232     /// }
233     ///
234     /// assert_eq!(b"hello\0", &dst);
235     /// ```
put_slice(&mut self, src: &[u8])236     fn put_slice(&mut self, src: &[u8]) {
237         let mut off = 0;
238 
239         assert!(
240             self.remaining_mut() >= src.len(),
241             "buffer overflow; remaining = {}; src = {}",
242             self.remaining_mut(),
243             src.len()
244         );
245 
246         while off < src.len() {
247             let cnt;
248 
249             unsafe {
250                 let dst = self.chunk_mut();
251                 cnt = cmp::min(dst.len(), src.len() - off);
252 
253                 ptr::copy_nonoverlapping(src[off..].as_ptr(), dst.as_mut_ptr() as *mut u8, cnt);
254 
255                 off += cnt;
256             }
257 
258             unsafe {
259                 self.advance_mut(cnt);
260             }
261         }
262     }
263 
264     /// Put `cnt` bytes `val` into `self`.
265     ///
266     /// Logically equivalent to calling `self.put_u8(val)` `cnt` times, but may work faster.
267     ///
268     /// `self` must have at least `cnt` remaining capacity.
269     ///
270     /// ```
271     /// use bytes::BufMut;
272     ///
273     /// let mut dst = [0; 6];
274     ///
275     /// {
276     ///     let mut buf = &mut dst[..];
277     ///     buf.put_bytes(b'a', 4);
278     ///
279     ///     assert_eq!(2, buf.remaining_mut());
280     /// }
281     ///
282     /// assert_eq!(b"aaaa\0\0", &dst);
283     /// ```
284     ///
285     /// # Panics
286     ///
287     /// This function panics if there is not enough remaining capacity in
288     /// `self`.
put_bytes(&mut self, val: u8, cnt: usize)289     fn put_bytes(&mut self, val: u8, cnt: usize) {
290         for _ in 0..cnt {
291             self.put_u8(val);
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 low `nbytes` of a signed 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(0x0504010203, 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` or if `nbytes` is greater than 8.
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 low `nbytes` of a signed 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(0x0504010203, 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` or if `nbytes` is greater than 8.
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     /// Creates an adaptor which can write at most `limit` bytes to `self`.
874     ///
875     /// # Examples
876     ///
877     /// ```
878     /// use bytes::BufMut;
879     ///
880     /// let arr = &mut [0u8; 128][..];
881     /// assert_eq!(arr.remaining_mut(), 128);
882     ///
883     /// let dst = arr.limit(10);
884     /// assert_eq!(dst.remaining_mut(), 10);
885     /// ```
limit(self, limit: usize) -> Limit<Self> where Self: Sized,886     fn limit(self, limit: usize) -> Limit<Self>
887     where
888         Self: Sized,
889     {
890         limit::new(self, limit)
891     }
892 
893     /// Creates an adaptor which implements the `Write` trait for `self`.
894     ///
895     /// This function returns a new value which implements `Write` by adapting
896     /// the `Write` trait functions to the `BufMut` trait functions. Given that
897     /// `BufMut` operations are infallible, none of the `Write` functions will
898     /// return with `Err`.
899     ///
900     /// # Examples
901     ///
902     /// ```
903     /// use bytes::BufMut;
904     /// use std::io::Write;
905     ///
906     /// let mut buf = vec![].writer();
907     ///
908     /// let num = buf.write(&b"hello world"[..]).unwrap();
909     /// assert_eq!(11, num);
910     ///
911     /// let buf = buf.into_inner();
912     ///
913     /// assert_eq!(*buf, b"hello world"[..]);
914     /// ```
915     #[cfg(feature = "std")]
writer(self) -> Writer<Self> where Self: Sized,916     fn writer(self) -> Writer<Self>
917     where
918         Self: Sized,
919     {
920         writer::new(self)
921     }
922 
923     /// Creates an adapter which will chain this buffer with another.
924     ///
925     /// The returned `BufMut` instance will first write to all bytes from
926     /// `self`. Afterwards, it will write to `next`.
927     ///
928     /// # Examples
929     ///
930     /// ```
931     /// use bytes::BufMut;
932     ///
933     /// let mut a = [0u8; 5];
934     /// let mut b = [0u8; 6];
935     ///
936     /// let mut chain = (&mut a[..]).chain_mut(&mut b[..]);
937     ///
938     /// chain.put_slice(b"hello world");
939     ///
940     /// assert_eq!(&a[..], b"hello");
941     /// assert_eq!(&b[..], b" world");
942     /// ```
chain_mut<U: BufMut>(self, next: U) -> Chain<Self, U> where Self: Sized,943     fn chain_mut<U: BufMut>(self, next: U) -> Chain<Self, U>
944     where
945         Self: Sized,
946     {
947         Chain::new(self, next)
948     }
949 }
950 
951 macro_rules! deref_forward_bufmut {
952     () => {
953         fn remaining_mut(&self) -> usize {
954             (**self).remaining_mut()
955         }
956 
957         fn chunk_mut(&mut self) -> &mut UninitSlice {
958             (**self).chunk_mut()
959         }
960 
961         unsafe fn advance_mut(&mut self, cnt: usize) {
962             (**self).advance_mut(cnt)
963         }
964 
965         fn put_slice(&mut self, src: &[u8]) {
966             (**self).put_slice(src)
967         }
968 
969         fn put_u8(&mut self, n: u8) {
970             (**self).put_u8(n)
971         }
972 
973         fn put_i8(&mut self, n: i8) {
974             (**self).put_i8(n)
975         }
976 
977         fn put_u16(&mut self, n: u16) {
978             (**self).put_u16(n)
979         }
980 
981         fn put_u16_le(&mut self, n: u16) {
982             (**self).put_u16_le(n)
983         }
984 
985         fn put_i16(&mut self, n: i16) {
986             (**self).put_i16(n)
987         }
988 
989         fn put_i16_le(&mut self, n: i16) {
990             (**self).put_i16_le(n)
991         }
992 
993         fn put_u32(&mut self, n: u32) {
994             (**self).put_u32(n)
995         }
996 
997         fn put_u32_le(&mut self, n: u32) {
998             (**self).put_u32_le(n)
999         }
1000 
1001         fn put_i32(&mut self, n: i32) {
1002             (**self).put_i32(n)
1003         }
1004 
1005         fn put_i32_le(&mut self, n: i32) {
1006             (**self).put_i32_le(n)
1007         }
1008 
1009         fn put_u64(&mut self, n: u64) {
1010             (**self).put_u64(n)
1011         }
1012 
1013         fn put_u64_le(&mut self, n: u64) {
1014             (**self).put_u64_le(n)
1015         }
1016 
1017         fn put_i64(&mut self, n: i64) {
1018             (**self).put_i64(n)
1019         }
1020 
1021         fn put_i64_le(&mut self, n: i64) {
1022             (**self).put_i64_le(n)
1023         }
1024     };
1025 }
1026 
1027 unsafe impl<T: BufMut + ?Sized> BufMut for &mut T {
1028     deref_forward_bufmut!();
1029 }
1030 
1031 unsafe impl<T: BufMut + ?Sized> BufMut for Box<T> {
1032     deref_forward_bufmut!();
1033 }
1034 
1035 unsafe impl BufMut for &mut [u8] {
1036     #[inline]
remaining_mut(&self) -> usize1037     fn remaining_mut(&self) -> usize {
1038         self.len()
1039     }
1040 
1041     #[inline]
chunk_mut(&mut self) -> &mut UninitSlice1042     fn chunk_mut(&mut self) -> &mut UninitSlice {
1043         // UninitSlice is repr(transparent), so safe to transmute
1044         unsafe { &mut *(*self as *mut [u8] as *mut _) }
1045     }
1046 
1047     #[inline]
advance_mut(&mut self, cnt: usize)1048     unsafe fn advance_mut(&mut self, cnt: usize) {
1049         // Lifetime dance taken from `impl Write for &mut [u8]`.
1050         let (_, b) = core::mem::replace(self, &mut []).split_at_mut(cnt);
1051         *self = b;
1052     }
1053 
1054     #[inline]
put_slice(&mut self, src: &[u8])1055     fn put_slice(&mut self, src: &[u8]) {
1056         self[..src.len()].copy_from_slice(src);
1057         unsafe {
1058             self.advance_mut(src.len());
1059         }
1060     }
1061 
put_bytes(&mut self, val: u8, cnt: usize)1062     fn put_bytes(&mut self, val: u8, cnt: usize) {
1063         assert!(self.remaining_mut() >= cnt);
1064         unsafe {
1065             ptr::write_bytes(self.as_mut_ptr(), val, cnt);
1066             self.advance_mut(cnt);
1067         }
1068     }
1069 }
1070 
1071 unsafe impl BufMut for Vec<u8> {
1072     #[inline]
remaining_mut(&self) -> usize1073     fn remaining_mut(&self) -> usize {
1074         // A vector can never have more than isize::MAX bytes
1075         core::isize::MAX as usize - self.len()
1076     }
1077 
1078     #[inline]
advance_mut(&mut self, cnt: usize)1079     unsafe fn advance_mut(&mut self, cnt: usize) {
1080         let len = self.len();
1081         let remaining = self.capacity() - len;
1082 
1083         assert!(
1084             cnt <= remaining,
1085             "cannot advance past `remaining_mut`: {:?} <= {:?}",
1086             cnt,
1087             remaining
1088         );
1089 
1090         self.set_len(len + cnt);
1091     }
1092 
1093     #[inline]
chunk_mut(&mut self) -> &mut UninitSlice1094     fn chunk_mut(&mut self) -> &mut UninitSlice {
1095         if self.capacity() == self.len() {
1096             self.reserve(64); // Grow the vec
1097         }
1098 
1099         let cap = self.capacity();
1100         let len = self.len();
1101 
1102         let ptr = self.as_mut_ptr();
1103         unsafe { &mut UninitSlice::from_raw_parts_mut(ptr, cap)[len..] }
1104     }
1105 
1106     // Specialize these methods so they can skip checking `remaining_mut`
1107     // and `advance_mut`.
put<T: super::Buf>(&mut self, mut src: T) where Self: Sized,1108     fn put<T: super::Buf>(&mut self, mut src: T)
1109     where
1110         Self: Sized,
1111     {
1112         // In case the src isn't contiguous, reserve upfront
1113         self.reserve(src.remaining());
1114 
1115         while src.has_remaining() {
1116             let l;
1117 
1118             // a block to contain the src.bytes() borrow
1119             {
1120                 let s = src.chunk();
1121                 l = s.len();
1122                 self.extend_from_slice(s);
1123             }
1124 
1125             src.advance(l);
1126         }
1127     }
1128 
1129     #[inline]
put_slice(&mut self, src: &[u8])1130     fn put_slice(&mut self, src: &[u8]) {
1131         self.extend_from_slice(src);
1132     }
1133 
put_bytes(&mut self, val: u8, cnt: usize)1134     fn put_bytes(&mut self, val: u8, cnt: usize) {
1135         let new_len = self.len().checked_add(cnt).unwrap();
1136         self.resize(new_len, val);
1137     }
1138 }
1139 
1140 // The existence of this function makes the compiler catch if the BufMut
1141 // trait is "object-safe" or not.
_assert_trait_object(_b: &dyn BufMut)1142 fn _assert_trait_object(_b: &dyn BufMut) {}
1143