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