bytes_expand/buf/
buf_mut.rs

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