ntex_bytes/bvec.rs
1use std::{borrow, fmt, io, ops::DerefMut, ptr};
2
3use crate::{Buf, BufMut, BytePageSize, Bytes, SpareWriter, 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_slice(b"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. If the cache has no
89 /// page of the requested size but has one of the next smaller size, see
90 /// [`BytePageSize::prev`], that page is used instead, the buffer then has
91 /// the smaller capacity and page size.
92 ///
93 /// When the buffer grows, it moves to a page of the size that fits the
94 /// new capacity, see [`reserve`](Self::reserve). Growth always uses a
95 /// page of exactly that size. Above the largest page size the buffer is
96 /// a regular allocation without a page size, it is freed when dropped.
97 ///
98 /// [`BytePageSize::Unset`] has the allocation size of
99 /// [`BytePageSize::Size64`], it creates a `Size64` page.
100 ///
101 /// # Examples
102 ///
103 /// ```
104 /// use ntex_bytes::{BytePageSize, BytesMut};
105 ///
106 /// let mut buf = BytesMut::with_page_size(BytePageSize::Size4);
107 /// assert_eq!(buf.capacity(), BytePageSize::Size4.capacity());
108 /// assert_eq!(buf.page_size(), BytePageSize::Size4);
109 ///
110 /// buf.extend_from_slice(&[0; 5000]);
111 /// assert_eq!(buf.page_size(), BytePageSize::Size8);
112 /// ```
113 #[inline]
114 #[must_use]
115 pub fn with_page_size(size: BytePageSize) -> BytesMut {
116 let size = if size == BytePageSize::Unset {
117 BytePageSize::Size64
118 } else {
119 size
120 };
121 BytesMut {
122 storage: StorageVec::sized(size),
123 }
124 }
125
126 /// Creates a new `BytesMut` from the page cache, like
127 /// [`with_page_size`](Self::with_page_size), with the allocation charged
128 /// to `tracker`.
129 ///
130 /// The allocation stays charged while any `BytesMut` or [`Bytes`]
131 /// handle refers to it. A buffer that grows into a new allocation
132 /// charges it to the same tracker, the old allocation is uncharged when
133 /// its last handle is dropped. Copies made by [`Clone`], conversions or
134 /// [`Bytes::trimdown`] are not charged.
135 ///
136 /// # Examples
137 ///
138 /// ```
139 /// use ntex_bytes::{BytePageSize, BytesMut, BytesTracker};
140 ///
141 /// let tracker = BytesTracker::new();
142 /// let buf = BytesMut::with_page_size_in(BytePageSize::Size4, &tracker);
143 /// assert_eq!(tracker.snapshot().live_bytes, 4096);
144 /// assert_eq!(tracker.snapshot().live_allocations, 1);
145 ///
146 /// drop(buf);
147 /// assert_eq!(tracker.snapshot().live_bytes, 0);
148 /// ```
149 #[cfg(feature = "tracker")]
150 #[cfg_attr(docsrs, doc(cfg(feature = "tracker")))]
151 #[inline]
152 #[must_use]
153 pub fn with_page_size_in(size: BytePageSize, tracker: &crate::BytesTracker) -> BytesMut {
154 let size = if size == BytePageSize::Unset {
155 BytePageSize::Size64
156 } else {
157 size
158 };
159 BytesMut {
160 storage: StorageVec::sized_in(size, tracker),
161 }
162 }
163
164 /// Charges the allocation of the buffer to `tracker`.
165 ///
166 /// The allocation stays charged as described in
167 /// [`with_page_size_in`](Self::with_page_size_in). If the allocation is
168 /// charged to a different tracker, the charge moves to `tracker`, also
169 /// while it is shared with [`Bytes`] handles. Setting the tracker the
170 /// buffer is already charged to does nothing.
171 ///
172 /// # Examples
173 ///
174 /// ```
175 /// use ntex_bytes::{BytesMut, BytesTracker};
176 ///
177 /// let tracker = BytesTracker::new();
178 /// let mut buf = BytesMut::with_capacity(256);
179 /// buf.extend_from_slice(&[0; 128]);
180 ///
181 /// let head = buf.split_to(64);
182 /// buf.set_tracker(&tracker);
183 /// assert!(buf.tracker().unwrap().ptr_eq(&tracker));
184 /// assert_eq!(tracker.snapshot().live_allocations, 1);
185 ///
186 /// let other = BytesTracker::new();
187 /// buf.set_tracker(&other);
188 /// assert_eq!(tracker.snapshot().live_allocations, 0);
189 /// assert_eq!(other.snapshot().live_allocations, 1);
190 ///
191 /// drop((buf, head));
192 /// assert_eq!(other.snapshot().live_allocations, 0);
193 /// ```
194 #[cfg(feature = "tracker")]
195 #[cfg_attr(docsrs, doc(cfg(feature = "tracker")))]
196 #[inline]
197 pub fn set_tracker(&mut self, tracker: &crate::BytesTracker) {
198 self.storage.set_tracker(tracker);
199 }
200
201 /// Returns the tracker charged with the allocation of the buffer.
202 #[cfg(feature = "tracker")]
203 #[cfg_attr(docsrs, doc(cfg(feature = "tracker")))]
204 #[inline]
205 #[must_use]
206 pub fn tracker(&self) -> Option<&crate::BytesTracker> {
207 self.storage.tracker()
208 }
209
210 /// Returns the page size of the buffer.
211 ///
212 /// The page size is derived from the allocation size, a buffer whose
213 /// allocation, header included, is exactly a page size belongs to that
214 /// page size. This covers buffers created by
215 /// [`with_page_size`](Self::with_page_size), converted from a pooled
216 /// [`BytePage`](crate::BytePage), or created with a page
217 /// [`capacity`](BytePageSize::capacity). They return to the page cache
218 /// when the last reference is dropped. Other buffers return
219 /// [`BytePageSize::Unset`], they are freed when dropped.
220 #[inline]
221 pub fn page_size(&self) -> BytePageSize {
222 self.storage.page_size()
223 }
224
225 /// Creates a `BytesMut` by copying a byte slice.
226 #[inline]
227 #[must_use]
228 pub fn copy_from_slice<T: AsRef<[u8]>>(src: T) -> Self {
229 let slice = src.as_ref();
230 BytesMut {
231 storage: StorageVec::from_slice(slice.len(), slice),
232 }
233 }
234
235 /// Creates a new `BytesMut` with default capacity.
236 ///
237 /// Resulting object has length 0 and unspecified capacity.
238 ///
239 /// # Examples
240 ///
241 /// ```
242 /// use ntex_bytes::{BytesMut, BufMut};
243 ///
244 /// let mut bytes = BytesMut::new();
245 ///
246 /// assert_eq!(0, bytes.len());
247 ///
248 /// bytes.reserve(2);
249 /// bytes.put_slice(b"xy");
250 ///
251 /// assert_eq!(&b"xy"[..], &bytes[..]);
252 /// ```
253 #[inline]
254 #[must_use]
255 pub fn new() -> BytesMut {
256 BytesMut {
257 storage: StorageVec::with_capacity(crate::storage::MIN_CAPACITY),
258 }
259 }
260
261 /// Returns the number of bytes contained in this `BytesMut`.
262 ///
263 /// # Examples
264 ///
265 /// ```
266 /// use ntex_bytes::BytesMut;
267 ///
268 /// let b = BytesMut::copy_from_slice(&b"hello"[..]);
269 /// assert_eq!(b.len(), 5);
270 /// ```
271 #[inline]
272 pub fn len(&self) -> usize {
273 self.storage.len()
274 }
275
276 /// Returns `true` if the buffer is empty.
277 ///
278 /// # Examples
279 ///
280 /// ```
281 /// use ntex_bytes::BytesMut;
282 ///
283 /// let b = BytesMut::with_capacity(64);
284 /// assert!(b.is_empty());
285 /// ```
286 #[inline]
287 pub fn is_empty(&self) -> bool {
288 self.storage.len() == 0
289 }
290
291 /// Returns the number of bytes the `BytesMut` can hold without reallocating.
292 ///
293 /// # Examples
294 ///
295 /// ```
296 /// use ntex_bytes::BytesMut;
297 ///
298 /// let b = BytesMut::with_capacity(64);
299 /// assert_eq!(b.capacity(), 64);
300 /// ```
301 #[inline]
302 pub fn capacity(&self) -> usize {
303 self.storage.capacity()
304 }
305
306 /// Returns `true` if no other handle refers to the underlying buffer.
307 ///
308 /// Values split off with [`split_to`](Self::split_to) or frozen into
309 /// [`Bytes`] share the buffer with `self`. While they exist, clearing
310 /// `self` does not reclaim the capacity in front of it, and the whole
311 /// allocation stays alive as long as any of them does.
312 ///
313 /// # Examples
314 ///
315 /// ```
316 /// use ntex_bytes::BytesMut;
317 ///
318 /// let mut buf = BytesMut::with_capacity(64);
319 /// buf.extend_from_slice(&[0; 32]);
320 /// assert!(buf.is_unique());
321 ///
322 /// let head = buf.split_to(30);
323 /// assert!(!buf.is_unique());
324 ///
325 /// drop(head);
326 /// assert!(buf.is_unique());
327 /// ```
328 #[inline]
329 pub fn is_unique(&self) -> bool {
330 self.storage.is_unique()
331 }
332
333 /// Converts `self` into an immutable `Bytes`.
334 ///
335 /// The conversion is zero cost and is used to indicate that the slice
336 /// referenced by the handle will no longer be mutated. Once the conversion
337 /// is done, the handle can be cloned and shared across threads.
338 ///
339 /// # Examples
340 ///
341 /// ```
342 /// use ntex_bytes::{BytesMut, BufMut};
343 /// use std::thread;
344 ///
345 /// let mut b = BytesMut::with_capacity(64);
346 /// b.put_slice(b"hello world");
347 /// let b1 = b.freeze();
348 /// let b2 = b1.clone();
349 ///
350 /// let th = thread::spawn(move || {
351 /// assert_eq!(b1, b"hello world");
352 /// });
353 ///
354 /// assert_eq!(b2, b"hello world");
355 /// th.join().unwrap();
356 /// ```
357 #[inline]
358 #[must_use]
359 pub fn freeze(self) -> Bytes {
360 Bytes {
361 storage: self.storage.freeze(),
362 }
363 }
364
365 /// Removes the bytes from the current view, returning them in a
366 /// `Bytes` instance.
367 ///
368 /// Afterwards, `self` will be empty, but will retain any additional
369 /// capacity that it had before the operation. This is identical to
370 /// `self.split_to(self.len())`.
371 ///
372 /// This is an `O(1)` operation that just increases the reference count and
373 /// sets a few indices.
374 ///
375 /// # Examples
376 ///
377 /// ```
378 /// use ntex_bytes::{BytesMut, BufMut};
379 ///
380 /// let mut buf = BytesMut::with_capacity(1024);
381 /// buf.put(&b"hello world"[..]);
382 ///
383 /// let other = buf.take();
384 ///
385 /// assert!(buf.is_empty());
386 /// assert_eq!(1013, buf.capacity());
387 ///
388 /// assert_eq!(other, b"hello world"[..]);
389 /// ```
390 #[inline]
391 #[must_use]
392 pub fn take(&mut self) -> Bytes {
393 Bytes {
394 storage: self.storage.split_to(self.len()),
395 }
396 }
397
398 /// Splits the buffer into two at the given index.
399 ///
400 /// Afterwards `self` contains elements `[at, len)`, and the returned `Bytes`
401 /// contains elements `[0, at)`.
402 ///
403 /// This is an `O(1)` operation that just increases the reference count and
404 /// sets a few indices.
405 ///
406 /// # Examples
407 ///
408 /// ```
409 /// use ntex_bytes::BytesMut;
410 ///
411 /// let mut a = BytesMut::copy_from_slice(&b"hello world"[..]);
412 /// let mut b = a.split_to(5);
413 ///
414 /// a[0] = b'!';
415 ///
416 /// assert_eq!(&a[..], b"!world");
417 /// assert_eq!(&b[..], b"hello");
418 /// ```
419 ///
420 /// # Panics
421 ///
422 /// Panics if `at > len`.
423 #[inline]
424 #[must_use]
425 pub fn split_to(&mut self, at: usize) -> Bytes {
426 self.split_to_checked(at)
427 .expect("at value must be <= self.len()`")
428 }
429
430 /// Advance the internal cursor.
431 ///
432 /// Afterwards `self` contains elements `[cnt, len)`.
433 /// This is an `O(1)` operation.
434 ///
435 /// # Examples
436 ///
437 /// ```
438 /// use ntex_bytes::BytesMut;
439 ///
440 /// let mut a = BytesMut::copy_from_slice(&b"hello world"[..]);
441 /// a.advance_to(5);
442 ///
443 /// a[0] = b'!';
444 ///
445 /// assert_eq!(&a[..], b"!world");
446 /// ```
447 ///
448 /// # Panics
449 ///
450 /// Panics if `cnt > len`.
451 #[inline]
452 pub fn advance_to(&mut self, cnt: usize) {
453 // SAFETY: `set_start` checks `cnt <= len` before advancing within this live, exclusively
454 // owned view.
455 unsafe {
456 self.storage.set_start(cnt);
457 }
458 }
459
460 /// Splits the bytes into two at the given index.
461 ///
462 /// Returns `None` if `at > len`.
463 #[inline]
464 #[must_use]
465 pub fn split_to_checked(&mut self, at: usize) -> Option<Bytes> {
466 if at <= self.len() {
467 Some(Bytes {
468 storage: self.storage.split_to(at),
469 })
470 } else {
471 None
472 }
473 }
474
475 /// Shortens the buffer, keeping the first `len` bytes and dropping the
476 /// rest.
477 ///
478 /// If `len` is greater than the buffer's current length, this has no
479 /// effect.
480 ///
481 /// `truncate(0)` on a buffer that is not shared with any other handle
482 /// also reclaims the capacity in front of the current view, see
483 /// [`clear`](Self::clear).
484 ///
485 /// # Examples
486 ///
487 /// ```
488 /// use ntex_bytes::BytesMut;
489 ///
490 /// let mut buf = BytesMut::copy_from_slice(&b"hello world"[..]);
491 /// buf.truncate(5);
492 /// assert_eq!(buf, b"hello"[..]);
493 /// ```
494 #[inline]
495 pub fn truncate(&mut self, len: usize) {
496 self.storage.truncate(len);
497 }
498
499 /// Clears the buffer, removing all data.
500 ///
501 /// If no other handle refers to the underlying buffer (see
502 /// [`is_unique`](Self::is_unique)), the view is reset to the start of the
503 /// allocation, so the full capacity becomes available again.
504 ///
505 /// # Examples
506 ///
507 /// ```
508 /// use ntex_bytes::BytesMut;
509 ///
510 /// let mut buf = BytesMut::copy_from_slice(&b"hello world"[..]);
511 /// buf.clear();
512 /// assert!(buf.is_empty());
513 /// ```
514 #[inline]
515 pub fn clear(&mut self) {
516 self.truncate(0);
517 }
518
519 /// Resizes the buffer so that `len` is equal to `new_len`.
520 ///
521 /// If `new_len` is greater than `len`, the buffer is extended by the
522 /// difference with each additional byte set to `value`. If `new_len` is
523 /// less than `len`, the buffer is simply truncated.
524 ///
525 /// # Panics
526 ///
527 /// Panics if `new_len` exceeds `u32::MAX` minus the buffer
528 /// header size, just under 4 GiB.
529 ///
530 /// # Examples
531 ///
532 /// ```
533 /// use ntex_bytes::BytesMut;
534 ///
535 /// let mut buf = BytesMut::new();
536 ///
537 /// buf.resize(3, 0x1);
538 /// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);
539 ///
540 /// buf.resize(2, 0x2);
541 /// assert_eq!(&buf[..], &[0x1, 0x1]);
542 ///
543 /// buf.resize(4, 0x3);
544 /// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
545 /// ```
546 #[inline]
547 pub fn resize(&mut self, new_len: usize, value: u8) {
548 self.storage.resize(new_len, value);
549 }
550
551 /// Sets the length of the buffer.
552 ///
553 /// This will explicitly set the size of the buffer without actually
554 /// modifying the data, so it is up to the caller to ensure that the data
555 /// has been initialized.
556 ///
557 /// # Examples
558 ///
559 /// ```
560 /// use ntex_bytes::BytesMut;
561 ///
562 /// let mut b = BytesMut::copy_from_slice(&b"hello world"[..]);
563 ///
564 /// unsafe {
565 /// b.set_len(5);
566 /// }
567 ///
568 /// assert_eq!(&b[..], b"hello");
569 ///
570 /// unsafe {
571 /// b.set_len(11);
572 /// }
573 ///
574 /// assert_eq!(&b[..], b"hello world");
575 /// ```
576 ///
577 /// # Safety
578 ///
579 /// Caller must ensure that data has been initialized.
580 ///
581 /// # Panics
582 ///
583 /// Panics if `len > self.capacity()`.
584 #[inline]
585 pub unsafe fn set_len(&mut self, len: usize) {
586 self.storage.set_len(len);
587 }
588
589 /// Reserves capacity for at least `additional` more bytes to be inserted
590 /// into the given `BytesMut`.
591 ///
592 /// Before allocating new buffer space, the function will attempt to reclaim
593 /// space in the existing buffer. If the current handle references a small
594 /// view in the original buffer and all other handles have been dropped,
595 /// and the requested capacity is less than or equal to the existing
596 /// buffer's capacity, then the current view will be copied to the front of
597 /// the buffer and the handle will take ownership of the full buffer.
598 ///
599 /// Otherwise a unique buffer that is not a pooled page is reallocated,
600 /// often in place, and a new buffer is allocated in all other cases. The
601 /// new capacity is at least twice the current capacity and at least 8
602 /// bytes, like `Vec<u8>`, so appending in small steps reallocates a
603 /// logarithmic number of times. Use
604 /// [`reserve_exact`](Self::reserve_exact) to avoid the doubling.
605 ///
606 /// A buffer with a [`page_size`](Self::page_size) moves to a page of the
607 /// smallest size that fits the new capacity, but not smaller than its
608 /// current page size, the old page returns to the page cache. Above the
609 /// largest page size, a regular buffer without a page size is allocated.
610 ///
611 /// # Panics
612 ///
613 /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
614 /// header size, just under 4 GiB.
615 ///
616 /// # Examples
617 ///
618 /// In the following example, a new buffer is allocated.
619 ///
620 /// ```
621 /// use ntex_bytes::BytesMut;
622 ///
623 /// let mut buf = BytesMut::copy_from_slice(&b"hello"[..]);
624 /// buf.reserve(64);
625 /// assert!(buf.capacity() >= 69);
626 /// ```
627 ///
628 /// In the following example, the existing buffer is reclaimed.
629 ///
630 /// ```
631 /// use ntex_bytes::{BytesMut, BufMut};
632 ///
633 /// let mut buf = BytesMut::with_capacity(128);
634 /// buf.put(&[0; 64][..]);
635 ///
636 /// let ptr = buf.as_ptr();
637 /// let other = buf.take();
638 ///
639 /// assert!(buf.is_empty());
640 /// assert_eq!(buf.capacity(), 64);
641 ///
642 /// drop(other);
643 /// buf.reserve(128);
644 ///
645 /// assert_eq!(buf.capacity(), 128);
646 /// assert_eq!(buf.as_ptr(), ptr);
647 /// ```
648 #[inline]
649 pub fn reserve(&mut self, additional: usize) {
650 self.storage.reserve(additional);
651 }
652
653 /// Reserves capacity for exactly `additional` more bytes to be inserted
654 /// into the given `BytesMut`.
655 ///
656 /// Behaves like [`reserve`](Self::reserve), it reclaims the existing buffer
657 /// when possible and reallocates a unique buffer, but a new allocation is
658 /// sized to hold exactly `additional` more bytes instead of growing to at
659 /// least twice the current capacity. The allocation size is the new capacity
660 /// plus the buffer header, [`METADATA_SIZE`](crate::METADATA_SIZE) bytes.
661 /// The contents are not moved when the buffer already has enough remaining
662 /// capacity.
663 ///
664 /// The capacity is not rounded up to a page size, a buffer with a
665 /// [`page_size`](Self::page_size) loses it unless the new capacity is a page
666 /// capacity.
667 ///
668 /// # Panics
669 ///
670 /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
671 /// header size, just under 4 GiB.
672 ///
673 /// # Examples
674 ///
675 /// ```
676 /// use ntex_bytes::BytesMut;
677 ///
678 /// let mut buf = BytesMut::copy_from_slice(&[0; 1000][..]);
679 /// buf.reserve_exact(24);
680 /// assert_eq!(buf.capacity(), 1024);
681 ///
682 /// // enough remaining capacity keeps the current buffer
683 /// let ptr = buf.as_ptr();
684 /// buf.reserve_exact(24);
685 /// assert_eq!(buf.as_ptr(), ptr);
686 /// ```
687 #[inline]
688 pub fn reserve_exact(&mut self, additional: usize) {
689 self.storage.reserve_exact(additional);
690 }
691
692 /// Grows the buffer by one step if its remaining capacity is less than
693 /// the low threshold of its page size.
694 ///
695 /// Nothing happens when the remaining capacity is at least
696 /// [`BytePageSize::low`](crate::BytePageSize::low) of the buffer's
697 /// [`page_size`](Self::page_size), 1 KiB for a 16 KiB page and 4 KiB
698 /// for a buffer without a page size.
699 ///
700 /// If the allocation holds the data and
701 /// [`BytePageSize::half_capacity`](crate::BytePageSize::half_capacity)
702 /// more bytes, it is reused: a unique buffer moves its data to the start
703 /// of the allocation, a shared buffer with a page size moves to a page of
704 /// the same size. Otherwise a buffer with a page size moves to a page of
705 /// the next larger page size, the old page returns to the page cache. A
706 /// buffer without a page size, or with the largest page size, grows its
707 /// capacity by its current capacity, by at least 112 bytes (104 with the
708 /// `tracker` feature) and by at most 64 KiB, like [`reserve_exact`](Self::reserve_exact) does: a unique
709 /// buffer is reallocated, often in place, otherwise the data is copied
710 /// into a new buffer.
711 ///
712 /// # Panics
713 ///
714 /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
715 /// header size, just under 4 GiB.
716 ///
717 /// # Examples
718 ///
719 /// ```
720 /// use ntex_bytes::{BytePageSize, BytesMut};
721 ///
722 /// let mut buf = BytesMut::with_page_size(BytePageSize::Size4);
723 /// buf.extend_from_slice(b"hello");
724 ///
725 /// // the remaining capacity is above the low threshold, the buffer is kept
726 /// buf.reserve_more();
727 /// assert_eq!(buf.page_size(), BytePageSize::Size4);
728 ///
729 /// buf.extend_from_slice(&[0; 4000]);
730 /// buf.reserve_more();
731 /// assert_eq!(buf.page_size(), BytePageSize::Size8);
732 /// assert_eq!(buf.capacity(), BytePageSize::Size8.capacity());
733 /// assert_eq!(&buf[..5], b"hello");
734 ///
735 /// // consumed data makes room, the page is compacted in place
736 /// let mut buf = BytesMut::with_page_size(BytePageSize::Size4);
737 /// buf.extend_from_slice(&[0; 4000]);
738 /// buf.advance_to(3990);
739 /// buf.reserve_more();
740 /// assert_eq!(buf.page_size(), BytePageSize::Size4);
741 /// assert_eq!(buf.capacity(), BytePageSize::Size4.capacity());
742 ///
743 /// let mut buf = BytesMut::with_capacity(1000);
744 /// buf.reserve_more();
745 /// assert_eq!(buf.capacity(), 2000);
746 ///
747 /// let mut buf = BytesMut::with_capacity(1024 * 1024);
748 /// buf.extend_from_slice(&vec![0; 1024 * 1024]);
749 /// buf.reserve_more();
750 /// assert_eq!(buf.capacity(), 1024 * 1024 + 64 * 1024);
751 /// ```
752 #[inline]
753 pub fn reserve_more(&mut self) {
754 self.storage.reserve_more();
755 }
756
757 /// Appends a byte slice to the buffer.
758 ///
759 /// Additional capacity is reserved automatically when needed.
760 ///
761 /// # Examples
762 ///
763 /// ```
764 /// use ntex_bytes::BytesMut;
765 ///
766 /// let mut buf = BytesMut::with_capacity(0);
767 /// buf.extend_from_slice(b"aaabbb");
768 /// buf.extend_from_slice(b"cccddd");
769 ///
770 /// assert_eq!(b"aaabbbcccddd", &buf[..]);
771 /// ```
772 #[inline]
773 pub fn extend_from_slice(&mut self, extend: &[u8]) {
774 self.put_slice(extend);
775 }
776
777 /// Returns a writer that appends bytes to the spare capacity of the
778 /// buffer without initializing it first.
779 ///
780 /// Capacity for at least `additional` bytes is reserved like
781 /// [`reserve`](Self::reserve) does, the writer reserves more when it is
782 /// full. The buffer length is updated once, when the writer is dropped.
783 ///
784 /// # Panics
785 ///
786 /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
787 /// header size, just under 4 GiB.
788 ///
789 /// # Examples
790 ///
791 /// ```
792 /// use ntex_bytes::BytesMut;
793 ///
794 /// let mut buf = BytesMut::copy_from_slice(b"hello");
795 /// let mut w = buf.spare_writer(6);
796 /// w.push(b' ');
797 /// w.extend_from_slice(b"world");
798 /// assert_eq!(w.len(), 6);
799 /// drop(w);
800 ///
801 /// assert_eq!(&buf[..], b"hello world");
802 /// ```
803 #[inline]
804 pub fn spare_writer(&mut self, additional: usize) -> SpareWriter<'_> {
805 SpareWriter::new(self, additional)
806 }
807
808 /// Returns an iterator over the bytes contained by the buffer.
809 ///
810 /// # Examples
811 ///
812 /// ```
813 /// use ntex_bytes::{Buf, BytesMut};
814 ///
815 /// let buf = BytesMut::copy_from_slice(&b"abc"[..]);
816 /// let mut iter = buf.iter();
817 ///
818 /// assert_eq!(iter.next().map(|b| *b), Some(b'a'));
819 /// assert_eq!(iter.next().map(|b| *b), Some(b'b'));
820 /// assert_eq!(iter.next().map(|b| *b), Some(b'c'));
821 /// assert_eq!(iter.next(), None);
822 /// ```
823 #[inline]
824 pub fn iter(&'_ self) -> std::slice::Iter<'_, u8> {
825 self.chunk().iter()
826 }
827}
828
829impl_buf!(BytesMut {});
830
831impl_slice_traits!(BytesMut);
832
833impl_partial_eq!(BytesMut);
834
835impl BufMut for BytesMut {
836 #[inline]
837 fn remaining_mut(&self) -> usize {
838 self.storage.remaining()
839 }
840
841 #[inline]
842 unsafe fn advance_mut(&mut self, cnt: usize) {
843 // This call will panic if `cnt` is too big
844 self.storage.set_len(self.len() + cnt);
845 }
846
847 #[inline]
848 fn chunk_mut(&mut self) -> &mut UninitSlice {
849 self.storage.spare_mut()
850 }
851
852 #[inline]
853 fn put<T: Buf>(&mut self, mut src: T)
854 where
855 Self: Sized,
856 {
857 self.reserve(src.remaining());
858 while src.has_remaining() {
859 let chunk = src.chunk();
860 let len = chunk.len();
861 self.put_slice(chunk);
862 src.advance(len);
863 }
864 }
865
866 #[inline]
867 fn put_slice(&mut self, src: &[u8]) {
868 self.reserve(src.len());
869 self.storage.put_slice_partial(src);
870 }
871
872 #[inline]
873 fn put_u8(&mut self, n: u8) {
874 self.reserve(1);
875 self.storage.put_u8(n);
876 }
877
878 #[inline]
879 fn put_i8(&mut self, n: i8) {
880 self.put_u8(n as u8);
881 }
882}
883
884/// Interop with the `bytes` crate: like `bytes::BytesMut`, the buffer grows on
885/// demand, so `remaining_mut()` reports `usize::MAX - len` and `chunk_mut()`
886/// is never empty. The native [`BufMut`] impl reports spare capacity instead.
887// SAFETY: Chunks expose only allocated spare bytes, and advancement checks capacity before exposing
888// caller-initialized data.
889unsafe impl bytes::buf::BufMut for BytesMut {
890 #[inline]
891 fn remaining_mut(&self) -> usize {
892 usize::MAX - self.len()
893 }
894
895 #[inline]
896 unsafe fn advance_mut(&mut self, cnt: usize) {
897 let remaining = BufMut::remaining_mut(self);
898 assert!(
899 cnt <= remaining,
900 "cannot advance past `remaining_mut`: {cnt:?} <= {remaining:?}"
901 );
902 BufMut::advance_mut(self, cnt);
903 }
904
905 #[inline]
906 fn chunk_mut(&mut self) -> &mut bytes::buf::UninitSlice {
907 if BufMut::remaining_mut(self) == 0 {
908 self.reserve(64);
909 }
910 // SAFETY: The live buffer exclusively owns its spare capacity, which is exactly the
911 // returned range.
912 unsafe {
913 let ptr = self.storage.as_ptr();
914 bytes::buf::UninitSlice::from_raw_parts_mut(
915 ptr.add(self.len()),
916 BufMut::remaining_mut(self),
917 )
918 }
919 }
920
921 #[inline]
922 fn put<T: bytes::buf::Buf>(&mut self, mut src: T)
923 where
924 Self: Sized,
925 {
926 self.reserve(src.remaining());
927 while src.has_remaining() {
928 let chunk = src.chunk();
929 let len = chunk.len();
930 BufMut::put_slice(self, chunk);
931 src.advance(len);
932 }
933 }
934
935 #[inline]
936 fn put_slice(&mut self, src: &[u8]) {
937 BufMut::put_slice(self, src);
938 }
939
940 #[inline]
941 fn put_bytes(&mut self, val: u8, cnt: usize) {
942 self.reserve(cnt);
943 // SAFETY: `reserve(cnt)` provides writable space, and all `cnt` bytes are initialized
944 // before advancing.
945 unsafe {
946 ptr::write_bytes(self.storage.as_ptr().add(self.len()), val, cnt);
947 BufMut::advance_mut(self, cnt);
948 }
949 }
950
951 #[inline]
952 fn put_u8(&mut self, n: u8) {
953 BufMut::put_u8(self, n);
954 }
955
956 #[inline]
957 fn put_i8(&mut self, n: i8) {
958 BufMut::put_i8(self, n);
959 }
960}
961
962impl AsMut<[u8]> for BytesMut {
963 #[inline]
964 fn as_mut(&mut self) -> &mut [u8] {
965 self.storage.as_mut()
966 }
967}
968
969impl DerefMut for BytesMut {
970 #[inline]
971 fn deref_mut(&mut self) -> &mut [u8] {
972 self.storage.as_mut()
973 }
974}
975
976impl Eq for BytesMut {}
977
978impl PartialEq for BytesMut {
979 #[inline]
980 fn eq(&self, other: &BytesMut) -> bool {
981 self.storage.as_ref() == other.storage.as_ref()
982 }
983}
984
985impl borrow::BorrowMut<[u8]> for BytesMut {
986 #[inline]
987 fn borrow_mut(&mut self) -> &mut [u8] {
988 self.as_mut()
989 }
990}
991
992impl PartialEq<Bytes> for BytesMut {
993 fn eq(&self, other: &Bytes) -> bool {
994 other[..] == self[..]
995 }
996}
997
998impl PartialEq<BytesMut> for Bytes {
999 fn eq(&self, other: &BytesMut) -> bool {
1000 *other == *self
1001 }
1002}
1003
1004impl_read!(BytesMut);
1005
1006impl io::Write for BytesMut {
1007 fn write(&mut self, src: &[u8]) -> Result<usize, io::Error> {
1008 self.extend_from_slice(src);
1009 Ok(src.len())
1010 }
1011
1012 fn flush(&mut self) -> Result<(), io::Error> {
1013 Ok(())
1014 }
1015}
1016
1017impl fmt::Write for BytesMut {
1018 #[inline]
1019 fn write_str(&mut self, s: &str) -> fmt::Result {
1020 self.extend_from_slice(s.as_bytes());
1021 Ok(())
1022 }
1023}
1024
1025impl Clone for BytesMut {
1026 #[inline]
1027 fn clone(&self) -> BytesMut {
1028 BytesMut::from(&self[..])
1029 }
1030}
1031
1032impl FromIterator<u8> for BytesMut {
1033 fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
1034 let iter = into_iter.into_iter();
1035 let (min, maybe_max) = iter.size_hint();
1036
1037 let mut out = BytesMut::with_capacity(maybe_max.unwrap_or(min));
1038 out.extend(iter);
1039 out
1040 }
1041}
1042
1043impl<'a> FromIterator<&'a u8> for BytesMut {
1044 fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
1045 into_iter.into_iter().copied().collect::<BytesMut>()
1046 }
1047}
1048
1049impl Extend<u8> for BytesMut {
1050 fn extend<T>(&mut self, iter: T)
1051 where
1052 T: IntoIterator<Item = u8>,
1053 {
1054 let iter = iter.into_iter();
1055 self.reserve(iter.size_hint().0);
1056 for b in iter {
1057 self.put_u8(b);
1058 }
1059 }
1060}
1061
1062impl<'a> Extend<&'a u8> for BytesMut {
1063 fn extend<T>(&mut self, iter: T)
1064 where
1065 T: IntoIterator<Item = &'a u8>,
1066 {
1067 self.extend(iter.into_iter().copied());
1068 }
1069}
1070
1071impl From<BytesMut> for Bytes {
1072 #[inline]
1073 fn from(b: BytesMut) -> Self {
1074 b.freeze()
1075 }
1076}
1077
1078impl<'a> From<&'a [u8]> for BytesMut {
1079 #[inline]
1080 fn from(src: &'a [u8]) -> BytesMut {
1081 BytesMut::copy_from_slice(src)
1082 }
1083}
1084
1085impl<const N: usize> From<[u8; N]> for BytesMut {
1086 #[inline]
1087 fn from(src: [u8; N]) -> BytesMut {
1088 BytesMut::copy_from_slice(src)
1089 }
1090}
1091
1092impl<'a, const N: usize> From<&'a [u8; N]> for BytesMut {
1093 #[inline]
1094 fn from(src: &'a [u8; N]) -> BytesMut {
1095 BytesMut::copy_from_slice(src)
1096 }
1097}
1098
1099impl<'a> From<&'a str> for BytesMut {
1100 #[inline]
1101 fn from(src: &'a str) -> BytesMut {
1102 BytesMut::from(src.as_bytes())
1103 }
1104}
1105
1106impl From<Bytes> for BytesMut {
1107 #[inline]
1108 fn from(src: Bytes) -> BytesMut {
1109 match src.storage.try_into_vec() {
1110 Ok(storage) => BytesMut { storage },
1111 Err(storage) => BytesMut::copy_from_slice(storage.as_ref()),
1112 }
1113 }
1114}
1115
1116impl From<&Bytes> for BytesMut {
1117 #[inline]
1118 fn from(src: &Bytes) -> BytesMut {
1119 BytesMut::copy_from_slice(&src[..])
1120 }
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125 use super::*;
1126
1127 /// STATEMENT: Repeated small writes grow `BytesMut` amortized rather than reallocating for every write.
1128 ///
1129 /// HOW:
1130 /// - Append eight bytes 10,000 times and check length and at most 16 capacity changes.
1131 /// - Format 1,000 eight-digit numbers into another buffer and verify length and bounded capacity.
1132 #[test]
1133 fn growth_is_amortized() {
1134 let mut buf = BytesMut::with_capacity(0);
1135 let mut cap = buf.capacity();
1136 let mut reallocs = 0;
1137 for _ in 0..10_000 {
1138 buf.put_slice(b"abcdefgh");
1139 if buf.capacity() != cap {
1140 reallocs += 1;
1141 cap = buf.capacity();
1142 }
1143 }
1144 assert_eq!(buf.len(), 80_000);
1145 assert!(reallocs <= 16, "reallocs: {reallocs}");
1146
1147 // writes through `io::Write` and `fmt::Write` grow the same way
1148 let mut buf = BytesMut::with_capacity(0);
1149 for i in 0..1000 {
1150 std::fmt::Write::write_fmt(&mut buf, format_args!("{i:08}")).unwrap();
1151 }
1152 assert_eq!(buf.len(), 8000);
1153 assert!(buf.capacity() < 16_000);
1154 }
1155
1156 /// STATEMENT: Large reservations for small live data allocate only the requested additional capacity.
1157 ///
1158 /// HOW:
1159 /// - Reserve 64 KiB after `hello` and check capacity equals live length plus the request.
1160 /// - Split 1,000 bytes from a shared 1,024-byte buffer, reserve 4,096 for the tail, and check capacity and head data.
1161 #[test]
1162 fn growth_of_little_data_is_exact() {
1163 let mut buf = BytesMut::copy_from_slice(b"hello");
1164 buf.reserve(64 * 1024);
1165 assert_eq!(buf.capacity(), 5 + 64 * 1024);
1166
1167 // a buffer shared with split off `Bytes`
1168 let mut buf = BytesMut::with_capacity(1024);
1169 buf.extend_from_slice(&[1; 1024]);
1170 let head = buf.split_to(1000);
1171 buf.reserve(4096);
1172 assert_eq!(buf.capacity(), 24 + 4096);
1173 assert_eq!(&head[..], &[1; 1000][..]);
1174 }
1175
1176 /// STATEMENT: Converting uniquely owned vector-backed `Bytes` to `BytesMut` reuses spare capacity.
1177 ///
1178 /// HOW:
1179 /// - Freeze 64 bytes in a 256-byte buffer, convert back, and check pointer, contents, and capacity.
1180 /// - Fill the spare capacity and verify the pointer and appended bytes.
1181 #[test]
1182 fn from_unique_bytes_reuses_buffer() {
1183 let mut buf = BytesMut::with_capacity(256);
1184 buf.extend_from_slice(&[1; 64]);
1185 let b = buf.freeze();
1186 let ptr = b.as_ptr();
1187
1188 let mut m = BytesMut::from(b);
1189 assert_eq!(m.as_ptr(), ptr);
1190 assert_eq!(&m[..], &[1; 64][..]);
1191 assert_eq!(m.capacity(), 256);
1192
1193 // spare capacity past the view is writable
1194 m.extend_from_slice(&[2; 192]);
1195 assert_eq!(m.as_ptr(), ptr);
1196 assert_eq!(&m[64..], &[2; 192][..]);
1197 }
1198
1199 /// STATEMENT: A unique `Bytes` subview regains writable capacity after its visible end when made mutable.
1200 ///
1201 /// HOW:
1202 /// - Drop a split 32-byte head, truncate the tail, convert to `BytesMut`, and check pointer and tail capacity.
1203 /// - Append 160 bytes and verify old and new content without relocation.
1204 #[test]
1205 fn from_unique_bytes_subview() {
1206 let mut buf = BytesMut::with_capacity(256);
1207 buf.extend_from_slice(&[1; 128]);
1208 let mut b = buf.freeze();
1209 let head = b.split_to(32);
1210 drop(head);
1211 b.truncate(64);
1212 let ptr = b.as_ptr();
1213
1214 let mut m = BytesMut::from(b);
1215 assert_eq!(m.as_ptr(), ptr);
1216 assert_eq!(m.len(), 64);
1217 assert_eq!(m.capacity(), 256 - 32);
1218
1219 // the dropped tail of the view is spare capacity again
1220 m.extend_from_slice(&[3; 160]);
1221 assert_eq!(m.as_ptr(), ptr);
1222 assert_eq!(&m[..64], &[1; 64][..]);
1223 assert_eq!(&m[64..], &[3; 160][..]);
1224 }
1225
1226 /// STATEMENT: Converting shared `Bytes` to `BytesMut` copies rather than exposing shared mutable storage.
1227 ///
1228 /// HOW:
1229 /// - Keep a clone, convert its sibling, mutate it, and check distinct pointers and unchanged clone data.
1230 /// - Convert bytes taken from a live `BytesMut` and verify later writes to the original do not alter the copy.
1231 #[test]
1232 fn from_shared_bytes_copies() {
1233 let b = BytesMut::copy_from_slice([1; 64]).freeze();
1234 let b2 = b.clone();
1235
1236 let mut m = BytesMut::from(b);
1237 assert_ne!(m.as_ptr(), b2.as_ptr());
1238 m[0] = 2;
1239 assert_eq!(&b2[..], &[1; 64][..]);
1240
1241 // the buffer is still referenced by a `BytesMut`
1242 let mut buf = BytesMut::with_capacity(256);
1243 buf.extend_from_slice(&[1; 64]);
1244 let b = buf.take();
1245 let m = BytesMut::from(b);
1246 assert_ne!(m.as_ptr(), buf.as_ptr());
1247 buf.extend_from_slice(&[2; 64]);
1248 assert_eq!(&m[..], &[1; 64][..]);
1249 }
1250
1251 // Run under miri: without `Acquire`, the header update races with the
1252 // read made by the other thread before it released its handle.
1253 /// STATEMENT: Reclaiming unique `Bytes` storage synchronizes with a different thread releasing its view.
1254 ///
1255 /// HOW:
1256 /// - Read a cloned view on another thread while retrying `try_into_vec` until unique ownership is available.
1257 /// - Check pointer reuse, mutate the reclaimed buffer, and verify the joined thread read the original byte.
1258 #[test]
1259 fn from_bytes_synchronizes_with_release() {
1260 let b = BytesMut::copy_from_slice([1; 64]).freeze();
1261 let other = b.clone();
1262 let handle = std::thread::spawn(move || {
1263 let val = other[0];
1264 drop(other);
1265 val
1266 });
1267
1268 let ptr = b.as_ptr();
1269 let mut storage = b.storage;
1270 let mut m = loop {
1271 match storage.try_into_vec() {
1272 Ok(storage) => break BytesMut { storage },
1273 Err(st) => {
1274 storage = st;
1275 std::thread::yield_now();
1276 }
1277 }
1278 };
1279 assert_eq!(m.as_ptr(), ptr);
1280 m[0] = 2;
1281 assert_eq!(handle.join().unwrap(), 1);
1282 }
1283
1284 /// STATEMENT: Inline and static `Bytes` convert to mutable buffers with unchanged contents.
1285 ///
1286 /// HOW:
1287 /// - Convert inline `inline` bytes and a static 64-byte array with `BytesMut::from` and compare their contents.
1288 #[test]
1289 fn from_inline_and_static_bytes() {
1290 let m = BytesMut::from(Bytes::copy_from_slice(b"inline"));
1291 assert_eq!(&m[..], b"inline");
1292
1293 let m = BytesMut::from(Bytes::from_static(&[1; 64]));
1294 assert_eq!(&m[..], &[1; 64][..]);
1295 }
1296
1297 /// STATEMENT: Reading `BytesMut` consumes its contents without touching unused destination bytes.
1298 ///
1299 /// HOW:
1300 /// - Read `123` into a ten-byte zeroed array and verify a three-byte read, an empty buffer, and seven untouched zeros.
1301 #[test]
1302 fn bvec_read() {
1303 use std::io::Read;
1304
1305 let mut b = BytesMut::copy_from_slice(b"123");
1306
1307 let mut buf = [0; 10];
1308 assert_eq!(b.read(&mut buf).unwrap(), 3);
1309 assert_eq!(b.len(), 0);
1310 assert_eq!(buf, [49, 50, 51, 0, 0, 0, 0, 0, 0, 0]);
1311 }
1312
1313 /// STATEMENT: Converting borrowed `Bytes` yields independently extensible mutable contents.
1314 ///
1315 /// HOW:
1316 /// - Convert borrowed static `hello`, append `!`, and verify `hello!` while the source remains `hello`.
1317 #[test]
1318 fn from_bytes_ref() {
1319 let b = Bytes::from_static(b"hello");
1320 let mut m = BytesMut::from(&b);
1321 m.extend_from_slice(b"!");
1322 assert_eq!(m, "hello!");
1323 assert_eq!(b, "hello");
1324 }
1325}