1use crate::buf::{limit, Chain, Limit, UninitSlice};
2#[cfg(feature = "std")]
3use crate::buf::{writer, Writer};
4
5use core::{cmp, mem, ptr, usize};
6
7use 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/// ```
29pub unsafe trait BufMut {
30 /// Returns the number of bytes that can be written from the current
31 /// position until the end of the buffer is reached.
32 ///
33 /// This value is greater than or equal to the length of the slice returned
34 /// by `chunk_mut()`.
35 ///
36 /// Writing to a `BufMut` may involve allocating more memory on the fly.
37 /// Implementations may fail before reaching the number of bytes indicated
38 /// by this method if they encounter an allocation failure.
39 ///
40 /// # Examples
41 ///
42 /// ```
43 /// use bytes::BufMut;
44 ///
45 /// let mut dst = [0; 10];
46 /// let mut buf = &mut dst[..];
47 ///
48 /// let original_remaining = buf.remaining_mut();
49 /// buf.put(&b"hello"[..]);
50 ///
51 /// assert_eq!(original_remaining - 5, buf.remaining_mut());
52 /// ```
53 ///
54 /// # Implementer notes
55 ///
56 /// Implementations of `remaining_mut` should ensure that the return value
57 /// does not change unless a call is made to `advance_mut` or any other
58 /// function that is documented to change the `BufMut`'s current position.
59 ///
60 /// # Note
61 ///
62 /// `remaining_mut` may return value smaller than actual available space.
63 fn remaining_mut(&self) -> usize;
64
65 /// Advance the internal cursor of the BufMut
66 ///
67 /// The next call to `chunk_mut` will return a slice starting `cnt` bytes
68 /// further into the underlying buffer.
69 ///
70 /// This function is unsafe because there is no guarantee that the bytes
71 /// being advanced past have been initialized.
72 ///
73 /// # Examples
74 ///
75 /// ```
76 /// use bytes::BufMut;
77 ///
78 /// let mut buf = Vec::with_capacity(16);
79 ///
80 /// // Write some data
81 /// buf.chunk_mut()[0..2].copy_from_slice(b"he");
82 /// unsafe { buf.advance_mut(2) };
83 ///
84 /// // write more bytes
85 /// buf.chunk_mut()[0..3].copy_from_slice(b"llo");
86 ///
87 /// unsafe { buf.advance_mut(3); }
88 ///
89 /// assert_eq!(5, buf.len());
90 /// assert_eq!(buf, b"hello");
91 /// ```
92 ///
93 /// # Panics
94 ///
95 /// This function **may** panic if `cnt > self.remaining_mut()`.
96 ///
97 /// # Implementer notes
98 ///
99 /// It is recommended for implementations of `advance_mut` to panic if
100 /// `cnt > self.remaining_mut()`. If the implementation does not panic,
101 /// the call must behave as if `cnt == self.remaining_mut()`.
102 ///
103 /// A call with `cnt == 0` should never panic and be a no-op.
104 unsafe fn advance_mut(&mut self, cnt: usize);
105
106 /// Returns true if there is space in `self` for more bytes.
107 ///
108 /// This is equivalent to `self.remaining_mut() != 0`.
109 ///
110 /// # Examples
111 ///
112 /// ```
113 /// use bytes::BufMut;
114 ///
115 /// let mut dst = [0; 5];
116 /// let mut buf = &mut dst[..];
117 ///
118 /// assert!(buf.has_remaining_mut());
119 ///
120 /// buf.put(&b"hello"[..]);
121 ///
122 /// assert!(!buf.has_remaining_mut());
123 /// ```
124 fn has_remaining_mut(&self) -> bool {
125 self.remaining_mut() > 0
126 }
127
128 /// Returns a mutable slice starting at the current BufMut position and of
129 /// length between 0 and `BufMut::remaining_mut()`. Note that this *can* be shorter than the
130 /// whole remainder of the buffer (this allows non-continuous implementation).
131 ///
132 /// This is a lower level function. Most operations are done with other
133 /// functions.
134 ///
135 /// The returned byte slice may represent uninitialized memory.
136 ///
137 /// # Examples
138 ///
139 /// ```
140 /// use bytes::BufMut;
141 ///
142 /// let mut buf = Vec::with_capacity(16);
143 ///
144 /// unsafe {
145 /// // MaybeUninit::as_mut_ptr
146 /// buf.chunk_mut()[0..].as_mut_ptr().write(b'h');
147 /// buf.chunk_mut()[1..].as_mut_ptr().write(b'e');
148 ///
149 /// buf.advance_mut(2);
150 ///
151 /// buf.chunk_mut()[0..].as_mut_ptr().write(b'l');
152 /// buf.chunk_mut()[1..].as_mut_ptr().write(b'l');
153 /// buf.chunk_mut()[2..].as_mut_ptr().write(b'o');
154 ///
155 /// buf.advance_mut(3);
156 /// }
157 ///
158 /// assert_eq!(5, buf.len());
159 /// assert_eq!(buf, b"hello");
160 /// ```
161 ///
162 /// # Implementer notes
163 ///
164 /// This function should never panic. `chunk_mut` should return an empty
165 /// slice **if and only if** `remaining_mut()` returns 0. In other words,
166 /// `chunk_mut()` returning an empty slice implies that `remaining_mut()` will
167 /// return 0 and `remaining_mut()` returning 0 implies that `chunk_mut()` will
168 /// return an empty slice.
169 ///
170 /// This function may trigger an out-of-memory abort if it tries to allocate
171 /// memory and fails to do so.
172 // The `chunk_mut` method was previously called `bytes_mut`. This alias makes the
173 // rename more easily discoverable.
174 #[cfg_attr(docsrs, doc(alias = "bytes_mut"))]
175 fn chunk_mut(&mut self) -> &mut UninitSlice;
176
177 /// Transfer bytes into `self` from `src` and advance the cursor by the
178 /// number of bytes written.
179 ///
180 /// # Examples
181 ///
182 /// ```
183 /// use bytes::BufMut;
184 ///
185 /// let mut buf = vec![];
186 ///
187 /// buf.put_u8(b'h');
188 /// buf.put(&b"ello"[..]);
189 /// buf.put(&b" world"[..]);
190 ///
191 /// assert_eq!(buf, b"hello world");
192 /// ```
193 ///
194 /// # Panics
195 ///
196 /// Panics if `self` does not have enough capacity to contain `src`.
197 fn put<T: super::Buf>(&mut self, mut src: T)
198 where
199 Self: Sized,
200 {
201 assert!(self.remaining_mut() >= src.remaining());
202
203 while src.has_remaining() {
204 let l;
205
206 unsafe {
207 let s = src.chunk();
208 let d = self.chunk_mut();
209 l = cmp::min(s.len(), d.len());
210
211 ptr::copy_nonoverlapping(s.as_ptr(), d.as_mut_ptr() as *mut u8, l);
212 }
213
214 src.advance(l);
215 unsafe {
216 self.advance_mut(l);
217 }
218 }
219 }
220
221 /// Transfer bytes into `self` from `src` and advance the cursor by the
222 /// number of bytes written.
223 ///
224 /// `self` must have enough remaining capacity to contain all of `src`.
225 ///
226 /// ```
227 /// use bytes::BufMut;
228 ///
229 /// let mut dst = [0; 6];
230 ///
231 /// {
232 /// let mut buf = &mut dst[..];
233 /// buf.put_slice(b"hello");
234 ///
235 /// assert_eq!(1, buf.remaining_mut());
236 /// }
237 ///
238 /// assert_eq!(b"hello\0", &dst);
239 /// ```
240 fn put_slice(&mut self, src: &[u8]) {
241 let mut off = 0;
242
243 assert!(
244 self.remaining_mut() >= src.len(),
245 "buffer overflow; remaining = {}; src = {}",
246 self.remaining_mut(),
247 src.len()
248 );
249
250 while off < src.len() {
251 let cnt;
252
253 unsafe {
254 let dst = self.chunk_mut();
255 cnt = cmp::min(dst.len(), src.len() - off);
256
257 ptr::copy_nonoverlapping(src[off..].as_ptr(), dst.as_mut_ptr() as *mut u8, cnt);
258
259 off += cnt;
260 }
261
262 unsafe {
263 self.advance_mut(cnt);
264 }
265 }
266 }
267
268 /// Put `cnt` bytes `val` into `self`.
269 ///
270 /// Logically equivalent to calling `self.put_u8(val)` `cnt` times, but may work faster.
271 ///
272 /// `self` must have at least `cnt` remaining capacity.
273 ///
274 /// ```
275 /// use bytes::BufMut;
276 ///
277 /// let mut dst = [0; 6];
278 ///
279 /// {
280 /// let mut buf = &mut dst[..];
281 /// buf.put_bytes(b'a', 4);
282 ///
283 /// assert_eq!(2, buf.remaining_mut());
284 /// }
285 ///
286 /// assert_eq!(b"aaaa\0\0", &dst);
287 /// ```
288 ///
289 /// # Panics
290 ///
291 /// This function panics if there is not enough remaining capacity in
292 /// `self`.
293 fn put_bytes(&mut self, val: u8, cnt: usize) {
294 for _ in 0..cnt {
295 self.put_u8(val);
296 }
297 }
298
299 /// Writes an unsigned 8 bit integer to `self`.
300 ///
301 /// The current position is advanced by 1.
302 ///
303 /// # Examples
304 ///
305 /// ```
306 /// use bytes::BufMut;
307 ///
308 /// let mut buf = vec![];
309 /// buf.put_u8(0x01);
310 /// assert_eq!(buf, b"\x01");
311 /// ```
312 ///
313 /// # Panics
314 ///
315 /// This function panics if there is not enough remaining capacity in
316 /// `self`.
317 fn put_u8(&mut self, n: u8) {
318 let src = [n];
319 self.put_slice(&src);
320 }
321
322 /// Writes a signed 8 bit integer to `self`.
323 ///
324 /// The current position is advanced by 1.
325 ///
326 /// # Examples
327 ///
328 /// ```
329 /// use bytes::BufMut;
330 ///
331 /// let mut buf = vec![];
332 /// buf.put_i8(0x01);
333 /// assert_eq!(buf, b"\x01");
334 /// ```
335 ///
336 /// # Panics
337 ///
338 /// This function panics if there is not enough remaining capacity in
339 /// `self`.
340 fn put_i8(&mut self, n: i8) {
341 let src = [n as u8];
342 self.put_slice(&src)
343 }
344
345 /// Writes an unsigned 16 bit integer to `self` in big-endian byte order.
346 ///
347 /// The current position is advanced by 2.
348 ///
349 /// # Examples
350 ///
351 /// ```
352 /// use bytes::BufMut;
353 ///
354 /// let mut buf = vec![];
355 /// buf.put_u16(0x0809);
356 /// assert_eq!(buf, b"\x08\x09");
357 /// ```
358 ///
359 /// # Panics
360 ///
361 /// This function panics if there is not enough remaining capacity in
362 /// `self`.
363 fn put_u16(&mut self, n: u16) {
364 self.put_slice(&n.to_be_bytes())
365 }
366
367 /// Writes an unsigned 16 bit integer to `self` in little-endian byte order.
368 ///
369 /// The current position is advanced by 2.
370 ///
371 /// # Examples
372 ///
373 /// ```
374 /// use bytes::BufMut;
375 ///
376 /// let mut buf = vec![];
377 /// buf.put_u16_le(0x0809);
378 /// assert_eq!(buf, b"\x09\x08");
379 /// ```
380 ///
381 /// # Panics
382 ///
383 /// This function panics if there is not enough remaining capacity in
384 /// `self`.
385 fn put_u16_le(&mut self, n: u16) {
386 self.put_slice(&n.to_le_bytes())
387 }
388
389 /// Writes an unsigned 16 bit integer to `self` in native-endian byte order.
390 ///
391 /// The current position is advanced by 2.
392 ///
393 /// # Examples
394 ///
395 /// ```
396 /// use bytes::BufMut;
397 ///
398 /// let mut buf = vec![];
399 /// buf.put_u16_ne(0x0809);
400 /// if cfg!(target_endian = "big") {
401 /// assert_eq!(buf, b"\x08\x09");
402 /// } else {
403 /// assert_eq!(buf, b"\x09\x08");
404 /// }
405 /// ```
406 ///
407 /// # Panics
408 ///
409 /// This function panics if there is not enough remaining capacity in
410 /// `self`.
411 fn put_u16_ne(&mut self, n: u16) {
412 self.put_slice(&n.to_ne_bytes())
413 }
414
415 /// Writes a signed 16 bit integer to `self` in big-endian byte order.
416 ///
417 /// The current position is advanced by 2.
418 ///
419 /// # Examples
420 ///
421 /// ```
422 /// use bytes::BufMut;
423 ///
424 /// let mut buf = vec![];
425 /// buf.put_i16(0x0809);
426 /// assert_eq!(buf, b"\x08\x09");
427 /// ```
428 ///
429 /// # Panics
430 ///
431 /// This function panics if there is not enough remaining capacity in
432 /// `self`.
433 fn put_i16(&mut self, n: i16) {
434 self.put_slice(&n.to_be_bytes())
435 }
436
437 /// Writes a signed 16 bit integer to `self` in little-endian byte order.
438 ///
439 /// The current position is advanced by 2.
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// use bytes::BufMut;
445 ///
446 /// let mut buf = vec![];
447 /// buf.put_i16_le(0x0809);
448 /// assert_eq!(buf, b"\x09\x08");
449 /// ```
450 ///
451 /// # Panics
452 ///
453 /// This function panics if there is not enough remaining capacity in
454 /// `self`.
455 fn put_i16_le(&mut self, n: i16) {
456 self.put_slice(&n.to_le_bytes())
457 }
458
459 /// Writes a signed 16 bit integer to `self` in native-endian byte order.
460 ///
461 /// The current position is advanced by 2.
462 ///
463 /// # Examples
464 ///
465 /// ```
466 /// use bytes::BufMut;
467 ///
468 /// let mut buf = vec![];
469 /// buf.put_i16_ne(0x0809);
470 /// if cfg!(target_endian = "big") {
471 /// assert_eq!(buf, b"\x08\x09");
472 /// } else {
473 /// assert_eq!(buf, b"\x09\x08");
474 /// }
475 /// ```
476 ///
477 /// # Panics
478 ///
479 /// This function panics if there is not enough remaining capacity in
480 /// `self`.
481 fn put_i16_ne(&mut self, n: i16) {
482 self.put_slice(&n.to_ne_bytes())
483 }
484
485 /// Writes an unsigned 32 bit integer to `self` in big-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(0x0809A0A1);
496 /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
497 /// ```
498 ///
499 /// # Panics
500 ///
501 /// This function panics if there is not enough remaining capacity in
502 /// `self`.
503 fn put_u32(&mut self, n: u32) {
504 self.put_slice(&n.to_be_bytes())
505 }
506
507 /// Writes an unsigned 32 bit integer to `self` in little-endian byte order.
508 ///
509 /// The current position is advanced by 4.
510 ///
511 /// # Examples
512 ///
513 /// ```
514 /// use bytes::BufMut;
515 ///
516 /// let mut buf = vec![];
517 /// buf.put_u32_le(0x0809A0A1);
518 /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
519 /// ```
520 ///
521 /// # Panics
522 ///
523 /// This function panics if there is not enough remaining capacity in
524 /// `self`.
525 fn put_u32_le(&mut self, n: u32) {
526 self.put_slice(&n.to_le_bytes())
527 }
528
529 /// Writes an unsigned 32 bit integer to `self` in native-endian byte order.
530 ///
531 /// The current position is advanced by 4.
532 ///
533 /// # Examples
534 ///
535 /// ```
536 /// use bytes::BufMut;
537 ///
538 /// let mut buf = vec![];
539 /// buf.put_u32_ne(0x0809A0A1);
540 /// if cfg!(target_endian = "big") {
541 /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
542 /// } else {
543 /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
544 /// }
545 /// ```
546 ///
547 /// # Panics
548 ///
549 /// This function panics if there is not enough remaining capacity in
550 /// `self`.
551 fn put_u32_ne(&mut self, n: u32) {
552 self.put_slice(&n.to_ne_bytes())
553 }
554
555 /// Writes a signed 32 bit integer to `self` in big-endian byte order.
556 ///
557 /// The current position is advanced by 4.
558 ///
559 /// # Examples
560 ///
561 /// ```
562 /// use bytes::BufMut;
563 ///
564 /// let mut buf = vec![];
565 /// buf.put_i32(0x0809A0A1);
566 /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
567 /// ```
568 ///
569 /// # Panics
570 ///
571 /// This function panics if there is not enough remaining capacity in
572 /// `self`.
573 fn put_i32(&mut self, n: i32) {
574 self.put_slice(&n.to_be_bytes())
575 }
576
577 /// Writes a signed 32 bit integer to `self` in little-endian byte order.
578 ///
579 /// The current position is advanced by 4.
580 ///
581 /// # Examples
582 ///
583 /// ```
584 /// use bytes::BufMut;
585 ///
586 /// let mut buf = vec![];
587 /// buf.put_i32_le(0x0809A0A1);
588 /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
589 /// ```
590 ///
591 /// # Panics
592 ///
593 /// This function panics if there is not enough remaining capacity in
594 /// `self`.
595 fn put_i32_le(&mut self, n: i32) {
596 self.put_slice(&n.to_le_bytes())
597 }
598
599 /// Writes a signed 32 bit integer to `self` in native-endian byte order.
600 ///
601 /// The current position is advanced by 4.
602 ///
603 /// # Examples
604 ///
605 /// ```
606 /// use bytes::BufMut;
607 ///
608 /// let mut buf = vec![];
609 /// buf.put_i32_ne(0x0809A0A1);
610 /// if cfg!(target_endian = "big") {
611 /// assert_eq!(buf, b"\x08\x09\xA0\xA1");
612 /// } else {
613 /// assert_eq!(buf, b"\xA1\xA0\x09\x08");
614 /// }
615 /// ```
616 ///
617 /// # Panics
618 ///
619 /// This function panics if there is not enough remaining capacity in
620 /// `self`.
621 fn put_i32_ne(&mut self, n: i32) {
622 self.put_slice(&n.to_ne_bytes())
623 }
624
625 /// Writes an unsigned 64 bit integer to `self` in the big-endian byte order.
626 ///
627 /// The current position is advanced by 8.
628 ///
629 /// # Examples
630 ///
631 /// ```
632 /// use bytes::BufMut;
633 ///
634 /// let mut buf = vec![];
635 /// buf.put_u64(0x0102030405060708);
636 /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
637 /// ```
638 ///
639 /// # Panics
640 ///
641 /// This function panics if there is not enough remaining capacity in
642 /// `self`.
643 fn put_u64(&mut self, n: u64) {
644 self.put_slice(&n.to_be_bytes())
645 }
646
647 /// Writes an unsigned 64 bit integer to `self` in little-endian byte order.
648 ///
649 /// The current position is advanced by 8.
650 ///
651 /// # Examples
652 ///
653 /// ```
654 /// use bytes::BufMut;
655 ///
656 /// let mut buf = vec![];
657 /// buf.put_u64_le(0x0102030405060708);
658 /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
659 /// ```
660 ///
661 /// # Panics
662 ///
663 /// This function panics if there is not enough remaining capacity in
664 /// `self`.
665 fn put_u64_le(&mut self, n: u64) {
666 self.put_slice(&n.to_le_bytes())
667 }
668
669 /// Writes an unsigned 64 bit integer to `self` in native-endian byte order.
670 ///
671 /// The current position is advanced by 8.
672 ///
673 /// # Examples
674 ///
675 /// ```
676 /// use bytes::BufMut;
677 ///
678 /// let mut buf = vec![];
679 /// buf.put_u64_ne(0x0102030405060708);
680 /// if cfg!(target_endian = "big") {
681 /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
682 /// } else {
683 /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
684 /// }
685 /// ```
686 ///
687 /// # Panics
688 ///
689 /// This function panics if there is not enough remaining capacity in
690 /// `self`.
691 fn put_u64_ne(&mut self, n: u64) {
692 self.put_slice(&n.to_ne_bytes())
693 }
694
695 /// Writes a signed 64 bit integer to `self` in the big-endian byte order.
696 ///
697 /// The current position is advanced by 8.
698 ///
699 /// # Examples
700 ///
701 /// ```
702 /// use bytes::BufMut;
703 ///
704 /// let mut buf = vec![];
705 /// buf.put_i64(0x0102030405060708);
706 /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
707 /// ```
708 ///
709 /// # Panics
710 ///
711 /// This function panics if there is not enough remaining capacity in
712 /// `self`.
713 fn put_i64(&mut self, n: i64) {
714 self.put_slice(&n.to_be_bytes())
715 }
716
717 /// Writes a signed 64 bit integer to `self` in little-endian byte order.
718 ///
719 /// The current position is advanced by 8.
720 ///
721 /// # Examples
722 ///
723 /// ```
724 /// use bytes::BufMut;
725 ///
726 /// let mut buf = vec![];
727 /// buf.put_i64_le(0x0102030405060708);
728 /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
729 /// ```
730 ///
731 /// # Panics
732 ///
733 /// This function panics if there is not enough remaining capacity in
734 /// `self`.
735 fn put_i64_le(&mut self, n: i64) {
736 self.put_slice(&n.to_le_bytes())
737 }
738
739 /// Writes a signed 64 bit integer to `self` in native-endian byte order.
740 ///
741 /// The current position is advanced by 8.
742 ///
743 /// # Examples
744 ///
745 /// ```
746 /// use bytes::BufMut;
747 ///
748 /// let mut buf = vec![];
749 /// buf.put_i64_ne(0x0102030405060708);
750 /// if cfg!(target_endian = "big") {
751 /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08");
752 /// } else {
753 /// assert_eq!(buf, b"\x08\x07\x06\x05\x04\x03\x02\x01");
754 /// }
755 /// ```
756 ///
757 /// # Panics
758 ///
759 /// This function panics if there is not enough remaining capacity in
760 /// `self`.
761 fn put_i64_ne(&mut self, n: i64) {
762 self.put_slice(&n.to_ne_bytes())
763 }
764
765 /// Writes an unsigned 128 bit integer to `self` in the big-endian byte order.
766 ///
767 /// The current position is advanced by 16.
768 ///
769 /// # Examples
770 ///
771 /// ```
772 /// use bytes::BufMut;
773 ///
774 /// let mut buf = vec![];
775 /// buf.put_u128(0x01020304050607080910111213141516);
776 /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
777 /// ```
778 ///
779 /// # Panics
780 ///
781 /// This function panics if there is not enough remaining capacity in
782 /// `self`.
783 fn put_u128(&mut self, n: u128) {
784 self.put_slice(&n.to_be_bytes())
785 }
786
787 /// Writes an unsigned 128 bit integer to `self` in little-endian byte order.
788 ///
789 /// The current position is advanced by 16.
790 ///
791 /// # Examples
792 ///
793 /// ```
794 /// use bytes::BufMut;
795 ///
796 /// let mut buf = vec![];
797 /// buf.put_u128_le(0x01020304050607080910111213141516);
798 /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
799 /// ```
800 ///
801 /// # Panics
802 ///
803 /// This function panics if there is not enough remaining capacity in
804 /// `self`.
805 fn put_u128_le(&mut self, n: u128) {
806 self.put_slice(&n.to_le_bytes())
807 }
808
809 /// Writes an unsigned 128 bit integer to `self` in native-endian byte order.
810 ///
811 /// The current position is advanced by 16.
812 ///
813 /// # Examples
814 ///
815 /// ```
816 /// use bytes::BufMut;
817 ///
818 /// let mut buf = vec![];
819 /// buf.put_u128_ne(0x01020304050607080910111213141516);
820 /// if cfg!(target_endian = "big") {
821 /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
822 /// } else {
823 /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
824 /// }
825 /// ```
826 ///
827 /// # Panics
828 ///
829 /// This function panics if there is not enough remaining capacity in
830 /// `self`.
831 fn put_u128_ne(&mut self, n: u128) {
832 self.put_slice(&n.to_ne_bytes())
833 }
834
835 /// Writes a signed 128 bit integer to `self` in the big-endian byte order.
836 ///
837 /// The current position is advanced by 16.
838 ///
839 /// # Examples
840 ///
841 /// ```
842 /// use bytes::BufMut;
843 ///
844 /// let mut buf = vec![];
845 /// buf.put_i128(0x01020304050607080910111213141516);
846 /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
847 /// ```
848 ///
849 /// # Panics
850 ///
851 /// This function panics if there is not enough remaining capacity in
852 /// `self`.
853 fn put_i128(&mut self, n: i128) {
854 self.put_slice(&n.to_be_bytes())
855 }
856
857 /// Writes a signed 128 bit integer to `self` in little-endian byte order.
858 ///
859 /// The current position is advanced by 16.
860 ///
861 /// # Examples
862 ///
863 /// ```
864 /// use bytes::BufMut;
865 ///
866 /// let mut buf = vec![];
867 /// buf.put_i128_le(0x01020304050607080910111213141516);
868 /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
869 /// ```
870 ///
871 /// # Panics
872 ///
873 /// This function panics if there is not enough remaining capacity in
874 /// `self`.
875 fn put_i128_le(&mut self, n: i128) {
876 self.put_slice(&n.to_le_bytes())
877 }
878
879 /// Writes a signed 128 bit integer to `self` in native-endian byte order.
880 ///
881 /// The current position is advanced by 16.
882 ///
883 /// # Examples
884 ///
885 /// ```
886 /// use bytes::BufMut;
887 ///
888 /// let mut buf = vec![];
889 /// buf.put_i128_ne(0x01020304050607080910111213141516);
890 /// if cfg!(target_endian = "big") {
891 /// assert_eq!(buf, b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x16");
892 /// } else {
893 /// assert_eq!(buf, b"\x16\x15\x14\x13\x12\x11\x10\x09\x08\x07\x06\x05\x04\x03\x02\x01");
894 /// }
895 /// ```
896 ///
897 /// # Panics
898 ///
899 /// This function panics if there is not enough remaining capacity in
900 /// `self`.
901 fn put_i128_ne(&mut self, n: i128) {
902 self.put_slice(&n.to_ne_bytes())
903 }
904
905 /// Writes an unsigned n-byte integer to `self` in big-endian byte order.
906 ///
907 /// The current position is advanced by `nbytes`.
908 ///
909 /// # Examples
910 ///
911 /// ```
912 /// use bytes::BufMut;
913 ///
914 /// let mut buf = vec![];
915 /// buf.put_uint(0x010203, 3);
916 /// assert_eq!(buf, b"\x01\x02\x03");
917 /// ```
918 ///
919 /// # Panics
920 ///
921 /// This function panics if there is not enough remaining capacity in
922 /// `self`.
923 fn put_uint(&mut self, n: u64, nbytes: usize) {
924 self.put_slice(&n.to_be_bytes()[mem::size_of_val(&n) - nbytes..]);
925 }
926
927 /// Writes an unsigned n-byte integer to `self` in the little-endian byte order.
928 ///
929 /// The current position is advanced by `nbytes`.
930 ///
931 /// # Examples
932 ///
933 /// ```
934 /// use bytes::BufMut;
935 ///
936 /// let mut buf = vec![];
937 /// buf.put_uint_le(0x010203, 3);
938 /// assert_eq!(buf, b"\x03\x02\x01");
939 /// ```
940 ///
941 /// # Panics
942 ///
943 /// This function panics if there is not enough remaining capacity in
944 /// `self`.
945 fn put_uint_le(&mut self, n: u64, nbytes: usize) {
946 self.put_slice(&n.to_le_bytes()[0..nbytes]);
947 }
948
949 /// Writes an unsigned n-byte integer to `self` in the native-endian byte order.
950 ///
951 /// The current position is advanced by `nbytes`.
952 ///
953 /// # Examples
954 ///
955 /// ```
956 /// use bytes::BufMut;
957 ///
958 /// let mut buf = vec![];
959 /// buf.put_uint_ne(0x010203, 3);
960 /// if cfg!(target_endian = "big") {
961 /// assert_eq!(buf, b"\x01\x02\x03");
962 /// } else {
963 /// assert_eq!(buf, b"\x03\x02\x01");
964 /// }
965 /// ```
966 ///
967 /// # Panics
968 ///
969 /// This function panics if there is not enough remaining capacity in
970 /// `self`.
971 fn put_uint_ne(&mut self, n: u64, nbytes: usize) {
972 if cfg!(target_endian = "big") {
973 self.put_uint(n, nbytes)
974 } else {
975 self.put_uint_le(n, nbytes)
976 }
977 }
978
979 /// Writes low `nbytes` of a signed integer to `self` in big-endian byte order.
980 ///
981 /// The current position is advanced by `nbytes`.
982 ///
983 /// # Examples
984 ///
985 /// ```
986 /// use bytes::BufMut;
987 ///
988 /// let mut buf = vec![];
989 /// buf.put_int(0x0504010203, 3);
990 /// assert_eq!(buf, b"\x01\x02\x03");
991 /// ```
992 ///
993 /// # Panics
994 ///
995 /// This function panics if there is not enough remaining capacity in
996 /// `self` or if `nbytes` is greater than 8.
997 fn put_int(&mut self, n: i64, nbytes: usize) {
998 self.put_slice(&n.to_be_bytes()[mem::size_of_val(&n) - nbytes..]);
999 }
1000
1001 /// Writes low `nbytes` of a signed integer to `self` in little-endian byte order.
1002 ///
1003 /// The current position is advanced by `nbytes`.
1004 ///
1005 /// # Examples
1006 ///
1007 /// ```
1008 /// use bytes::BufMut;
1009 ///
1010 /// let mut buf = vec![];
1011 /// buf.put_int_le(0x0504010203, 3);
1012 /// assert_eq!(buf, b"\x03\x02\x01");
1013 /// ```
1014 ///
1015 /// # Panics
1016 ///
1017 /// This function panics if there is not enough remaining capacity in
1018 /// `self` or if `nbytes` is greater than 8.
1019 fn put_int_le(&mut self, n: i64, nbytes: usize) {
1020 self.put_slice(&n.to_le_bytes()[0..nbytes]);
1021 }
1022
1023 /// Writes low `nbytes` of a signed integer to `self` in native-endian byte order.
1024 ///
1025 /// The current position is advanced by `nbytes`.
1026 ///
1027 /// # Examples
1028 ///
1029 /// ```
1030 /// use bytes::BufMut;
1031 ///
1032 /// let mut buf = vec![];
1033 /// buf.put_int_ne(0x010203, 3);
1034 /// if cfg!(target_endian = "big") {
1035 /// assert_eq!(buf, b"\x01\x02\x03");
1036 /// } else {
1037 /// assert_eq!(buf, b"\x03\x02\x01");
1038 /// }
1039 /// ```
1040 ///
1041 /// # Panics
1042 ///
1043 /// This function panics if there is not enough remaining capacity in
1044 /// `self` or if `nbytes` is greater than 8.
1045 fn put_int_ne(&mut self, n: i64, nbytes: usize) {
1046 if cfg!(target_endian = "big") {
1047 self.put_int(n, nbytes)
1048 } else {
1049 self.put_int_le(n, nbytes)
1050 }
1051 }
1052
1053 /// Writes an IEEE754 single-precision (4 bytes) floating point number to
1054 /// `self` in big-endian byte order.
1055 ///
1056 /// The current position is advanced by 4.
1057 ///
1058 /// # Examples
1059 ///
1060 /// ```
1061 /// use bytes::BufMut;
1062 ///
1063 /// let mut buf = vec![];
1064 /// buf.put_f32(1.2f32);
1065 /// assert_eq!(buf, b"\x3F\x99\x99\x9A");
1066 /// ```
1067 ///
1068 /// # Panics
1069 ///
1070 /// This function panics if there is not enough remaining capacity in
1071 /// `self`.
1072 fn put_f32(&mut self, n: f32) {
1073 self.put_u32(n.to_bits());
1074 }
1075
1076 /// Writes an IEEE754 single-precision (4 bytes) floating point number to
1077 /// `self` in little-endian byte order.
1078 ///
1079 /// The current position is advanced by 4.
1080 ///
1081 /// # Examples
1082 ///
1083 /// ```
1084 /// use bytes::BufMut;
1085 ///
1086 /// let mut buf = vec![];
1087 /// buf.put_f32_le(1.2f32);
1088 /// assert_eq!(buf, b"\x9A\x99\x99\x3F");
1089 /// ```
1090 ///
1091 /// # Panics
1092 ///
1093 /// This function panics if there is not enough remaining capacity in
1094 /// `self`.
1095 fn put_f32_le(&mut self, n: f32) {
1096 self.put_u32_le(n.to_bits());
1097 }
1098
1099 /// Writes an IEEE754 single-precision (4 bytes) floating point number to
1100 /// `self` in native-endian byte order.
1101 ///
1102 /// The current position is advanced by 4.
1103 ///
1104 /// # Examples
1105 ///
1106 /// ```
1107 /// use bytes::BufMut;
1108 ///
1109 /// let mut buf = vec![];
1110 /// buf.put_f32_ne(1.2f32);
1111 /// if cfg!(target_endian = "big") {
1112 /// assert_eq!(buf, b"\x3F\x99\x99\x9A");
1113 /// } else {
1114 /// assert_eq!(buf, b"\x9A\x99\x99\x3F");
1115 /// }
1116 /// ```
1117 ///
1118 /// # Panics
1119 ///
1120 /// This function panics if there is not enough remaining capacity in
1121 /// `self`.
1122 fn put_f32_ne(&mut self, n: f32) {
1123 self.put_u32_ne(n.to_bits());
1124 }
1125
1126 /// Writes an IEEE754 double-precision (8 bytes) floating point number to
1127 /// `self` in big-endian byte order.
1128 ///
1129 /// The current position is advanced by 8.
1130 ///
1131 /// # Examples
1132 ///
1133 /// ```
1134 /// use bytes::BufMut;
1135 ///
1136 /// let mut buf = vec![];
1137 /// buf.put_f64(1.2f64);
1138 /// assert_eq!(buf, b"\x3F\xF3\x33\x33\x33\x33\x33\x33");
1139 /// ```
1140 ///
1141 /// # Panics
1142 ///
1143 /// This function panics if there is not enough remaining capacity in
1144 /// `self`.
1145 fn put_f64(&mut self, n: f64) {
1146 self.put_u64(n.to_bits());
1147 }
1148
1149 /// Writes an IEEE754 double-precision (8 bytes) floating point number to
1150 /// `self` in little-endian byte order.
1151 ///
1152 /// The current position is advanced by 8.
1153 ///
1154 /// # Examples
1155 ///
1156 /// ```
1157 /// use bytes::BufMut;
1158 ///
1159 /// let mut buf = vec![];
1160 /// buf.put_f64_le(1.2f64);
1161 /// assert_eq!(buf, b"\x33\x33\x33\x33\x33\x33\xF3\x3F");
1162 /// ```
1163 ///
1164 /// # Panics
1165 ///
1166 /// This function panics if there is not enough remaining capacity in
1167 /// `self`.
1168 fn put_f64_le(&mut self, n: f64) {
1169 self.put_u64_le(n.to_bits());
1170 }
1171
1172 /// Writes an IEEE754 double-precision (8 bytes) floating point number to
1173 /// `self` in native-endian byte order.
1174 ///
1175 /// The current position is advanced by 8.
1176 ///
1177 /// # Examples
1178 ///
1179 /// ```
1180 /// use bytes::BufMut;
1181 ///
1182 /// let mut buf = vec![];
1183 /// buf.put_f64_ne(1.2f64);
1184 /// if cfg!(target_endian = "big") {
1185 /// assert_eq!(buf, b"\x3F\xF3\x33\x33\x33\x33\x33\x33");
1186 /// } else {
1187 /// assert_eq!(buf, b"\x33\x33\x33\x33\x33\x33\xF3\x3F");
1188 /// }
1189 /// ```
1190 ///
1191 /// # Panics
1192 ///
1193 /// This function panics if there is not enough remaining capacity in
1194 /// `self`.
1195 fn put_f64_ne(&mut self, n: f64) {
1196 self.put_u64_ne(n.to_bits());
1197 }
1198
1199 /// Creates an adaptor which can write at most `limit` bytes to `self`.
1200 ///
1201 /// # Examples
1202 ///
1203 /// ```
1204 /// use bytes::BufMut;
1205 ///
1206 /// let arr = &mut [0u8; 128][..];
1207 /// assert_eq!(arr.remaining_mut(), 128);
1208 ///
1209 /// let dst = arr.limit(10);
1210 /// assert_eq!(dst.remaining_mut(), 10);
1211 /// ```
1212 fn limit(self, limit: usize) -> Limit<Self>
1213 where
1214 Self: Sized,
1215 {
1216 limit::new(self, limit)
1217 }
1218
1219 /// Creates an adaptor which implements the `Write` trait for `self`.
1220 ///
1221 /// This function returns a new value which implements `Write` by adapting
1222 /// the `Write` trait functions to the `BufMut` trait functions. Given that
1223 /// `BufMut` operations are infallible, none of the `Write` functions will
1224 /// return with `Err`.
1225 ///
1226 /// # Examples
1227 ///
1228 /// ```
1229 /// use bytes::BufMut;
1230 /// use std::io::Write;
1231 ///
1232 /// let mut buf = vec![].writer();
1233 ///
1234 /// let num = buf.write(&b"hello world"[..]).unwrap();
1235 /// assert_eq!(11, num);
1236 ///
1237 /// let buf = buf.into_inner();
1238 ///
1239 /// assert_eq!(*buf, b"hello world"[..]);
1240 /// ```
1241 #[cfg(feature = "std")]
1242 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1243 fn writer(self) -> Writer<Self>
1244 where
1245 Self: Sized,
1246 {
1247 writer::new(self)
1248 }
1249
1250 /// Creates an adapter which will chain this buffer with another.
1251 ///
1252 /// The returned `BufMut` instance will first write to all bytes from
1253 /// `self`. Afterwards, it will write to `next`.
1254 ///
1255 /// # Examples
1256 ///
1257 /// ```
1258 /// use bytes::BufMut;
1259 ///
1260 /// let mut a = [0u8; 5];
1261 /// let mut b = [0u8; 6];
1262 ///
1263 /// let mut chain = (&mut a[..]).chain_mut(&mut b[..]);
1264 ///
1265 /// chain.put_slice(b"hello world");
1266 ///
1267 /// assert_eq!(&a[..], b"hello");
1268 /// assert_eq!(&b[..], b" world");
1269 /// ```
1270 fn chain_mut<U: BufMut>(self, next: U) -> Chain<Self, U>
1271 where
1272 Self: Sized,
1273 {
1274 Chain::new(self, next)
1275 }
1276}
1277
1278macro_rules! deref_forward_bufmut {
1279 () => {
1280 fn remaining_mut(&self) -> usize {
1281 (**self).remaining_mut()
1282 }
1283
1284 fn chunk_mut(&mut self) -> &mut UninitSlice {
1285 (**self).chunk_mut()
1286 }
1287
1288 unsafe fn advance_mut(&mut self, cnt: usize) {
1289 (**self).advance_mut(cnt)
1290 }
1291
1292 fn put_slice(&mut self, src: &[u8]) {
1293 (**self).put_slice(src)
1294 }
1295
1296 fn put_u8(&mut self, n: u8) {
1297 (**self).put_u8(n)
1298 }
1299
1300 fn put_i8(&mut self, n: i8) {
1301 (**self).put_i8(n)
1302 }
1303
1304 fn put_u16(&mut self, n: u16) {
1305 (**self).put_u16(n)
1306 }
1307
1308 fn put_u16_le(&mut self, n: u16) {
1309 (**self).put_u16_le(n)
1310 }
1311
1312 fn put_u16_ne(&mut self, n: u16) {
1313 (**self).put_u16_ne(n)
1314 }
1315
1316 fn put_i16(&mut self, n: i16) {
1317 (**self).put_i16(n)
1318 }
1319
1320 fn put_i16_le(&mut self, n: i16) {
1321 (**self).put_i16_le(n)
1322 }
1323
1324 fn put_i16_ne(&mut self, n: i16) {
1325 (**self).put_i16_ne(n)
1326 }
1327
1328 fn put_u32(&mut self, n: u32) {
1329 (**self).put_u32(n)
1330 }
1331
1332 fn put_u32_le(&mut self, n: u32) {
1333 (**self).put_u32_le(n)
1334 }
1335
1336 fn put_u32_ne(&mut self, n: u32) {
1337 (**self).put_u32_ne(n)
1338 }
1339
1340 fn put_i32(&mut self, n: i32) {
1341 (**self).put_i32(n)
1342 }
1343
1344 fn put_i32_le(&mut self, n: i32) {
1345 (**self).put_i32_le(n)
1346 }
1347
1348 fn put_i32_ne(&mut self, n: i32) {
1349 (**self).put_i32_ne(n)
1350 }
1351
1352 fn put_u64(&mut self, n: u64) {
1353 (**self).put_u64(n)
1354 }
1355
1356 fn put_u64_le(&mut self, n: u64) {
1357 (**self).put_u64_le(n)
1358 }
1359
1360 fn put_u64_ne(&mut self, n: u64) {
1361 (**self).put_u64_ne(n)
1362 }
1363
1364 fn put_i64(&mut self, n: i64) {
1365 (**self).put_i64(n)
1366 }
1367
1368 fn put_i64_le(&mut self, n: i64) {
1369 (**self).put_i64_le(n)
1370 }
1371
1372 fn put_i64_ne(&mut self, n: i64) {
1373 (**self).put_i64_ne(n)
1374 }
1375 };
1376}
1377
1378unsafe impl<T: BufMut + ?Sized> BufMut for &mut T {
1379 deref_forward_bufmut!();
1380}
1381
1382unsafe impl<T: BufMut + ?Sized> BufMut for Box<T> {
1383 deref_forward_bufmut!();
1384}
1385
1386unsafe impl BufMut for &mut [u8] {
1387 #[inline]
1388 fn remaining_mut(&self) -> usize {
1389 self.len()
1390 }
1391
1392 #[inline]
1393 fn chunk_mut(&mut self) -> &mut UninitSlice {
1394 // UninitSlice is repr(transparent), so safe to transmute
1395 unsafe { &mut *(*self as *mut [u8] as *mut _) }
1396 }
1397
1398 #[inline]
1399 unsafe fn advance_mut(&mut self, cnt: usize) {
1400 // Lifetime dance taken from `impl Write for &mut [u8]`.
1401 let (_, b) = core::mem::replace(self, &mut []).split_at_mut(cnt);
1402 *self = b;
1403 }
1404
1405 #[inline]
1406 fn put_slice(&mut self, src: &[u8]) {
1407 self[..src.len()].copy_from_slice(src);
1408 unsafe {
1409 self.advance_mut(src.len());
1410 }
1411 }
1412
1413 fn put_bytes(&mut self, val: u8, cnt: usize) {
1414 assert!(self.remaining_mut() >= cnt);
1415 unsafe {
1416 ptr::write_bytes(self.as_mut_ptr(), val, cnt);
1417 self.advance_mut(cnt);
1418 }
1419 }
1420}
1421
1422unsafe impl BufMut for Vec<u8> {
1423 #[inline]
1424 fn remaining_mut(&self) -> usize {
1425 // A vector can never have more than isize::MAX bytes
1426 core::isize::MAX as usize - self.len()
1427 }
1428
1429 #[inline]
1430 unsafe fn advance_mut(&mut self, cnt: usize) {
1431 let len = self.len();
1432 let remaining = self.capacity() - len;
1433
1434 assert!(
1435 cnt <= remaining,
1436 "cannot advance past `remaining_mut`: {:?} <= {:?}",
1437 cnt,
1438 remaining
1439 );
1440
1441 self.set_len(len + cnt);
1442 }
1443
1444 #[inline]
1445 fn chunk_mut(&mut self) -> &mut UninitSlice {
1446 if self.capacity() == self.len() {
1447 self.reserve(64); // Grow the vec
1448 }
1449
1450 let cap = self.capacity();
1451 let len = self.len();
1452
1453 let ptr = self.as_mut_ptr();
1454 unsafe { &mut UninitSlice::from_raw_parts_mut(ptr, cap)[len..] }
1455 }
1456
1457 // Specialize these methods so they can skip checking `remaining_mut`
1458 // and `advance_mut`.
1459 fn put<T: super::Buf>(&mut self, mut src: T)
1460 where
1461 Self: Sized,
1462 {
1463 // In case the src isn't contiguous, reserve upfront
1464 self.reserve(src.remaining());
1465
1466 while src.has_remaining() {
1467 let l;
1468
1469 // a block to contain the src.bytes() borrow
1470 {
1471 let s = src.chunk();
1472 l = s.len();
1473 self.extend_from_slice(s);
1474 }
1475
1476 src.advance(l);
1477 }
1478 }
1479
1480 #[inline]
1481 fn put_slice(&mut self, src: &[u8]) {
1482 self.extend_from_slice(src);
1483 }
1484
1485 fn put_bytes(&mut self, val: u8, cnt: usize) {
1486 let new_len = self.len().checked_add(cnt).unwrap();
1487 self.resize(new_len, val);
1488 }
1489}
1490
1491// The existence of this function makes the compiler catch if the BufMut
1492// trait is "object-safe" or not.
1493fn _assert_trait_object(_b: &dyn BufMut) {}
1494