1 use super::{IntoBuf, Writer};
2 use byteorder::{LittleEndian, ByteOrder, BigEndian};
3 use iovec::IoVec;
4 
5 use std::{cmp, io, ptr, usize};
6 
7 /// A trait for values that provide sequential write access to bytes.
8 ///
9 /// Write bytes to a buffer
10 ///
11 /// A buffer stores bytes in memory such that write operations are infallible.
12 /// The underlying storage may or may not be in contiguous memory. A `BufMut`
13 /// value is a cursor into the buffer. Writing to `BufMut` advances the cursor
14 /// position.
15 ///
16 /// The simplest `BufMut` is a `Vec<u8>`.
17 ///
18 /// ```
19 /// use bytes::BufMut;
20 ///
21 /// let mut buf = vec![];
22 ///
23 /// buf.put("hello world");
24 ///
25 /// assert_eq!(buf, b"hello world");
26 /// ```
27 pub trait BufMut {
28     /// Returns the number of bytes that can be written from the current
29     /// position until the end of the buffer is reached.
30     ///
31     /// This value is greater than or equal to the length of the slice returned
32     /// by `bytes_mut`.
33     ///
34     /// # Examples
35     ///
36     /// ```
37     /// use bytes::BufMut;
38     /// use std::io::Cursor;
39     ///
40     /// let mut dst = [0; 10];
41     /// let mut buf = Cursor::new(&mut dst[..]);
42     ///
43     /// assert_eq!(10, buf.remaining_mut());
44     /// buf.put("hello");
45     ///
46     /// assert_eq!(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     ///     buf.bytes_mut()[0] = b'h';
73     ///     buf.bytes_mut()[1] = b'e';
74     ///
75     ///     buf.advance_mut(2);
76     ///
77     ///     buf.bytes_mut()[0] = b'l';
78     ///     buf.bytes_mut()[1..3].copy_from_slice(b"lo");
79     ///
80     ///     buf.advance_mut(3);
81     /// }
82     ///
83     /// assert_eq!(5, buf.len());
84     /// assert_eq!(buf, b"hello");
85     /// ```
86     ///
87     /// # Panics
88     ///
89     /// This function **may** panic if `cnt > self.remaining_mut()`.
90     ///
91     /// # Implementer notes
92     ///
93     /// It is recommended for implementations of `advance_mut` to panic if
94     /// `cnt > self.remaining_mut()`. If the implementation does not panic,
95     /// the call must behave as if `cnt == self.remaining_mut()`.
96     ///
97     /// A call with `cnt == 0` should never panic and be a no-op.
advance_mut(&mut self, cnt: usize)98     unsafe fn advance_mut(&mut self, cnt: usize);
99 
100     /// Returns true if there is space in `self` for more bytes.
101     ///
102     /// This is equivalent to `self.remaining_mut() != 0`.
103     ///
104     /// # Examples
105     ///
106     /// ```
107     /// use bytes::BufMut;
108     /// use std::io::Cursor;
109     ///
110     /// let mut dst = [0; 5];
111     /// let mut buf = Cursor::new(&mut dst);
112     ///
113     /// assert!(buf.has_remaining_mut());
114     ///
115     /// buf.put("hello");
116     ///
117     /// assert!(!buf.has_remaining_mut());
118     /// ```
has_remaining_mut(&self) -> bool119     fn has_remaining_mut(&self) -> bool {
120         self.remaining_mut() > 0
121     }
122 
123     /// Returns a mutable slice starting at the current BufMut position and of
124     /// length between 0 and `BufMut::remaining_mut()`.
125     ///
126     /// This is a lower level function. Most operations are done with other
127     /// functions.
128     ///
129     /// The returned byte slice may represent uninitialized memory.
130     ///
131     /// # Examples
132     ///
133     /// ```
134     /// use bytes::BufMut;
135     ///
136     /// let mut buf = Vec::with_capacity(16);
137     ///
138     /// unsafe {
139     ///     buf.bytes_mut()[0] = b'h';
140     ///     buf.bytes_mut()[1] = b'e';
141     ///
142     ///     buf.advance_mut(2);
143     ///
144     ///     buf.bytes_mut()[0] = b'l';
145     ///     buf.bytes_mut()[1..3].copy_from_slice(b"lo");
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. `bytes_mut` should return an empty
157     /// slice **if and only if** `remaining_mut` returns 0. In other words,
158     /// `bytes_mut` returning an empty slice implies that `remaining_mut` will
159     /// return 0 and `remaining_mut` returning 0 implies that `bytes_mut` will
160     /// return an empty slice.
bytes_mut(&mut self) -> &mut [u8]161     unsafe fn bytes_mut(&mut self) -> &mut [u8];
162 
163     /// Fills `dst` with potentially multiple mutable slices starting at `self`'s
164     /// current position.
165     ///
166     /// If the `BufMut` is backed by disjoint slices of bytes, `bytes_vec_mut`
167     /// enables fetching more than one slice at once. `dst` is a slice of
168     /// mutable `IoVec` references, enabling the slice to be directly used with
169     /// [`readv`] without any further conversion. The sum of the lengths of all
170     /// the buffers in `dst` will be less than or equal to
171     /// `Buf::remaining_mut()`.
172     ///
173     /// The entries in `dst` will be overwritten, but the data **contained** by
174     /// the slices **will not** be modified. If `bytes_vec_mut` does not fill every
175     /// entry in `dst`, then `dst` is guaranteed to contain all remaining slices
176     /// in `self.
177     ///
178     /// This is a lower level function. Most operations are done with other
179     /// functions.
180     ///
181     /// # Implementer notes
182     ///
183     /// This function should never panic. Once the end of the buffer is reached,
184     /// i.e., `BufMut::remaining_mut` returns 0, calls to `bytes_vec_mut` must
185     /// return 0 without mutating `dst`.
186     ///
187     /// Implementations should also take care to properly handle being called
188     /// with `dst` being a zero length slice.
189     ///
190     /// [`readv`]: http://man7.org/linux/man-pages/man2/readv.2.html
bytes_vec_mut<'a>(&'a mut self, dst: &mut [&'a mut IoVec]) -> usize191     unsafe fn bytes_vec_mut<'a>(&'a mut self, dst: &mut [&'a mut IoVec]) -> usize {
192         if dst.is_empty() {
193             return 0;
194         }
195 
196         if self.has_remaining_mut() {
197             dst[0] = self.bytes_mut().into();
198             1
199         } else {
200             0
201         }
202     }
203 
204     /// Transfer bytes into `self` from `src` and advance the cursor by the
205     /// number of bytes written.
206     ///
207     /// # Examples
208     ///
209     /// ```
210     /// use bytes::BufMut;
211     ///
212     /// let mut buf = vec![];
213     ///
214     /// buf.put(b'h');
215     /// buf.put(&b"ello"[..]);
216     /// buf.put(" world");
217     ///
218     /// assert_eq!(buf, b"hello world");
219     /// ```
220     ///
221     /// # Panics
222     ///
223     /// Panics if `self` does not have enough capacity to contain `src`.
put<T: IntoBuf>(&mut self, src: T) where Self: Sized224     fn put<T: IntoBuf>(&mut self, src: T) where Self: Sized {
225         use super::Buf;
226 
227         let mut src = src.into_buf();
228 
229         assert!(self.remaining_mut() >= src.remaining());
230 
231         while src.has_remaining() {
232             let l;
233 
234             unsafe {
235                 let s = src.bytes();
236                 let d = self.bytes_mut();
237                 l = cmp::min(s.len(), d.len());
238 
239                 ptr::copy_nonoverlapping(
240                     s.as_ptr(),
241                     d.as_mut_ptr(),
242                     l);
243             }
244 
245             src.advance(l);
246             unsafe { self.advance_mut(l); }
247         }
248     }
249 
250     /// Transfer bytes into `self` from `src` and advance the cursor by the
251     /// number of bytes written.
252     ///
253     /// `self` must have enough remaining capacity to contain all of `src`.
254     ///
255     /// ```
256     /// use bytes::BufMut;
257     /// use std::io::Cursor;
258     ///
259     /// let mut dst = [0; 6];
260     ///
261     /// {
262     ///     let mut buf = Cursor::new(&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");
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(),
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     #[doc(hidden)]
342     #[deprecated(note="use put_u16_be or put_u16_le")]
put_u16<T: ByteOrder>(&mut self, n: u16) where Self: Sized343     fn put_u16<T: ByteOrder>(&mut self, n: u16) where Self: Sized {
344         let mut buf = [0; 2];
345         T::write_u16(&mut buf, n);
346         self.put_slice(&buf)
347     }
348 
349     /// Writes an unsigned 16 bit integer to `self` in big-endian byte order.
350     ///
351     /// The current position is advanced by 2.
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// use bytes::BufMut;
357     ///
358     /// let mut buf = vec![];
359     /// buf.put_u16_be(0x0809);
360     /// assert_eq!(buf, b"\x08\x09");
361     /// ```
362     ///
363     /// # Panics
364     ///
365     /// This function panics if there is not enough remaining capacity in
366     /// `self`.
put_u16_be(&mut self, n: u16)367     fn put_u16_be(&mut self, n: u16) {
368         let mut buf = [0; 2];
369         BigEndian::write_u16(&mut buf, n);
370         self.put_slice(&buf)
371     }
372 
373     /// Writes an unsigned 16 bit integer to `self` in little-endian byte order.
374     ///
375     /// The current position is advanced by 2.
376     ///
377     /// # Examples
378     ///
379     /// ```
380     /// use bytes::BufMut;
381     ///
382     /// let mut buf = vec![];
383     /// buf.put_u16_le(0x0809);
384     /// assert_eq!(buf, b"\x09\x08");
385     /// ```
386     ///
387     /// # Panics
388     ///
389     /// This function panics if there is not enough remaining capacity in
390     /// `self`.
put_u16_le(&mut self, n: u16)391     fn put_u16_le(&mut self, n: u16) {
392         let mut buf = [0; 2];
393         LittleEndian::write_u16(&mut buf, n);
394         self.put_slice(&buf)
395     }
396 
397     #[doc(hidden)]
398     #[deprecated(note="use put_i16_be or put_i16_le")]
put_i16<T: ByteOrder>(&mut self, n: i16) where Self: Sized399     fn put_i16<T: ByteOrder>(&mut self, n: i16) where Self: Sized {
400         let mut buf = [0; 2];
401         T::write_i16(&mut buf, n);
402         self.put_slice(&buf)
403     }
404 
405     /// Writes a signed 16 bit integer to `self` in big-endian byte order.
406     ///
407     /// The current position is advanced by 2.
408     ///
409     /// # Examples
410     ///
411     /// ```
412     /// use bytes::BufMut;
413     ///
414     /// let mut buf = vec![];
415     /// buf.put_i16_be(0x0809);
416     /// assert_eq!(buf, b"\x08\x09");
417     /// ```
418     ///
419     /// # Panics
420     ///
421     /// This function panics if there is not enough remaining capacity in
422     /// `self`.
put_i16_be(&mut self, n: i16)423     fn put_i16_be(&mut self, n: i16) {
424         let mut buf = [0; 2];
425         BigEndian::write_i16(&mut buf, n);
426         self.put_slice(&buf)
427     }
428 
429     /// Writes a signed 16 bit integer to `self` in little-endian byte order.
430     ///
431     /// The current position is advanced by 2.
432     ///
433     /// # Examples
434     ///
435     /// ```
436     /// use bytes::BufMut;
437     ///
438     /// let mut buf = vec![];
439     /// buf.put_i16_le(0x0809);
440     /// assert_eq!(buf, b"\x09\x08");
441     /// ```
442     ///
443     /// # Panics
444     ///
445     /// This function panics if there is not enough remaining capacity in
446     /// `self`.
put_i16_le(&mut self, n: i16)447     fn put_i16_le(&mut self, n: i16) {
448         let mut buf = [0; 2];
449         LittleEndian::write_i16(&mut buf, n);
450         self.put_slice(&buf)
451     }
452 
453     #[doc(hidden)]
454     #[deprecated(note="use put_u32_be or put_u32_le")]
put_u32<T: ByteOrder>(&mut self, n: u32) where Self: Sized455     fn put_u32<T: ByteOrder>(&mut self, n: u32) where Self: Sized {
456         let mut buf = [0; 4];
457         T::write_u32(&mut buf, n);
458         self.put_slice(&buf)
459     }
460 
461     /// Writes an unsigned 32 bit integer to `self` in big-endian byte order.
462     ///
463     /// The current position is advanced by 4.
464     ///
465     /// # Examples
466     ///
467     /// ```
468     /// use bytes::BufMut;
469     ///
470     /// let mut buf = vec![];
471     /// buf.put_u32_be(0x0809A0A1);
472     /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
473     /// ```
474     ///
475     /// # Panics
476     ///
477     /// This function panics if there is not enough remaining capacity in
478     /// `self`.
put_u32_be(&mut self, n: u32)479     fn put_u32_be(&mut self, n: u32) {
480         let mut buf = [0; 4];
481         BigEndian::write_u32(&mut buf, n);
482         self.put_slice(&buf)
483     }
484 
485     /// Writes an unsigned 32 bit integer to `self` in little-endian byte order.
486     ///
487     /// The current position is advanced by 4.
488     ///
489     /// # Examples
490     ///
491     /// ```
492     /// use bytes::BufMut;
493     ///
494     /// let mut buf = vec![];
495     /// buf.put_u32_le(0x0809A0A1);
496     /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
497     /// ```
498     ///
499     /// # Panics
500     ///
501     /// This function panics if there is not enough remaining capacity in
502     /// `self`.
put_u32_le(&mut self, n: u32)503     fn put_u32_le(&mut self, n: u32) {
504         let mut buf = [0; 4];
505         LittleEndian::write_u32(&mut buf, n);
506         self.put_slice(&buf)
507     }
508 
509     #[doc(hidden)]
510     #[deprecated(note="use put_i32_be or put_i32_le")]
put_i32<T: ByteOrder>(&mut self, n: i32) where Self: Sized511     fn put_i32<T: ByteOrder>(&mut self, n: i32) where Self: Sized {
512         let mut buf = [0; 4];
513         T::write_i32(&mut buf, n);
514         self.put_slice(&buf)
515     }
516 
517     /// Writes a signed 32 bit integer to `self` in big-endian byte order.
518     ///
519     /// The current position is advanced by 4.
520     ///
521     /// # Examples
522     ///
523     /// ```
524     /// use bytes::BufMut;
525     ///
526     /// let mut buf = vec![];
527     /// buf.put_i32_be(0x0809A0A1);
528     /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
529     /// ```
530     ///
531     /// # Panics
532     ///
533     /// This function panics if there is not enough remaining capacity in
534     /// `self`.
put_i32_be(&mut self, n: i32)535     fn put_i32_be(&mut self, n: i32) {
536         let mut buf = [0; 4];
537         BigEndian::write_i32(&mut buf, n);
538         self.put_slice(&buf)
539     }
540 
541     /// Writes a signed 32 bit integer to `self` in little-endian byte order.
542     ///
543     /// The current position is advanced by 4.
544     ///
545     /// # Examples
546     ///
547     /// ```
548     /// use bytes::BufMut;
549     ///
550     /// let mut buf = vec![];
551     /// buf.put_i32_le(0x0809A0A1);
552     /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
553     /// ```
554     ///
555     /// # Panics
556     ///
557     /// This function panics if there is not enough remaining capacity in
558     /// `self`.
put_i32_le(&mut self, n: i32)559     fn put_i32_le(&mut self, n: i32) {
560         let mut buf = [0; 4];
561         LittleEndian::write_i32(&mut buf, n);
562         self.put_slice(&buf)
563     }
564 
565     #[doc(hidden)]
566     #[deprecated(note="use put_u64_be or put_u64_le")]
put_u64<T: ByteOrder>(&mut self, n: u64) where Self: Sized567     fn put_u64<T: ByteOrder>(&mut self, n: u64) where Self: Sized {
568         let mut buf = [0; 8];
569         T::write_u64(&mut buf, n);
570         self.put_slice(&buf)
571     }
572 
573     /// Writes an unsigned 64 bit integer to `self` in the big-endian byte order.
574     ///
575     /// The current position is advanced by 8.
576     ///
577     /// # Examples
578     ///
579     /// ```
580     /// use bytes::BufMut;
581     ///
582     /// let mut buf = vec![];
583     /// buf.put_u64_be(0x0102030405060708);
584     /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
585     /// ```
586     ///
587     /// # Panics
588     ///
589     /// This function panics if there is not enough remaining capacity in
590     /// `self`.
put_u64_be(&mut self, n: u64)591     fn put_u64_be(&mut self, n: u64) {
592         let mut buf = [0; 8];
593         BigEndian::write_u64(&mut buf, n);
594         self.put_slice(&buf)
595     }
596 
597     /// Writes an unsigned 64 bit integer to `self` in little-endian byte order.
598     ///
599     /// The current position is advanced by 8.
600     ///
601     /// # Examples
602     ///
603     /// ```
604     /// use bytes::BufMut;
605     ///
606     /// let mut buf = vec![];
607     /// buf.put_u64_le(0x0102030405060708);
608     /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
609     /// ```
610     ///
611     /// # Panics
612     ///
613     /// This function panics if there is not enough remaining capacity in
614     /// `self`.
put_u64_le(&mut self, n: u64)615     fn put_u64_le(&mut self, n: u64) {
616         let mut buf = [0; 8];
617         LittleEndian::write_u64(&mut buf, n);
618         self.put_slice(&buf)
619     }
620 
621     #[doc(hidden)]
622     #[deprecated(note="use put_i64_be or put_i64_le")]
put_i64<T: ByteOrder>(&mut self, n: i64) where Self: Sized623     fn put_i64<T: ByteOrder>(&mut self, n: i64) where Self: Sized {
624         let mut buf = [0; 8];
625         T::write_i64(&mut buf, n);
626         self.put_slice(&buf)
627     }
628 
629     /// Writes a signed 64 bit integer to `self` in the big-endian byte order.
630     ///
631     /// The current position is advanced by 8.
632     ///
633     /// # Examples
634     ///
635     /// ```
636     /// use bytes::BufMut;
637     ///
638     /// let mut buf = vec![];
639     /// buf.put_i64_be(0x0102030405060708);
640     /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
641     /// ```
642     ///
643     /// # Panics
644     ///
645     /// This function panics if there is not enough remaining capacity in
646     /// `self`.
put_i64_be(&mut self, n: i64)647     fn put_i64_be(&mut self, n: i64) {
648         let mut buf = [0; 8];
649         BigEndian::write_i64(&mut buf, n);
650         self.put_slice(&buf)
651     }
652 
653     /// Writes a signed 64 bit integer to `self` in little-endian byte order.
654     ///
655     /// The current position is advanced by 8.
656     ///
657     /// # Examples
658     ///
659     /// ```
660     /// use bytes::BufMut;
661     ///
662     /// let mut buf = vec![];
663     /// buf.put_i64_le(0x0102030405060708);
664     /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
665     /// ```
666     ///
667     /// # Panics
668     ///
669     /// This function panics if there is not enough remaining capacity in
670     /// `self`.
put_i64_le(&mut self, n: i64)671     fn put_i64_le(&mut self, n: i64) {
672         let mut buf = [0; 8];
673         LittleEndian::write_i64(&mut buf, n);
674         self.put_slice(&buf)
675     }
676 
677     /// Writes an unsigned 128 bit integer to `self` in the big-endian byte order.
678     ///
679     /// **NOTE:** This method requires the `i128` feature.
680     /// The current position is advanced by 16.
681     ///
682     /// # Examples
683     ///
684     /// ```
685     /// use bytes::BufMut;
686     ///
687     /// let mut buf = vec![];
688     /// buf.put_u128_be(0x01020304050607080910111213141516);
689     /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
690     /// ```
691     ///
692     /// # Panics
693     ///
694     /// This function panics if there is not enough remaining capacity in
695     /// `self`.
696     #[cfg(feature = "i128")]
put_u128_be(&mut self, n: u128)697     fn put_u128_be(&mut self, n: u128) {
698         let mut buf = [0; 16];
699         BigEndian::write_u128(&mut buf, n);
700         self.put_slice(&buf)
701     }
702 
703     /// Writes an unsigned 128 bit integer to `self` in little-endian byte order.
704     ///
705     /// **NOTE:** This method requires the `i128` feature.
706     /// The current position is advanced by 16.
707     ///
708     /// # Examples
709     ///
710     /// ```
711     /// use bytes::BufMut;
712     ///
713     /// let mut buf = vec![];
714     /// buf.put_u128_le(0x01020304050607080910111213141516);
715     /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
716     /// ```
717     ///
718     /// # Panics
719     ///
720     /// This function panics if there is not enough remaining capacity in
721     /// `self`.
722     #[cfg(feature = "i128")]
put_u128_le(&mut self, n: u128)723     fn put_u128_le(&mut self, n: u128) {
724         let mut buf = [0; 16];
725         LittleEndian::write_u128(&mut buf, n);
726         self.put_slice(&buf)
727     }
728 
729     /// Writes a signed 128 bit integer to `self` in the big-endian byte order.
730     ///
731     /// **NOTE:** This method requires the `i128` feature.
732     /// The current position is advanced by 16.
733     ///
734     /// # Examples
735     ///
736     /// ```
737     /// use bytes::BufMut;
738     ///
739     /// let mut buf = vec![];
740     /// buf.put_i128_be(0x01020304050607080910111213141516);
741     /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
742     /// ```
743     ///
744     /// # Panics
745     ///
746     /// This function panics if there is not enough remaining capacity in
747     /// `self`.
748     #[cfg(feature = "i128")]
put_i128_be(&mut self, n: i128)749     fn put_i128_be(&mut self, n: i128) {
750         let mut buf = [0; 16];
751         BigEndian::write_i128(&mut buf, n);
752         self.put_slice(&buf)
753     }
754 
755     /// Writes a signed 128 bit integer to `self` in little-endian byte order.
756     ///
757     /// **NOTE:** This method requires the `i128` feature.
758     /// The current position is advanced by 16.
759     ///
760     /// # Examples
761     ///
762     /// ```
763     /// use bytes::BufMut;
764     ///
765     /// let mut buf = vec![];
766     /// buf.put_i128_le(0x01020304050607080910111213141516);
767     /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
768     /// ```
769     ///
770     /// # Panics
771     ///
772     /// This function panics if there is not enough remaining capacity in
773     /// `self`.
774     #[cfg(feature = "i128")]
put_i128_le(&mut self, n: i128)775     fn put_i128_le(&mut self, n: i128) {
776         let mut buf = [0; 16];
777         LittleEndian::write_i128(&mut buf, n);
778         self.put_slice(&buf)
779     }
780 
781     #[doc(hidden)]
782     #[deprecated(note="use put_uint_be or put_uint_le")]
put_uint<T: ByteOrder>(&mut self, n: u64, nbytes: usize) where Self: Sized783     fn put_uint<T: ByteOrder>(&mut self, n: u64, nbytes: usize) where Self: Sized {
784         let mut buf = [0; 8];
785         T::write_uint(&mut buf, n, nbytes);
786         self.put_slice(&buf[0..nbytes])
787     }
788 
789     /// Writes an unsigned n-byte integer to `self` in big-endian byte order.
790     ///
791     /// The current position is advanced by `nbytes`.
792     ///
793     /// # Examples
794     ///
795     /// ```
796     /// use bytes::BufMut;
797     ///
798     /// let mut buf = vec![];
799     /// buf.put_uint_be(0x010203, 3);
800     /// assert_eq!(buf, b"\x01\x02\x03");
801     /// ```
802     ///
803     /// # Panics
804     ///
805     /// This function panics if there is not enough remaining capacity in
806     /// `self`.
put_uint_be(&mut self, n: u64, nbytes: usize)807     fn put_uint_be(&mut self, n: u64, nbytes: usize) {
808         let mut buf = [0; 8];
809         BigEndian::write_uint(&mut buf, n, nbytes);
810         self.put_slice(&buf[0..nbytes])
811     }
812 
813     /// Writes an unsigned n-byte integer to `self` in the little-endian byte order.
814     ///
815     /// The current position is advanced by `nbytes`.
816     ///
817     /// # Examples
818     ///
819     /// ```
820     /// use bytes::BufMut;
821     ///
822     /// let mut buf = vec![];
823     /// buf.put_uint_le(0x010203, 3);
824     /// assert_eq!(buf, b"\x03\x02\x01");
825     /// ```
826     ///
827     /// # Panics
828     ///
829     /// This function panics if there is not enough remaining capacity in
830     /// `self`.
put_uint_le(&mut self, n: u64, nbytes: usize)831     fn put_uint_le(&mut self, n: u64, nbytes: usize) {
832         let mut buf = [0; 8];
833         LittleEndian::write_uint(&mut buf, n, nbytes);
834         self.put_slice(&buf[0..nbytes])
835     }
836 
837     #[doc(hidden)]
838     #[deprecated(note="use put_int_be or put_int_le")]
put_int<T: ByteOrder>(&mut self, n: i64, nbytes: usize) where Self: Sized839     fn put_int<T: ByteOrder>(&mut self, n: i64, nbytes: usize) where Self: Sized {
840         let mut buf = [0; 8];
841         T::write_int(&mut buf, n, nbytes);
842         self.put_slice(&buf[0..nbytes])
843     }
844 
845     /// Writes a signed n-byte integer to `self` in big-endian byte order.
846     ///
847     /// The current position is advanced by `nbytes`.
848     ///
849     /// # Examples
850     ///
851     /// ```
852     /// use bytes::BufMut;
853     ///
854     /// let mut buf = vec![];
855     /// buf.put_int_be(0x010203, 3);
856     /// assert_eq!(buf, b"\x01\x02\x03");
857     /// ```
858     ///
859     /// # Panics
860     ///
861     /// This function panics if there is not enough remaining capacity in
862     /// `self`.
put_int_be(&mut self, n: i64, nbytes: usize)863     fn put_int_be(&mut self, n: i64, nbytes: usize) {
864         let mut buf = [0; 8];
865         BigEndian::write_int(&mut buf, n, nbytes);
866         self.put_slice(&buf[0..nbytes])
867     }
868 
869     /// Writes a signed n-byte integer to `self` in little-endian byte order.
870     ///
871     /// The current position is advanced by `nbytes`.
872     ///
873     /// # Examples
874     ///
875     /// ```
876     /// use bytes::BufMut;
877     ///
878     /// let mut buf = vec![];
879     /// buf.put_int_le(0x010203, 3);
880     /// assert_eq!(buf, b"\x03\x02\x01");
881     /// ```
882     ///
883     /// # Panics
884     ///
885     /// This function panics if there is not enough remaining capacity in
886     /// `self`.
put_int_le(&mut self, n: i64, nbytes: usize)887     fn put_int_le(&mut self, n: i64, nbytes: usize) {
888         let mut buf = [0; 8];
889         LittleEndian::write_int(&mut buf, n, nbytes);
890         self.put_slice(&buf[0..nbytes])
891     }
892 
893     #[doc(hidden)]
894     #[deprecated(note="use put_f32_be or put_f32_le")]
put_f32<T: ByteOrder>(&mut self, n: f32) where Self: Sized895     fn put_f32<T: ByteOrder>(&mut self, n: f32) where Self: Sized {
896         let mut buf = [0; 4];
897         T::write_f32(&mut buf, n);
898         self.put_slice(&buf)
899     }
900 
901     /// Writes  an IEEE754 single-precision (4 bytes) floating point number to
902     /// `self` in big-endian byte order.
903     ///
904     /// The current position is advanced by 4.
905     ///
906     /// # Examples
907     ///
908     /// ```
909     /// use bytes::BufMut;
910     ///
911     /// let mut buf = vec![];
912     /// buf.put_f32_be(1.2f32);
913     /// assert_eq!(buf, b"\x3F\x99\x99\x9A");
914     /// ```
915     ///
916     /// # Panics
917     ///
918     /// This function panics if there is not enough remaining capacity in
919     /// `self`.
put_f32_be(&mut self, n: f32)920     fn put_f32_be(&mut self, n: f32) {
921         let mut buf = [0; 4];
922         BigEndian::write_f32(&mut buf, n);
923         self.put_slice(&buf)
924     }
925 
926     /// Writes  an IEEE754 single-precision (4 bytes) floating point number to
927     /// `self` in little-endian byte order.
928     ///
929     /// The current position is advanced by 4.
930     ///
931     /// # Examples
932     ///
933     /// ```
934     /// use bytes::BufMut;
935     ///
936     /// let mut buf = vec![];
937     /// buf.put_f32_le(1.2f32);
938     /// assert_eq!(buf, b"\x9A\x99\x99\x3F");
939     /// ```
940     ///
941     /// # Panics
942     ///
943     /// This function panics if there is not enough remaining capacity in
944     /// `self`.
put_f32_le(&mut self, n: f32)945     fn put_f32_le(&mut self, n: f32) {
946         let mut buf = [0; 4];
947         LittleEndian::write_f32(&mut buf, n);
948         self.put_slice(&buf)
949     }
950 
951     #[doc(hidden)]
952     #[deprecated(note="use put_f64_be or put_f64_le")]
put_f64<T: ByteOrder>(&mut self, n: f64) where Self: Sized953     fn put_f64<T: ByteOrder>(&mut self, n: f64) where Self: Sized {
954         let mut buf = [0; 8];
955         T::write_f64(&mut buf, n);
956         self.put_slice(&buf)
957     }
958 
959     /// Writes  an IEEE754 double-precision (8 bytes) floating point number to
960     /// `self` in big-endian byte order.
961     ///
962     /// The current position is advanced by 8.
963     ///
964     /// # Examples
965     ///
966     /// ```
967     /// use bytes::BufMut;
968     ///
969     /// let mut buf = vec![];
970     /// buf.put_f64_be(1.2f64);
971     /// assert_eq!(buf, b"\x3F\xF3\x33\x33\x33\x33\x33\x33");
972     /// ```
973     ///
974     /// # Panics
975     ///
976     /// This function panics if there is not enough remaining capacity in
977     /// `self`.
put_f64_be(&mut self, n: f64)978     fn put_f64_be(&mut self, n: f64) {
979         let mut buf = [0; 8];
980         BigEndian::write_f64(&mut buf, n);
981         self.put_slice(&buf)
982     }
983 
984     /// Writes  an IEEE754 double-precision (8 bytes) floating point number to
985     /// `self` in little-endian byte order.
986     ///
987     /// The current position is advanced by 8.
988     ///
989     /// # Examples
990     ///
991     /// ```
992     /// use bytes::BufMut;
993     ///
994     /// let mut buf = vec![];
995     /// buf.put_f64_le(1.2f64);
996     /// assert_eq!(buf, b"\x33\x33\x33\x33\x33\x33\xF3\x3F");
997     /// ```
998     ///
999     /// # Panics
1000     ///
1001     /// This function panics if there is not enough remaining capacity in
1002     /// `self`.
put_f64_le(&mut self, n: f64)1003     fn put_f64_le(&mut self, n: f64) {
1004         let mut buf = [0; 8];
1005         LittleEndian::write_f64(&mut buf, n);
1006         self.put_slice(&buf)
1007     }
1008 
1009     /// Creates a "by reference" adaptor for this instance of `BufMut`.
1010     ///
1011     /// The returned adapter also implements `BufMut` and will simply borrow
1012     /// `self`.
1013     ///
1014     /// # Examples
1015     ///
1016     /// ```
1017     /// use bytes::BufMut;
1018     /// use std::io;
1019     ///
1020     /// let mut buf = vec![];
1021     ///
1022     /// {
1023     ///     let mut reference = buf.by_ref();
1024     ///
1025     ///     // Adapt reference to `std::io::Write`.
1026     ///     let mut writer = reference.writer();
1027     ///
1028     ///     // Use the buffer as a writter
1029     ///     io::Write::write(&mut writer, &b"hello world"[..]).unwrap();
1030     /// } // drop our &mut reference so that we can use `buf` again
1031     ///
1032     /// assert_eq!(buf, &b"hello world"[..]);
1033     /// ```
by_ref(&mut self) -> &mut Self where Self: Sized1034     fn by_ref(&mut self) -> &mut Self where Self: Sized {
1035         self
1036     }
1037 
1038     /// Creates an adaptor which implements the `Write` trait for `self`.
1039     ///
1040     /// This function returns a new value which implements `Write` by adapting
1041     /// the `Write` trait functions to the `BufMut` trait functions. Given that
1042     /// `BufMut` operations are infallible, none of the `Write` functions will
1043     /// return with `Err`.
1044     ///
1045     /// # Examples
1046     ///
1047     /// ```
1048     /// use bytes::BufMut;
1049     /// use std::io::Write;
1050     ///
1051     /// let mut buf = vec![].writer();
1052     ///
1053     /// let num = buf.write(&b"hello world"[..]).unwrap();
1054     /// assert_eq!(11, num);
1055     ///
1056     /// let buf = buf.into_inner();
1057     ///
1058     /// assert_eq!(*buf, b"hello world"[..]);
1059     /// ```
writer(self) -> Writer<Self> where Self: Sized1060     fn writer(self) -> Writer<Self> where Self: Sized {
1061         super::writer::new(self)
1062     }
1063 }
1064 
1065 impl<'a, T: BufMut + ?Sized> BufMut for &'a mut T {
remaining_mut(&self) -> usize1066     fn remaining_mut(&self) -> usize {
1067         (**self).remaining_mut()
1068     }
1069 
bytes_mut(&mut self) -> &mut [u8]1070     unsafe fn bytes_mut(&mut self) -> &mut [u8] {
1071         (**self).bytes_mut()
1072     }
1073 
bytes_vec_mut<'b>(&'b mut self, dst: &mut [&'b mut IoVec]) -> usize1074     unsafe fn bytes_vec_mut<'b>(&'b mut self, dst: &mut [&'b mut IoVec]) -> usize {
1075         (**self).bytes_vec_mut(dst)
1076     }
1077 
advance_mut(&mut self, cnt: usize)1078     unsafe fn advance_mut(&mut self, cnt: usize) {
1079         (**self).advance_mut(cnt)
1080     }
1081 }
1082 
1083 impl<T: BufMut + ?Sized> BufMut for Box<T> {
remaining_mut(&self) -> usize1084     fn remaining_mut(&self) -> usize {
1085         (**self).remaining_mut()
1086     }
1087 
bytes_mut(&mut self) -> &mut [u8]1088     unsafe fn bytes_mut(&mut self) -> &mut [u8] {
1089         (**self).bytes_mut()
1090     }
1091 
bytes_vec_mut<'b>(&'b mut self, dst: &mut [&'b mut IoVec]) -> usize1092     unsafe fn bytes_vec_mut<'b>(&'b mut self, dst: &mut [&'b mut IoVec]) -> usize {
1093         (**self).bytes_vec_mut(dst)
1094     }
1095 
advance_mut(&mut self, cnt: usize)1096     unsafe fn advance_mut(&mut self, cnt: usize) {
1097         (**self).advance_mut(cnt)
1098     }
1099 }
1100 
1101 impl<T: AsMut<[u8]> + AsRef<[u8]>> BufMut for io::Cursor<T> {
remaining_mut(&self) -> usize1102     fn remaining_mut(&self) -> usize {
1103         use Buf;
1104         self.remaining()
1105     }
1106 
1107     /// Advance the internal cursor of the BufMut
advance_mut(&mut self, cnt: usize)1108     unsafe fn advance_mut(&mut self, cnt: usize) {
1109         use Buf;
1110         self.advance(cnt);
1111     }
1112 
1113     /// Returns a mutable slice starting at the current BufMut position and of
1114     /// length between 0 and `BufMut::remaining()`.
1115     ///
1116     /// The returned byte slice may represent uninitialized memory.
bytes_mut(&mut self) -> &mut [u8]1117     unsafe fn bytes_mut(&mut self) -> &mut [u8] {
1118         let len = self.get_ref().as_ref().len();
1119         let pos = self.position() as usize;
1120 
1121         if pos >= len {
1122             return Default::default();
1123         }
1124 
1125         &mut (self.get_mut().as_mut())[pos..]
1126     }
1127 }
1128 
1129 impl BufMut for Vec<u8> {
1130     #[inline]
remaining_mut(&self) -> usize1131     fn remaining_mut(&self) -> usize {
1132         usize::MAX - self.len()
1133     }
1134 
1135     #[inline]
advance_mut(&mut self, cnt: usize)1136     unsafe fn advance_mut(&mut self, cnt: usize) {
1137         let len = self.len();
1138         let remaining = self.capacity() - len;
1139         if cnt > remaining {
1140             // Reserve additional capacity, and ensure that the total length
1141             // will not overflow usize.
1142             self.reserve(cnt);
1143         }
1144 
1145         self.set_len(len + cnt);
1146     }
1147 
1148     #[inline]
bytes_mut(&mut self) -> &mut [u8]1149     unsafe fn bytes_mut(&mut self) -> &mut [u8] {
1150         use std::slice;
1151 
1152         if self.capacity() == self.len() {
1153             self.reserve(64); // Grow the vec
1154         }
1155 
1156         let cap = self.capacity();
1157         let len = self.len();
1158 
1159         let ptr = self.as_mut_ptr();
1160         &mut slice::from_raw_parts_mut(ptr, cap)[len..]
1161     }
1162 }
1163 
1164 // The existance of this function makes the compiler catch if the BufMut
1165 // trait is "object-safe" or not.
_assert_trait_object(_b: &BufMut)1166 fn _assert_trait_object(_b: &BufMut) {}
1167