ntex_bytes/bvec.rs
1use std::{borrow, fmt, io, ops::DerefMut, ptr};
2
3use crate::{Buf, BufMut, BytePageSize, Bytes, buf::UninitSlice, stvec::StorageVec};
4
5/// A unique reference to a contiguous slice of memory.
6///
7/// `BytesMut` represents a unique view into a potentially shared memory region.
8/// Given the uniqueness guarantee, owners of `BytesMut` handles are able to
9/// mutate the memory. It is similar to a `Vec<u8>` but with fewer copies and
10/// allocations. It also always allocates.
11///
12/// For more detail, see [`Bytes`].
13///
14/// # Growth
15///
16/// Safe write operations such as [`BufMut::put_slice`], [`BufMut::put_u8`], and
17/// [`extend_from_slice`](Self::extend_from_slice) reserve additional capacity
18/// when needed. Use [`reserve`](Self::reserve) when the required capacity is
19/// known in advance to avoid repeated allocation.
20///
21/// # Examples
22///
23/// ```
24/// use ntex_bytes::{BytesMut, BufMut};
25///
26/// let mut buf = BytesMut::with_capacity(64);
27///
28/// buf.put_u8(b'h');
29/// buf.put_u8(b'e');
30/// buf.put("llo");
31///
32/// assert_eq!(&buf[..], b"hello");
33///
34/// // Freeze the buffer so that it can be shared
35/// let a = buf.freeze();
36///
37/// // This does not allocate, instead `b` points to the same memory.
38/// let b = a.clone();
39///
40/// assert_eq!(a, b"hello");
41/// assert_eq!(b, b"hello");
42/// ```
43pub struct BytesMut {
44 pub(crate) storage: StorageVec,
45}
46
47impl BytesMut {
48 /// Creates a new `BytesMut` with the specified capacity.
49 ///
50 /// The returned `BytesMut` will be able to hold `capacity` bytes
51 /// without reallocating.
52 ///
53 /// It is important to note that this function does not specify the length
54 /// of the returned `BytesMut`, but only the capacity.
55 ///
56 /// # Panics
57 ///
58 /// Panics if `capacity` exceeds `u32::MAX` minus the buffer
59 /// header size, just under 4 GiB.
60 ///
61 /// # Examples
62 ///
63 /// ```
64 /// use ntex_bytes::{BytesMut, BufMut};
65 ///
66 /// let mut bytes = BytesMut::with_capacity(64);
67 ///
68 /// // `bytes` contains no data, even though there is capacity
69 /// assert_eq!(bytes.len(), 0);
70 ///
71 /// bytes.put(&b"hello world"[..]);
72 ///
73 /// assert_eq!(&bytes[..], b"hello world");
74 /// ```
75 #[inline]
76 #[must_use]
77 pub fn with_capacity(capacity: usize) -> BytesMut {
78 BytesMut {
79 storage: StorageVec::with_capacity(capacity),
80 }
81 }
82
83 /// Creates a new empty `BytesMut` backed by a page of the specified size.
84 ///
85 /// The buffer has the [`capacity`](BytePageSize::capacity) of the page
86 /// size. Pages are taken from the current thread's page cache, and the
87 /// page returns to the cache of the thread that drops the last reference
88 /// to it, including [`Bytes`] split off the buffer.
89 ///
90 /// When the buffer grows, it moves to a page of the size that fits the
91 /// new capacity, see [`reserve`](Self::reserve). Above the largest page
92 /// size the buffer is a regular allocation without a page size, it is
93 /// freed when dropped.
94 ///
95 /// [`BytePageSize::Unset`] has the allocation size of
96 /// [`BytePageSize::Size64`], it creates a `Size64` page.
97 ///
98 /// # Examples
99 ///
100 /// ```
101 /// use ntex_bytes::{BytePageSize, BytesMut};
102 ///
103 /// let mut buf = BytesMut::with_page_size(BytePageSize::Size4);
104 /// assert_eq!(buf.capacity(), BytePageSize::Size4.capacity());
105 /// assert_eq!(buf.page_size(), BytePageSize::Size4);
106 ///
107 /// buf.extend_from_slice(&[0; 5000]);
108 /// assert_eq!(buf.page_size(), BytePageSize::Size8);
109 /// ```
110 #[inline]
111 #[must_use]
112 pub fn with_page_size(size: BytePageSize) -> BytesMut {
113 let size = if size == BytePageSize::Unset {
114 BytePageSize::Size64
115 } else {
116 size
117 };
118 BytesMut {
119 storage: StorageVec::sized(size),
120 }
121 }
122
123 /// Returns the page size of the buffer.
124 ///
125 /// The page size is derived from the allocation size, a buffer whose
126 /// allocation, header included, is exactly a page size belongs to that
127 /// page size. This covers buffers created by
128 /// [`with_page_size`](Self::with_page_size), converted from a pooled
129 /// [`BytePage`](crate::BytePage), or created with a page
130 /// [`capacity`](BytePageSize::capacity). They return to the page cache
131 /// when the last reference is dropped. Other buffers return
132 /// [`BytePageSize::Unset`], they are freed when dropped.
133 #[inline]
134 pub fn page_size(&self) -> BytePageSize {
135 self.storage.page_size()
136 }
137
138 /// Creates a `BytesMut` by copying a byte slice.
139 #[inline]
140 #[must_use]
141 pub fn copy_from_slice<T: AsRef<[u8]>>(src: T) -> Self {
142 let slice = src.as_ref();
143 BytesMut {
144 storage: StorageVec::from_slice(slice.len(), slice),
145 }
146 }
147
148 /// Creates a new `BytesMut` with default capacity.
149 ///
150 /// Resulting object has length 0 and unspecified capacity.
151 ///
152 /// # Examples
153 ///
154 /// ```
155 /// use ntex_bytes::{BytesMut, BufMut};
156 ///
157 /// let mut bytes = BytesMut::new();
158 ///
159 /// assert_eq!(0, bytes.len());
160 ///
161 /// bytes.reserve(2);
162 /// bytes.put_slice(b"xy");
163 ///
164 /// assert_eq!(&b"xy"[..], &bytes[..]);
165 /// ```
166 #[inline]
167 #[must_use]
168 pub fn new() -> BytesMut {
169 BytesMut {
170 storage: StorageVec::with_capacity(crate::storage::MIN_CAPACITY),
171 }
172 }
173
174 /// Returns the number of bytes contained in this `BytesMut`.
175 ///
176 /// # Examples
177 ///
178 /// ```
179 /// use ntex_bytes::BytesMut;
180 ///
181 /// let b = BytesMut::copy_from_slice(&b"hello"[..]);
182 /// assert_eq!(b.len(), 5);
183 /// ```
184 #[inline]
185 pub fn len(&self) -> usize {
186 self.storage.len()
187 }
188
189 /// Returns `true` if the buffer is empty.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// use ntex_bytes::BytesMut;
195 ///
196 /// let b = BytesMut::with_capacity(64);
197 /// assert!(b.is_empty());
198 /// ```
199 #[inline]
200 pub fn is_empty(&self) -> bool {
201 self.storage.len() == 0
202 }
203
204 /// Returns the number of bytes the `BytesMut` can hold without reallocating.
205 ///
206 /// # Examples
207 ///
208 /// ```
209 /// use ntex_bytes::BytesMut;
210 ///
211 /// let b = BytesMut::with_capacity(64);
212 /// assert_eq!(b.capacity(), 64);
213 /// ```
214 #[inline]
215 pub fn capacity(&self) -> usize {
216 self.storage.capacity()
217 }
218
219 /// Returns `true` if no other handle refers to the underlying buffer.
220 ///
221 /// Values split off with [`split_to`](Self::split_to) or frozen into
222 /// [`Bytes`] share the buffer with `self`. While they exist, clearing
223 /// `self` does not reclaim the capacity in front of it, and the whole
224 /// allocation stays alive as long as any of them does.
225 ///
226 /// # Examples
227 ///
228 /// ```
229 /// use ntex_bytes::BytesMut;
230 ///
231 /// let mut buf = BytesMut::with_capacity(64);
232 /// buf.extend_from_slice(&[0; 32]);
233 /// assert!(buf.is_unique());
234 ///
235 /// let head = buf.split_to(30);
236 /// assert!(!buf.is_unique());
237 ///
238 /// drop(head);
239 /// assert!(buf.is_unique());
240 /// ```
241 #[inline]
242 pub fn is_unique(&self) -> bool {
243 self.storage.is_unique()
244 }
245
246 /// Converts `self` into an immutable `Bytes`.
247 ///
248 /// The conversion is zero cost and is used to indicate that the slice
249 /// referenced by the handle will no longer be mutated. Once the conversion
250 /// is done, the handle can be cloned and shared across threads.
251 ///
252 /// # Examples
253 ///
254 /// ```
255 /// use ntex_bytes::{BytesMut, BufMut};
256 /// use std::thread;
257 ///
258 /// let mut b = BytesMut::with_capacity(64);
259 /// b.put("hello world");
260 /// let b1 = b.freeze();
261 /// let b2 = b1.clone();
262 ///
263 /// let th = thread::spawn(move || {
264 /// assert_eq!(b1, b"hello world");
265 /// });
266 ///
267 /// assert_eq!(b2, b"hello world");
268 /// th.join().unwrap();
269 /// ```
270 #[inline]
271 #[must_use]
272 pub fn freeze(self) -> Bytes {
273 Bytes {
274 storage: self.storage.freeze(),
275 }
276 }
277
278 /// Removes the bytes from the current view, returning them in a
279 /// `Bytes` instance.
280 ///
281 /// Afterwards, `self` will be empty, but will retain any additional
282 /// capacity that it had before the operation. This is identical to
283 /// `self.split_to(self.len())`.
284 ///
285 /// This is an `O(1)` operation that just increases the reference count and
286 /// sets a few indices.
287 ///
288 /// # Examples
289 ///
290 /// ```
291 /// use ntex_bytes::{BytesMut, BufMut};
292 ///
293 /// let mut buf = BytesMut::with_capacity(1024);
294 /// buf.put(&b"hello world"[..]);
295 ///
296 /// let other = buf.take();
297 ///
298 /// assert!(buf.is_empty());
299 /// assert_eq!(1013, buf.capacity());
300 ///
301 /// assert_eq!(other, b"hello world"[..]);
302 /// ```
303 #[inline]
304 #[must_use]
305 pub fn take(&mut self) -> Bytes {
306 Bytes {
307 storage: self.storage.split_to(self.len()),
308 }
309 }
310
311 /// Splits the buffer into two at the given index.
312 ///
313 /// Afterwards `self` contains elements `[at, len)`, and the returned `Bytes`
314 /// contains elements `[0, at)`.
315 ///
316 /// This is an `O(1)` operation that just increases the reference count and
317 /// sets a few indices.
318 ///
319 /// # Examples
320 ///
321 /// ```
322 /// use ntex_bytes::BytesMut;
323 ///
324 /// let mut a = BytesMut::copy_from_slice(&b"hello world"[..]);
325 /// let mut b = a.split_to(5);
326 ///
327 /// a[0] = b'!';
328 ///
329 /// assert_eq!(&a[..], b"!world");
330 /// assert_eq!(&b[..], b"hello");
331 /// ```
332 ///
333 /// # Panics
334 ///
335 /// Panics if `at > len`.
336 #[inline]
337 #[must_use]
338 pub fn split_to(&mut self, at: usize) -> Bytes {
339 self.split_to_checked(at)
340 .expect("at value must be <= self.len()`")
341 }
342
343 /// Advance the internal cursor.
344 ///
345 /// Afterwards `self` contains elements `[cnt, len)`.
346 /// This is an `O(1)` operation.
347 ///
348 /// # Examples
349 ///
350 /// ```
351 /// use ntex_bytes::BytesMut;
352 ///
353 /// let mut a = BytesMut::copy_from_slice(&b"hello world"[..]);
354 /// a.advance_to(5);
355 ///
356 /// a[0] = b'!';
357 ///
358 /// assert_eq!(&a[..], b"!world");
359 /// ```
360 ///
361 /// # Panics
362 ///
363 /// Panics if `cnt > len`.
364 #[inline]
365 pub fn advance_to(&mut self, cnt: usize) {
366 unsafe {
367 self.storage.set_start(cnt);
368 }
369 }
370
371 /// Splits the bytes into two at the given index.
372 ///
373 /// Returns `None` if `at > len`.
374 #[inline]
375 #[must_use]
376 pub fn split_to_checked(&mut self, at: usize) -> Option<Bytes> {
377 if at <= self.len() {
378 Some(Bytes {
379 storage: self.storage.split_to(at),
380 })
381 } else {
382 None
383 }
384 }
385
386 /// Shortens the buffer, keeping the first `len` bytes and dropping the
387 /// rest.
388 ///
389 /// If `len` is greater than the buffer's current length, this has no
390 /// effect.
391 ///
392 /// `truncate(0)` on a buffer that is not shared with any other handle
393 /// also reclaims the capacity in front of the current view, see
394 /// [`clear`](Self::clear).
395 ///
396 /// # Examples
397 ///
398 /// ```
399 /// use ntex_bytes::BytesMut;
400 ///
401 /// let mut buf = BytesMut::copy_from_slice(&b"hello world"[..]);
402 /// buf.truncate(5);
403 /// assert_eq!(buf, b"hello"[..]);
404 /// ```
405 #[inline]
406 pub fn truncate(&mut self, len: usize) {
407 self.storage.truncate(len);
408 }
409
410 /// Clears the buffer, removing all data.
411 ///
412 /// If no other handle refers to the underlying buffer (see
413 /// [`is_unique`](Self::is_unique)), the view is reset to the start of the
414 /// allocation, so the full capacity becomes available again.
415 ///
416 /// # Examples
417 ///
418 /// ```
419 /// use ntex_bytes::BytesMut;
420 ///
421 /// let mut buf = BytesMut::copy_from_slice(&b"hello world"[..]);
422 /// buf.clear();
423 /// assert!(buf.is_empty());
424 /// ```
425 #[inline]
426 pub fn clear(&mut self) {
427 self.truncate(0);
428 }
429
430 /// Resizes the buffer so that `len` is equal to `new_len`.
431 ///
432 /// If `new_len` is greater than `len`, the buffer is extended by the
433 /// difference with each additional byte set to `value`. If `new_len` is
434 /// less than `len`, the buffer is simply truncated.
435 ///
436 /// # Panics
437 ///
438 /// Panics if `new_len` exceeds `u32::MAX` minus the buffer
439 /// header size, just under 4 GiB.
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// use ntex_bytes::BytesMut;
445 ///
446 /// let mut buf = BytesMut::new();
447 ///
448 /// buf.resize(3, 0x1);
449 /// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);
450 ///
451 /// buf.resize(2, 0x2);
452 /// assert_eq!(&buf[..], &[0x1, 0x1]);
453 ///
454 /// buf.resize(4, 0x3);
455 /// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
456 /// ```
457 #[inline]
458 pub fn resize(&mut self, new_len: usize, value: u8) {
459 self.storage.resize(new_len, value);
460 }
461
462 /// Sets the length of the buffer.
463 ///
464 /// This will explicitly set the size of the buffer without actually
465 /// modifying the data, so it is up to the caller to ensure that the data
466 /// has been initialized.
467 ///
468 /// # Examples
469 ///
470 /// ```
471 /// use ntex_bytes::BytesMut;
472 ///
473 /// let mut b = BytesMut::copy_from_slice(&b"hello world"[..]);
474 ///
475 /// unsafe {
476 /// b.set_len(5);
477 /// }
478 ///
479 /// assert_eq!(&b[..], b"hello");
480 ///
481 /// unsafe {
482 /// b.set_len(11);
483 /// }
484 ///
485 /// assert_eq!(&b[..], b"hello world");
486 /// ```
487 ///
488 /// # Safety
489 ///
490 /// Caller must ensure that data has been initialized.
491 ///
492 /// # Panics
493 ///
494 /// Panics if `len > self.capacity()`.
495 #[inline]
496 pub unsafe fn set_len(&mut self, len: usize) {
497 self.storage.set_len(len);
498 }
499
500 /// Reserves capacity for at least `additional` more bytes to be inserted
501 /// into the given `BytesMut`.
502 ///
503 /// Before allocating new buffer space, the function will attempt to reclaim
504 /// space in the existing buffer. If the current handle references a small
505 /// view in the original buffer and all other handles have been dropped,
506 /// and the requested capacity is less than or equal to the existing
507 /// buffer's capacity, then the current view will be copied to the front of
508 /// the buffer and the handle will take ownership of the full buffer.
509 ///
510 /// Otherwise a unique buffer that is not a pooled page is reallocated,
511 /// often in place, and a new buffer is allocated in all other cases. The
512 /// new capacity is at least twice the current length, so appending in
513 /// small steps reallocates a logarithmic number of times. Use
514 /// [`reserve_exact`](Self::reserve_exact) to avoid the doubling.
515 ///
516 /// A buffer with a [`page_size`](Self::page_size) moves to a page of the
517 /// smallest size that fits the new capacity, but not smaller than its
518 /// current page size, the old page returns to the page cache. Above the
519 /// largest page size, a regular buffer without a page size is allocated.
520 ///
521 /// # Panics
522 ///
523 /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
524 /// header size, just under 4 GiB.
525 ///
526 /// # Examples
527 ///
528 /// In the following example, a new buffer is allocated.
529 ///
530 /// ```
531 /// use ntex_bytes::BytesMut;
532 ///
533 /// let mut buf = BytesMut::copy_from_slice(&b"hello"[..]);
534 /// buf.reserve(64);
535 /// assert!(buf.capacity() >= 69);
536 /// ```
537 ///
538 /// In the following example, the existing buffer is reclaimed.
539 ///
540 /// ```
541 /// use ntex_bytes::{BytesMut, BufMut};
542 ///
543 /// let mut buf = BytesMut::with_capacity(128);
544 /// buf.put(&[0; 64][..]);
545 ///
546 /// let ptr = buf.as_ptr();
547 /// let other = buf.take();
548 ///
549 /// assert!(buf.is_empty());
550 /// assert_eq!(buf.capacity(), 64);
551 ///
552 /// drop(other);
553 /// buf.reserve(128);
554 ///
555 /// assert_eq!(buf.capacity(), 128);
556 /// assert_eq!(buf.as_ptr(), ptr);
557 /// ```
558 #[inline]
559 pub fn reserve(&mut self, additional: usize) {
560 self.storage.reserve(additional);
561 }
562
563 /// Reserves capacity for exactly `additional` more bytes to be inserted
564 /// into the given `BytesMut`.
565 ///
566 /// Behaves like [`reserve`](Self::reserve), it reclaims the existing buffer
567 /// when possible and reallocates a unique buffer, but a new allocation is
568 /// sized to hold exactly `additional` more bytes instead of growing to at
569 /// least twice the current length. The allocation size is the new capacity
570 /// plus the buffer header, [`METADATA_SIZE`](crate::METADATA_SIZE) bytes.
571 /// The contents are not moved when the buffer already has enough remaining
572 /// capacity.
573 ///
574 /// The capacity is not rounded up to a page size, a buffer with a
575 /// [`page_size`](Self::page_size) loses it unless the new capacity is a page
576 /// capacity.
577 ///
578 /// # Panics
579 ///
580 /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
581 /// header size, just under 4 GiB.
582 ///
583 /// # Examples
584 ///
585 /// ```
586 /// use ntex_bytes::BytesMut;
587 ///
588 /// let mut buf = BytesMut::copy_from_slice(&[0; 1000][..]);
589 /// buf.reserve_exact(24);
590 /// assert_eq!(buf.capacity(), 1024);
591 ///
592 /// // enough remaining capacity keeps the current buffer
593 /// let ptr = buf.as_ptr();
594 /// buf.reserve_exact(24);
595 /// assert_eq!(buf.as_ptr(), ptr);
596 /// ```
597 #[inline]
598 pub fn reserve_exact(&mut self, additional: usize) {
599 self.storage.reserve_exact(additional);
600 }
601
602 /// Grows the buffer by one step if its remaining capacity is less than
603 /// the low threshold of its page size.
604 ///
605 /// Nothing happens when the remaining capacity is at least
606 /// [`BytePageSize::low`](crate::BytePageSize::low) of the buffer's
607 /// [`page_size`](Self::page_size), 1 KiB for a 16 KiB page and 4 KiB
608 /// for a buffer without a page size.
609 ///
610 /// If the allocation holds the data and
611 /// [`BytePageSize::half_capacity`](crate::BytePageSize::half_capacity)
612 /// more bytes, it is reused: a unique buffer moves its data to the start
613 /// of the allocation, a shared buffer with a page size moves to a page of
614 /// the same size. Otherwise a buffer with a page size moves to a page of
615 /// the next larger page size, the old page returns to the page cache. A
616 /// buffer without a page size, or with the largest page size, grows its
617 /// capacity by its current capacity, by at least 112 bytes and by at most
618 /// 64 KiB, like [`reserve_exact`](Self::reserve_exact) does: a unique
619 /// buffer is reallocated, often in place, otherwise the data is copied
620 /// into a new buffer.
621 ///
622 /// # Panics
623 ///
624 /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
625 /// header size, just under 4 GiB.
626 ///
627 /// # Examples
628 ///
629 /// ```
630 /// use ntex_bytes::{BytePageSize, BytesMut};
631 ///
632 /// let mut buf = BytesMut::with_page_size(BytePageSize::Size4);
633 /// buf.extend_from_slice(b"hello");
634 ///
635 /// // the remaining capacity is above the low threshold, the buffer is kept
636 /// buf.reserve_more();
637 /// assert_eq!(buf.page_size(), BytePageSize::Size4);
638 ///
639 /// buf.extend_from_slice(&[0; 4000]);
640 /// buf.reserve_more();
641 /// assert_eq!(buf.page_size(), BytePageSize::Size8);
642 /// assert_eq!(buf.capacity(), BytePageSize::Size8.capacity());
643 /// assert_eq!(&buf[..5], b"hello");
644 ///
645 /// // consumed data makes room, the page is compacted in place
646 /// let mut buf = BytesMut::with_page_size(BytePageSize::Size4);
647 /// buf.extend_from_slice(&[0; 4000]);
648 /// buf.advance_to(3990);
649 /// buf.reserve_more();
650 /// assert_eq!(buf.page_size(), BytePageSize::Size4);
651 /// assert_eq!(buf.capacity(), BytePageSize::Size4.capacity());
652 ///
653 /// let mut buf = BytesMut::with_capacity(1000);
654 /// buf.reserve_more();
655 /// assert_eq!(buf.capacity(), 2000);
656 ///
657 /// let mut buf = BytesMut::with_capacity(1024 * 1024);
658 /// buf.extend_from_slice(&vec![0; 1024 * 1024]);
659 /// buf.reserve_more();
660 /// assert_eq!(buf.capacity(), 1024 * 1024 + 64 * 1024);
661 /// ```
662 #[inline]
663 pub fn reserve_more(&mut self) {
664 self.storage.reserve_more();
665 }
666
667 /// Appends a byte slice to the buffer.
668 ///
669 /// Additional capacity is reserved automatically when needed.
670 ///
671 /// # Examples
672 ///
673 /// ```
674 /// use ntex_bytes::BytesMut;
675 ///
676 /// let mut buf = BytesMut::with_capacity(0);
677 /// buf.extend_from_slice(b"aaabbb");
678 /// buf.extend_from_slice(b"cccddd");
679 ///
680 /// assert_eq!(b"aaabbbcccddd", &buf[..]);
681 /// ```
682 #[inline]
683 pub fn extend_from_slice(&mut self, extend: &[u8]) {
684 self.put_slice(extend);
685 }
686
687 /// Returns an iterator over the bytes contained by the buffer.
688 ///
689 /// # Examples
690 ///
691 /// ```
692 /// use ntex_bytes::{Buf, BytesMut};
693 ///
694 /// let buf = BytesMut::copy_from_slice(&b"abc"[..]);
695 /// let mut iter = buf.iter();
696 ///
697 /// assert_eq!(iter.next().map(|b| *b), Some(b'a'));
698 /// assert_eq!(iter.next().map(|b| *b), Some(b'b'));
699 /// assert_eq!(iter.next().map(|b| *b), Some(b'c'));
700 /// assert_eq!(iter.next(), None);
701 /// ```
702 #[inline]
703 pub fn iter(&'_ self) -> std::slice::Iter<'_, u8> {
704 self.chunk().iter()
705 }
706}
707
708impl_buf!(BytesMut {});
709
710impl_slice_traits!(BytesMut);
711
712impl_partial_eq!(BytesMut);
713
714impl BufMut for BytesMut {
715 #[inline]
716 fn remaining_mut(&self) -> usize {
717 self.storage.remaining()
718 }
719
720 #[inline]
721 unsafe fn advance_mut(&mut self, cnt: usize) {
722 // This call will panic if `cnt` is too big
723 self.storage.set_len(self.len() + cnt);
724 }
725
726 #[inline]
727 fn chunk_mut(&mut self) -> &mut UninitSlice {
728 self.storage.spare_mut()
729 }
730
731 #[inline]
732 fn put<T: Buf>(&mut self, mut src: T)
733 where
734 Self: Sized,
735 {
736 self.reserve(src.remaining());
737 while src.has_remaining() {
738 let chunk = src.chunk();
739 let len = chunk.len();
740 self.put_slice(chunk);
741 src.advance(len);
742 }
743 }
744
745 #[inline]
746 fn put_slice(&mut self, src: &[u8]) {
747 self.reserve(src.len());
748 self.storage.put_slice_partial(src);
749 }
750
751 #[inline]
752 fn put_u8(&mut self, n: u8) {
753 self.reserve(1);
754 self.storage.put_u8(n);
755 }
756
757 #[inline]
758 fn put_i8(&mut self, n: i8) {
759 self.put_u8(n as u8);
760 }
761}
762
763/// Interop with the `bytes` crate: like `bytes::BytesMut`, the buffer grows on
764/// demand, so `remaining_mut()` reports `usize::MAX - len` and `chunk_mut()`
765/// is never empty. The native [`BufMut`] impl reports spare capacity instead.
766unsafe impl bytes::buf::BufMut for BytesMut {
767 #[inline]
768 fn remaining_mut(&self) -> usize {
769 usize::MAX - self.len()
770 }
771
772 #[inline]
773 unsafe fn advance_mut(&mut self, cnt: usize) {
774 let remaining = BufMut::remaining_mut(self);
775 assert!(
776 cnt <= remaining,
777 "cannot advance past `remaining_mut`: {cnt:?} <= {remaining:?}"
778 );
779 BufMut::advance_mut(self, cnt);
780 }
781
782 #[inline]
783 fn chunk_mut(&mut self) -> &mut bytes::buf::UninitSlice {
784 if BufMut::remaining_mut(self) == 0 {
785 self.reserve(64);
786 }
787 unsafe {
788 let ptr = self.storage.as_ptr();
789 bytes::buf::UninitSlice::from_raw_parts_mut(
790 ptr.add(self.len()),
791 BufMut::remaining_mut(self),
792 )
793 }
794 }
795
796 #[inline]
797 fn put<T: bytes::buf::Buf>(&mut self, mut src: T)
798 where
799 Self: Sized,
800 {
801 self.reserve(src.remaining());
802 while src.has_remaining() {
803 let chunk = src.chunk();
804 let len = chunk.len();
805 BufMut::put_slice(self, chunk);
806 src.advance(len);
807 }
808 }
809
810 #[inline]
811 fn put_slice(&mut self, src: &[u8]) {
812 BufMut::put_slice(self, src);
813 }
814
815 #[inline]
816 fn put_bytes(&mut self, val: u8, cnt: usize) {
817 self.reserve(cnt);
818 unsafe {
819 ptr::write_bytes(self.storage.as_ptr().add(self.len()), val, cnt);
820 BufMut::advance_mut(self, cnt);
821 }
822 }
823
824 #[inline]
825 fn put_u8(&mut self, n: u8) {
826 BufMut::put_u8(self, n);
827 }
828
829 #[inline]
830 fn put_i8(&mut self, n: i8) {
831 BufMut::put_i8(self, n);
832 }
833}
834
835impl AsMut<[u8]> for BytesMut {
836 #[inline]
837 fn as_mut(&mut self) -> &mut [u8] {
838 self.storage.as_mut()
839 }
840}
841
842impl DerefMut for BytesMut {
843 #[inline]
844 fn deref_mut(&mut self) -> &mut [u8] {
845 self.storage.as_mut()
846 }
847}
848
849impl Eq for BytesMut {}
850
851impl PartialEq for BytesMut {
852 #[inline]
853 fn eq(&self, other: &BytesMut) -> bool {
854 self.storage.as_ref() == other.storage.as_ref()
855 }
856}
857
858impl borrow::BorrowMut<[u8]> for BytesMut {
859 #[inline]
860 fn borrow_mut(&mut self) -> &mut [u8] {
861 self.as_mut()
862 }
863}
864
865impl PartialEq<Bytes> for BytesMut {
866 fn eq(&self, other: &Bytes) -> bool {
867 other[..] == self[..]
868 }
869}
870
871impl PartialEq<BytesMut> for Bytes {
872 fn eq(&self, other: &BytesMut) -> bool {
873 *other == *self
874 }
875}
876
877impl_read!(BytesMut);
878
879impl io::Write for BytesMut {
880 fn write(&mut self, src: &[u8]) -> Result<usize, io::Error> {
881 self.extend_from_slice(src);
882 Ok(src.len())
883 }
884
885 fn flush(&mut self) -> Result<(), io::Error> {
886 Ok(())
887 }
888}
889
890impl fmt::Write for BytesMut {
891 #[inline]
892 fn write_str(&mut self, s: &str) -> fmt::Result {
893 self.extend_from_slice(s.as_bytes());
894 Ok(())
895 }
896}
897
898impl Clone for BytesMut {
899 #[inline]
900 fn clone(&self) -> BytesMut {
901 BytesMut::from(&self[..])
902 }
903}
904
905impl FromIterator<u8> for BytesMut {
906 fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
907 let iter = into_iter.into_iter();
908 let (min, maybe_max) = iter.size_hint();
909
910 let mut out = BytesMut::with_capacity(maybe_max.unwrap_or(min));
911 out.extend(iter);
912 out
913 }
914}
915
916impl<'a> FromIterator<&'a u8> for BytesMut {
917 fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
918 into_iter.into_iter().copied().collect::<BytesMut>()
919 }
920}
921
922impl Extend<u8> for BytesMut {
923 fn extend<T>(&mut self, iter: T)
924 where
925 T: IntoIterator<Item = u8>,
926 {
927 let iter = iter.into_iter();
928 self.reserve(iter.size_hint().0);
929 for b in iter {
930 self.put_u8(b);
931 }
932 }
933}
934
935impl<'a> Extend<&'a u8> for BytesMut {
936 fn extend<T>(&mut self, iter: T)
937 where
938 T: IntoIterator<Item = &'a u8>,
939 {
940 self.extend(iter.into_iter().copied());
941 }
942}
943
944impl From<BytesMut> for Bytes {
945 #[inline]
946 fn from(b: BytesMut) -> Self {
947 b.freeze()
948 }
949}
950
951impl<'a> From<&'a [u8]> for BytesMut {
952 #[inline]
953 fn from(src: &'a [u8]) -> BytesMut {
954 BytesMut::copy_from_slice(src)
955 }
956}
957
958impl<const N: usize> From<[u8; N]> for BytesMut {
959 #[inline]
960 fn from(src: [u8; N]) -> BytesMut {
961 BytesMut::copy_from_slice(src)
962 }
963}
964
965impl<'a, const N: usize> From<&'a [u8; N]> for BytesMut {
966 #[inline]
967 fn from(src: &'a [u8; N]) -> BytesMut {
968 BytesMut::copy_from_slice(src)
969 }
970}
971
972impl<'a> From<&'a str> for BytesMut {
973 #[inline]
974 fn from(src: &'a str) -> BytesMut {
975 BytesMut::from(src.as_bytes())
976 }
977}
978
979impl From<Bytes> for BytesMut {
980 #[inline]
981 fn from(src: Bytes) -> BytesMut {
982 match src.storage.try_into_vec() {
983 Ok(storage) => BytesMut { storage },
984 Err(storage) => BytesMut::copy_from_slice(storage.as_ref()),
985 }
986 }
987}
988
989impl From<&Bytes> for BytesMut {
990 #[inline]
991 fn from(src: &Bytes) -> BytesMut {
992 BytesMut::copy_from_slice(&src[..])
993 }
994}
995
996#[cfg(test)]
997mod tests {
998 use super::*;
999
1000 #[test]
1001 fn growth_is_amortized() {
1002 let mut buf = BytesMut::with_capacity(0);
1003 let mut cap = buf.capacity();
1004 let mut reallocs = 0;
1005 for _ in 0..10_000 {
1006 buf.put_slice(b"abcdefgh");
1007 if buf.capacity() != cap {
1008 reallocs += 1;
1009 cap = buf.capacity();
1010 }
1011 }
1012 assert_eq!(buf.len(), 80_000);
1013 assert!(reallocs <= 16, "reallocs: {reallocs}");
1014
1015 // writes through `io::Write` and `fmt::Write` grow the same way
1016 let mut buf = BytesMut::with_capacity(0);
1017 for i in 0..1000 {
1018 std::fmt::Write::write_fmt(&mut buf, format_args!("{i:08}")).unwrap();
1019 }
1020 assert_eq!(buf.len(), 8000);
1021 assert!(buf.capacity() < 16_000);
1022 }
1023
1024 #[test]
1025 fn growth_of_little_data_is_exact() {
1026 let mut buf = BytesMut::copy_from_slice(b"hello");
1027 buf.reserve(64 * 1024);
1028 assert_eq!(buf.capacity(), 5 + 64 * 1024);
1029
1030 // a buffer shared with split off `Bytes`
1031 let mut buf = BytesMut::with_capacity(1024);
1032 buf.extend_from_slice(&[1; 1024]);
1033 let head = buf.split_to(1000);
1034 buf.reserve(4096);
1035 assert_eq!(buf.capacity(), 24 + 4096);
1036 assert_eq!(&head[..], &[1; 1000][..]);
1037 }
1038
1039 #[test]
1040 fn from_unique_bytes_reuses_buffer() {
1041 let mut buf = BytesMut::with_capacity(256);
1042 buf.extend_from_slice(&[1; 64]);
1043 let b = buf.freeze();
1044 let ptr = b.as_ptr();
1045
1046 let mut m = BytesMut::from(b);
1047 assert_eq!(m.as_ptr(), ptr);
1048 assert_eq!(&m[..], &[1; 64][..]);
1049 assert_eq!(m.capacity(), 256);
1050
1051 // spare capacity past the view is writable
1052 m.extend_from_slice(&[2; 192]);
1053 assert_eq!(m.as_ptr(), ptr);
1054 assert_eq!(&m[64..], &[2; 192][..]);
1055 }
1056
1057 #[test]
1058 fn from_unique_bytes_subview() {
1059 let mut buf = BytesMut::with_capacity(256);
1060 buf.extend_from_slice(&[1; 128]);
1061 let mut b = buf.freeze();
1062 let head = b.split_to(32);
1063 drop(head);
1064 b.truncate(64);
1065 let ptr = b.as_ptr();
1066
1067 let mut m = BytesMut::from(b);
1068 assert_eq!(m.as_ptr(), ptr);
1069 assert_eq!(m.len(), 64);
1070 assert_eq!(m.capacity(), 256 - 32);
1071
1072 // the dropped tail of the view is spare capacity again
1073 m.extend_from_slice(&[3; 160]);
1074 assert_eq!(m.as_ptr(), ptr);
1075 assert_eq!(&m[..64], &[1; 64][..]);
1076 assert_eq!(&m[64..], &[3; 160][..]);
1077 }
1078
1079 #[test]
1080 fn from_shared_bytes_copies() {
1081 let b = BytesMut::copy_from_slice([1; 64]).freeze();
1082 let b2 = b.clone();
1083
1084 let mut m = BytesMut::from(b);
1085 assert_ne!(m.as_ptr(), b2.as_ptr());
1086 m[0] = 2;
1087 assert_eq!(&b2[..], &[1; 64][..]);
1088
1089 // the buffer is still referenced by a `BytesMut`
1090 let mut buf = BytesMut::with_capacity(256);
1091 buf.extend_from_slice(&[1; 64]);
1092 let b = buf.take();
1093 let m = BytesMut::from(b);
1094 assert_ne!(m.as_ptr(), buf.as_ptr());
1095 buf.extend_from_slice(&[2; 64]);
1096 assert_eq!(&m[..], &[1; 64][..]);
1097 }
1098
1099 // Run under miri: without `Acquire`, the header update races with the
1100 // read made by the other thread before it released its handle.
1101 #[test]
1102 fn from_bytes_synchronizes_with_release() {
1103 let b = BytesMut::copy_from_slice([1; 64]).freeze();
1104 let other = b.clone();
1105 let handle = std::thread::spawn(move || {
1106 let val = other[0];
1107 drop(other);
1108 val
1109 });
1110
1111 let ptr = b.as_ptr();
1112 let mut storage = b.storage;
1113 let mut m = loop {
1114 match storage.try_into_vec() {
1115 Ok(storage) => break BytesMut { storage },
1116 Err(st) => {
1117 storage = st;
1118 std::thread::yield_now();
1119 }
1120 }
1121 };
1122 assert_eq!(m.as_ptr(), ptr);
1123 m[0] = 2;
1124 assert_eq!(handle.join().unwrap(), 1);
1125 }
1126
1127 #[test]
1128 fn from_inline_and_static_bytes() {
1129 let m = BytesMut::from(Bytes::copy_from_slice(b"inline"));
1130 assert_eq!(&m[..], b"inline");
1131
1132 let m = BytesMut::from(Bytes::from_static(&[1; 64]));
1133 assert_eq!(&m[..], &[1; 64][..]);
1134 }
1135
1136 #[test]
1137 fn bvec_read() {
1138 use std::io::Read;
1139
1140 let mut b = BytesMut::copy_from_slice(b"123");
1141
1142 let mut buf = [0; 10];
1143 assert_eq!(b.read(&mut buf).unwrap(), 3);
1144 assert_eq!(b.len(), 0);
1145 assert_eq!(buf, [49, 50, 51, 0, 0, 0, 0, 0, 0, 0]);
1146 }
1147
1148 #[test]
1149 fn from_bytes_ref() {
1150 let b = Bytes::from_static(b"hello");
1151 let mut m = BytesMut::from(&b);
1152 m.extend_from_slice(b"!");
1153 assert_eq!(m, "hello!");
1154 assert_eq!(b, "hello");
1155 }
1156}