bytes/bytes_mut.rs
1use core::mem::{self, ManuallyDrop, MaybeUninit};
2use core::ops::{Deref, DerefMut};
3use core::ptr::{self, NonNull};
4use core::{cmp, fmt, hash, slice};
5
6use alloc::{
7 borrow::{Borrow, BorrowMut},
8 boxed::Box,
9 string::String,
10 vec,
11 vec::Vec,
12};
13
14use crate::buf::{IntoIter, UninitSlice};
15use crate::bytes::Vtable;
16#[allow(unused)]
17use crate::loom::sync::atomic::AtomicMut;
18use crate::loom::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
19use crate::{Buf, BufMut, Bytes, TryGetError};
20
21/// A unique reference to a contiguous slice of memory.
22///
23/// `BytesMut` represents a unique view into a potentially shared memory region.
24/// Given the uniqueness guarantee, owners of `BytesMut` handles are able to
25/// mutate the memory.
26///
27/// `BytesMut` can be thought of as containing a `buf: Arc<Vec<u8>>`, an offset
28/// into `buf`, a slice length, and a guarantee that no other `BytesMut` for the
29/// same `buf` overlaps with its slice. That guarantee means that a write lock
30/// is not required.
31///
32/// # Growth
33///
34/// `BytesMut`'s `BufMut` implementation will implicitly grow its buffer as
35/// necessary. However, explicitly reserving the required space up-front before
36/// a series of inserts will be more efficient.
37///
38/// # Examples
39///
40/// ```
41/// use bytes::{BytesMut, BufMut};
42///
43/// let mut buf = BytesMut::with_capacity(64);
44///
45/// buf.put_u8(b'h');
46/// buf.put_u8(b'e');
47/// buf.put(&b"llo"[..]);
48///
49/// assert_eq!(&buf[..], b"hello");
50///
51/// // Freeze the buffer so that it can be shared
52/// let a = buf.freeze();
53///
54/// // This does not allocate, instead `b` points to the same memory.
55/// let b = a.clone();
56///
57/// assert_eq!(&a[..], b"hello");
58/// assert_eq!(&b[..], b"hello");
59/// ```
60pub struct BytesMut {
61 ptr: NonNull<u8>,
62 len: usize,
63 cap: usize,
64 data: *mut Shared,
65}
66
67// Thread-safe reference-counted container for the shared storage. This mostly
68// the same as `core::sync::Arc` but without the weak counter. The ref counting
69// fns are based on the ones found in `std`.
70//
71// The main reason to use `Shared` instead of `core::sync::Arc` is that it ends
72// up making the overall code simpler and easier to reason about. This is due to
73// some of the logic around setting `Inner::arc` and other ways the `arc` field
74// is used. Using `Arc` ended up requiring a number of funky transmutes and
75// other shenanigans to make it work.
76struct Shared {
77 vec: Vec<u8>,
78 original_capacity_repr: usize,
79 ref_count: AtomicUsize,
80}
81
82impl Shared {
83 fn init_to_raw(b: Box<MaybeUninit<Self>>, v: Self) -> *mut Self {
84 let shared = Box::into_raw(b).cast::<Self>();
85 // SAFETY: The Box has the right layout.
86 unsafe { shared.write(v) };
87 shared
88 }
89}
90
91// Assert that the alignment of `Shared` is divisible by 2.
92// This is a necessary invariant since we depend on allocating `Shared` a
93// shared object to implicitly carry the `KIND_ARC` flag in its pointer.
94// This flag is set when the LSB is 0.
95const _: [(); 0 - mem::align_of::<Shared>() % 2] = []; // Assert that the alignment of `Shared` is divisible by 2.
96
97// Buffer storage strategy flags.
98const KIND_ARC: usize = 0b0;
99const KIND_VEC: usize = 0b1;
100const KIND_MASK: usize = 0b1;
101
102// The max original capacity value. Any `Bytes` allocated with a greater initial
103// capacity will default to this.
104const MAX_ORIGINAL_CAPACITY_WIDTH: usize = 17;
105// The original capacity algorithm will not take effect unless the originally
106// allocated capacity was at least 1kb in size.
107const MIN_ORIGINAL_CAPACITY_WIDTH: usize = 10;
108// The original capacity is stored in powers of 2 starting at 1kb to a max of
109// 64kb. Representing it as such requires only 3 bits of storage.
110const ORIGINAL_CAPACITY_MASK: usize = 0b11100;
111const ORIGINAL_CAPACITY_OFFSET: usize = 2;
112
113const VEC_POS_OFFSET: usize = 5;
114// When the storage is in the `Vec` representation, the pointer can be advanced
115// at most this value. This is due to the amount of storage available to track
116// the offset is usize - number of KIND bits and number of ORIGINAL_CAPACITY
117// bits.
118const MAX_VEC_POS: usize = usize::MAX >> VEC_POS_OFFSET;
119const NOT_VEC_POS_MASK: usize = 0b11111;
120
121#[cfg(target_pointer_width = "64")]
122const PTR_WIDTH: usize = 64;
123#[cfg(target_pointer_width = "32")]
124const PTR_WIDTH: usize = 32;
125
126/*
127 *
128 * ===== BytesMut =====
129 *
130 */
131
132impl BytesMut {
133 /// Creates a new `BytesMut` with the specified capacity.
134 ///
135 /// The returned `BytesMut` will be able to hold at least `capacity` bytes
136 /// without reallocating.
137 ///
138 /// It is important to note that this function does not specify the length
139 /// of the returned `BytesMut`, but only the capacity.
140 ///
141 /// # Examples
142 ///
143 /// ```
144 /// use bytes::{BytesMut, BufMut};
145 ///
146 /// let mut bytes = BytesMut::with_capacity(64);
147 ///
148 /// // `bytes` contains no data, even though there is capacity
149 /// assert_eq!(bytes.len(), 0);
150 ///
151 /// bytes.put(&b"hello world"[..]);
152 ///
153 /// assert_eq!(&bytes[..], b"hello world");
154 /// ```
155 #[inline]
156 pub fn with_capacity(capacity: usize) -> BytesMut {
157 BytesMut::from_vec(Vec::with_capacity(capacity))
158 }
159
160 /// Creates a new `BytesMut` with default capacity.
161 ///
162 /// Resulting object has length 0 and unspecified capacity.
163 /// This function does not allocate.
164 ///
165 /// # Examples
166 ///
167 /// ```
168 /// use bytes::{BytesMut, BufMut};
169 ///
170 /// let mut bytes = BytesMut::new();
171 ///
172 /// assert_eq!(0, bytes.len());
173 ///
174 /// bytes.reserve(2);
175 /// bytes.put_slice(b"xy");
176 ///
177 /// assert_eq!(&b"xy"[..], &bytes[..]);
178 /// ```
179 #[inline]
180 pub fn new() -> BytesMut {
181 BytesMut::with_capacity(0)
182 }
183
184 /// Returns the number of bytes contained in this `BytesMut`.
185 ///
186 /// # Examples
187 ///
188 /// ```
189 /// use bytes::BytesMut;
190 ///
191 /// let b = BytesMut::from(&b"hello"[..]);
192 /// assert_eq!(b.len(), 5);
193 /// ```
194 #[inline]
195 pub fn len(&self) -> usize {
196 self.len
197 }
198
199 /// Returns true if the `BytesMut` has a length of 0.
200 ///
201 /// # Examples
202 ///
203 /// ```
204 /// use bytes::BytesMut;
205 ///
206 /// let b = BytesMut::with_capacity(64);
207 /// assert!(b.is_empty());
208 /// ```
209 #[inline]
210 pub fn is_empty(&self) -> bool {
211 self.len == 0
212 }
213
214 /// Returns the number of bytes the `BytesMut` can hold without reallocating.
215 ///
216 /// # Examples
217 ///
218 /// ```
219 /// use bytes::BytesMut;
220 ///
221 /// let b = BytesMut::with_capacity(64);
222 /// assert_eq!(b.capacity(), 64);
223 /// ```
224 #[inline]
225 pub fn capacity(&self) -> usize {
226 self.cap
227 }
228
229 /// Converts `self` into an immutable `Bytes`.
230 ///
231 /// The conversion is zero cost and is used to indicate that the slice
232 /// referenced by the handle will no longer be mutated. Once the conversion
233 /// is done, the handle can be cloned and shared across threads.
234 ///
235 /// # Examples
236 ///
237 /// ```ignore-wasm
238 /// use bytes::{BytesMut, BufMut};
239 /// use std::thread;
240 ///
241 /// let mut b = BytesMut::with_capacity(64);
242 /// b.put(&b"hello world"[..]);
243 /// let b1 = b.freeze();
244 /// let b2 = b1.clone();
245 ///
246 /// let th = thread::spawn(move || {
247 /// assert_eq!(&b1[..], b"hello world");
248 /// });
249 ///
250 /// assert_eq!(&b2[..], b"hello world");
251 /// th.join().unwrap();
252 /// ```
253 #[inline]
254 pub fn freeze(self) -> Bytes {
255 let bytes = ManuallyDrop::new(self);
256 if bytes.kind() == KIND_VEC {
257 // Just re-use `Bytes` internal Vec vtable
258 unsafe {
259 let off = bytes.get_vec_pos();
260 let vec = rebuild_vec(bytes.ptr.as_ptr(), bytes.len, bytes.cap, off);
261 let mut b: Bytes = vec.into();
262 b.advance(off);
263 b
264 }
265 } else {
266 debug_assert_eq!(bytes.kind(), KIND_ARC);
267
268 let ptr = bytes.ptr.as_ptr();
269 let len = bytes.len;
270 let data = AtomicPtr::new(bytes.data.cast());
271 unsafe { Bytes::with_vtable(ptr, len, data, &SHARED_VTABLE) }
272 }
273 }
274
275 /// Creates a new `BytesMut` containing `len` zeros.
276 ///
277 /// The resulting object has a length of `len` and a capacity greater
278 /// than or equal to `len`. The entire length of the object will be filled
279 /// with zeros.
280 ///
281 /// On some platforms or allocators this function may be faster than
282 /// a manual implementation.
283 ///
284 /// # Examples
285 ///
286 /// ```
287 /// use bytes::BytesMut;
288 ///
289 /// let zeros = BytesMut::zeroed(42);
290 ///
291 /// assert!(zeros.capacity() >= 42);
292 /// assert_eq!(zeros.len(), 42);
293 /// zeros.into_iter().for_each(|x| assert_eq!(x, 0));
294 /// ```
295 pub fn zeroed(len: usize) -> BytesMut {
296 BytesMut::from_vec(vec![0; len])
297 }
298
299 /// Splits the bytes into two at the given index.
300 ///
301 /// Afterwards `self` contains elements `[0, at)`, and the returned
302 /// `BytesMut` contains elements `[at, capacity)`. It's guaranteed that the
303 /// memory does not move, that is, the address of `self` does not change,
304 /// and the address of the returned slice is `at` bytes after that.
305 ///
306 /// This is an `O(1)` operation that just increases the reference count
307 /// and sets a few indices.
308 ///
309 /// # Examples
310 ///
311 /// ```
312 /// use bytes::BytesMut;
313 ///
314 /// let mut a = BytesMut::from(&b"hello world"[..]);
315 /// let mut b = a.split_off(5);
316 ///
317 /// a[0] = b'j';
318 /// b[0] = b'!';
319 ///
320 /// assert_eq!(&a[..], b"jello");
321 /// assert_eq!(&b[..], b"!world");
322 /// ```
323 ///
324 /// # Panics
325 ///
326 /// Panics if `at > capacity`.
327 #[must_use = "consider BytesMut::truncate if you don't need the other half"]
328 pub fn split_off(&mut self, at: usize) -> BytesMut {
329 assert!(
330 at <= self.capacity(),
331 "split_off out of bounds: {:?} <= {:?}",
332 at,
333 self.capacity(),
334 );
335 unsafe {
336 // SAFETY: `shallow_clone` increments the reference count (or
337 // promotes to shared) and returns a bitwise copy of the handle.
338 // The caller immediately adjusts both handles so they represent
339 // disjoint regions.
340 let mut other = self.shallow_clone();
341 // SAFETY: We've checked that `at` <= `self.capacity()` above.
342 other.advance_unchecked(at);
343 self.cap = at;
344 self.len = cmp::min(self.len, at);
345 other
346 }
347 }
348
349 /// Removes the bytes from the current view, returning them in a new
350 /// `BytesMut` handle.
351 ///
352 /// Afterwards, `self` will be empty, but will retain any additional
353 /// capacity that it had before the operation. This is identical to
354 /// `self.split_to(self.len())`.
355 ///
356 /// This is an `O(1)` operation that just increases the reference count and
357 /// sets a few indices.
358 ///
359 /// # Examples
360 ///
361 /// ```
362 /// use bytes::{BytesMut, BufMut};
363 ///
364 /// let mut buf = BytesMut::with_capacity(1024);
365 /// buf.put(&b"hello world"[..]);
366 ///
367 /// let other = buf.split();
368 ///
369 /// assert!(buf.is_empty());
370 /// assert_eq!(1013, buf.capacity());
371 ///
372 /// assert_eq!(other, b"hello world"[..]);
373 /// ```
374 #[must_use = "consider BytesMut::clear if you don't need the other half"]
375 pub fn split(&mut self) -> BytesMut {
376 let len = self.len();
377 self.split_to(len)
378 }
379
380 /// Splits the buffer into two at the given index.
381 ///
382 /// Afterwards `self` contains elements `[at, len)`, and the returned `BytesMut`
383 /// contains elements `[0, at)`.
384 ///
385 /// This is an `O(1)` operation that just increases the reference count and
386 /// sets a few indices.
387 ///
388 /// # Examples
389 ///
390 /// ```
391 /// use bytes::BytesMut;
392 ///
393 /// let mut a = BytesMut::from(&b"hello world"[..]);
394 /// let mut b = a.split_to(5);
395 ///
396 /// a[0] = b'!';
397 /// b[0] = b'j';
398 ///
399 /// assert_eq!(&a[..], b"!world");
400 /// assert_eq!(&b[..], b"jello");
401 /// ```
402 ///
403 /// # Panics
404 ///
405 /// Panics if `at > len`.
406 #[must_use = "consider BytesMut::advance if you don't need the other half"]
407 pub fn split_to(&mut self, at: usize) -> BytesMut {
408 assert!(
409 at <= self.len(),
410 "split_to out of bounds: {:?} <= {:?}",
411 at,
412 self.len(),
413 );
414
415 unsafe {
416 // SAFETY: `shallow_clone` increments the reference count (or
417 // promotes to shared) and returns a bitwise copy of the handle.
418 // The caller immediately adjusts both handles so they represent
419 // disjoint regions.
420 let mut other = self.shallow_clone();
421 // SAFETY: We've checked that `at` <= `self.len()` and we know that `self.len()` <=
422 // `self.capacity()`.
423 self.advance_unchecked(at);
424 other.cap = at;
425 other.len = at;
426 other
427 }
428 }
429
430 /// Shortens the buffer, keeping the first `len` bytes and dropping the
431 /// rest.
432 ///
433 /// If `len` is greater than the buffer's current length, this has no
434 /// effect.
435 ///
436 /// Existing underlying capacity is preserved.
437 ///
438 /// The [split_off](`Self::split_off()`) method can emulate `truncate`, but this causes the
439 /// excess bytes to be returned instead of dropped.
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// use bytes::BytesMut;
445 ///
446 /// let mut buf = BytesMut::from(&b"hello world"[..]);
447 /// buf.truncate(5);
448 /// assert_eq!(buf, b"hello"[..]);
449 /// ```
450 pub fn truncate(&mut self, len: usize) {
451 if len <= self.len() {
452 // SAFETY: Shrinking the buffer cannot expose uninitialized bytes.
453 unsafe { self.set_len(len) };
454 }
455 }
456
457 /// Clears the buffer, removing all data. Existing capacity is preserved.
458 ///
459 /// # Examples
460 ///
461 /// ```
462 /// use bytes::BytesMut;
463 ///
464 /// let mut buf = BytesMut::from(&b"hello world"[..]);
465 /// buf.clear();
466 /// assert!(buf.is_empty());
467 /// ```
468 pub fn clear(&mut self) {
469 // SAFETY: Setting the length to zero cannot expose uninitialized bytes.
470 unsafe { self.set_len(0) };
471 }
472
473 /// Resizes the buffer so that `len` is equal to `new_len`.
474 ///
475 /// If `new_len` is greater than `len`, the buffer is extended by the
476 /// difference with each additional byte set to `value`. If `new_len` is
477 /// less than `len`, the buffer is simply truncated.
478 ///
479 /// # Examples
480 ///
481 /// ```
482 /// use bytes::BytesMut;
483 ///
484 /// let mut buf = BytesMut::new();
485 ///
486 /// buf.resize(3, 0x1);
487 /// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);
488 ///
489 /// buf.resize(2, 0x2);
490 /// assert_eq!(&buf[..], &[0x1, 0x1]);
491 ///
492 /// buf.resize(4, 0x3);
493 /// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
494 /// ```
495 pub fn resize(&mut self, new_len: usize, value: u8) {
496 let additional = if let Some(additional) = new_len.checked_sub(self.len()) {
497 additional
498 } else {
499 self.truncate(new_len);
500 return;
501 };
502
503 if additional == 0 {
504 return;
505 }
506
507 self.reserve(additional);
508 let dst = self.spare_capacity_mut().as_mut_ptr();
509 // SAFETY: `spare_capacity_mut` returns a valid, properly aligned pointer and we've
510 // reserved enough space to write `additional` bytes.
511 unsafe { ptr::write_bytes(dst, value, additional) };
512
513 // SAFETY: There are at least `new_len` initialized bytes in the buffer so no
514 // uninitialized bytes are being exposed.
515 unsafe { self.set_len(new_len) };
516 }
517
518 /// Sets the length of the buffer.
519 ///
520 /// This will explicitly set the size of the buffer without actually
521 /// modifying the data, so it is up to the caller to ensure that the data
522 /// has been initialized.
523 ///
524 /// # Examples
525 ///
526 /// ```
527 /// use bytes::BytesMut;
528 ///
529 /// let mut b = BytesMut::from(&b"hello world"[..]);
530 ///
531 /// unsafe {
532 /// b.set_len(5);
533 /// }
534 ///
535 /// assert_eq!(&b[..], b"hello");
536 ///
537 /// unsafe {
538 /// b.set_len(11);
539 /// }
540 ///
541 /// assert_eq!(&b[..], b"hello world");
542 /// ```
543 #[inline]
544 pub unsafe fn set_len(&mut self, len: usize) {
545 debug_assert!(len <= self.cap, "set_len out of bounds");
546 self.len = len;
547 }
548
549 /// Reserves capacity for at least `additional` more bytes to be inserted
550 /// into the given `BytesMut`.
551 ///
552 /// More than `additional` bytes may be reserved in order to avoid frequent
553 /// reallocations. A call to `reserve` may result in an allocation.
554 ///
555 /// Before allocating new buffer space, the function will attempt to reclaim
556 /// space in the existing buffer. If the current handle references a view
557 /// into a larger original buffer, and all other handles referencing part
558 /// of the same original buffer have been dropped, then the current view
559 /// can be copied/shifted to the front of the buffer and the handle can take
560 /// ownership of the full buffer, provided that the full buffer is large
561 /// enough to fit the requested additional capacity.
562 ///
563 /// This optimization will only happen if shifting the data from the current
564 /// view to the front of the buffer is not too expensive in terms of the
565 /// (amortized) time required. The precise condition is subject to change;
566 /// as of now, the length of the data being shifted needs to be at least as
567 /// large as the distance that it's shifted by. If the current view is empty
568 /// and the original buffer is large enough to fit the requested additional
569 /// capacity, then reallocations will never happen.
570 ///
571 /// This method does not preserve data stored in the unused capacity.
572 ///
573 /// # Examples
574 ///
575 /// In the following example, a new buffer is allocated.
576 ///
577 /// ```
578 /// use bytes::BytesMut;
579 ///
580 /// let mut buf = BytesMut::from(&b"hello"[..]);
581 /// buf.reserve(64);
582 /// assert!(buf.capacity() >= 69);
583 /// ```
584 ///
585 /// In the following example, the existing buffer is reclaimed.
586 ///
587 /// ```
588 /// use bytes::{BytesMut, BufMut};
589 ///
590 /// let mut buf = BytesMut::with_capacity(128);
591 /// buf.put(&[0; 64][..]);
592 ///
593 /// let ptr = buf.as_ptr();
594 /// let other = buf.split();
595 ///
596 /// assert!(buf.is_empty());
597 /// assert_eq!(buf.capacity(), 64);
598 ///
599 /// drop(other);
600 /// buf.reserve(128);
601 ///
602 /// assert_eq!(buf.capacity(), 128);
603 /// assert_eq!(buf.as_ptr(), ptr);
604 /// ```
605 ///
606 /// # Panics
607 ///
608 /// Panics if the new capacity overflows `usize`.
609 #[inline]
610 pub fn reserve(&mut self, additional: usize) {
611 let len = self.len();
612 let rem = self.capacity() - len;
613
614 if additional <= rem {
615 // The handle can already store at least `additional` more bytes, so
616 // there is no further work needed to be done.
617 return;
618 }
619
620 // will always succeed
621 let _ = self.reserve_inner(additional, true);
622 }
623
624 // In separate function to allow the short-circuits in `reserve` and `try_reclaim` to
625 // be inline-able. Significantly helps performance. Returns false if it did not succeed.
626 fn reserve_inner(&mut self, additional: usize, allocate: bool) -> bool {
627 let len = self.len();
628 let kind = self.kind();
629
630 if kind == KIND_VEC {
631 // If there's enough free space before the start of the buffer, then
632 // just copy the data backwards and reuse the already-allocated
633 // space.
634 //
635 // Otherwise, since backed by a vector, use `Vec::reserve`
636 //
637 // We need to make sure that this optimization does not kill the
638 // amortized runtimes of BytesMut's operations.
639 unsafe {
640 let off = self.get_vec_pos();
641
642 // Only reuse space if we can satisfy the requested additional space.
643 //
644 // Also check if the value of `off` suggests that enough bytes
645 // have been read to account for the overhead of shifting all
646 // the data (in an amortized analysis).
647 // Hence the condition `off >= self.len()`.
648 //
649 // This condition also already implies that the buffer is going
650 // to be (at least) half-empty in the end; so we do not break
651 // the (amortized) runtime with future resizes of the underlying
652 // `Vec`.
653 //
654 // [For more details check issue #524, and PR #525.]
655 if self.capacity() - self.len() + off >= additional && off >= self.len() {
656 // There's enough space, and it's not too much overhead:
657 // reuse the space!
658 //
659 // Just move the pointer back to the start after copying
660 // data back.
661 let base_ptr = self.ptr.as_ptr().sub(off);
662 // Since `off >= self.len()`, the two regions don't overlap.
663 ptr::copy_nonoverlapping(self.ptr.as_ptr(), base_ptr, self.len);
664 self.ptr = vptr(base_ptr);
665 self.set_vec_pos(0);
666
667 // Length stays constant, but since we moved backwards we
668 // can gain capacity back.
669 self.cap += off;
670 } else {
671 if !allocate {
672 return false;
673 }
674 // Not enough space, or reusing might be too much overhead:
675 // allocate more space!
676 let mut v =
677 ManuallyDrop::new(rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off));
678 v.reserve(additional);
679
680 // Update the info
681 self.ptr = vptr(v.as_mut_ptr().add(off));
682 self.cap = v.capacity() - off;
683 debug_assert_eq!(self.len, v.len() - off);
684 }
685
686 return true;
687 }
688 }
689
690 debug_assert_eq!(kind, KIND_ARC);
691 let shared: *mut Shared = self.data;
692
693 // Reserving involves abandoning the currently shared buffer and
694 // allocating a new vector with the requested capacity.
695 //
696 // Compute the new capacity
697 let mut new_cap = match len.checked_add(additional) {
698 Some(new_cap) => new_cap,
699 None if !allocate => return false,
700 None => panic!("overflow"),
701 };
702
703 unsafe {
704 // First, try to reclaim the buffer. This is possible if the current
705 // handle is the only outstanding handle pointing to the buffer.
706 if (*shared).is_unique() {
707 // This is the only handle to the buffer. It can be reclaimed.
708 // However, before doing the work of copying data, check to make
709 // sure that the vector has enough capacity.
710 let v = &mut (*shared).vec;
711
712 let v_capacity = v.capacity();
713 let ptr = v.as_mut_ptr();
714
715 let offset = self.ptr.as_ptr().offset_from(ptr) as usize;
716
717 let new_cap_plus_offset = match new_cap.checked_add(offset) {
718 Some(new_cap_plus_offset) => new_cap_plus_offset,
719 None if !allocate => return false,
720 None => panic!("overflow"),
721 };
722
723 // Compare the condition in the `kind == KIND_VEC` case above
724 // for more details.
725 if v_capacity >= new_cap_plus_offset {
726 self.cap = new_cap;
727 // no copy is necessary
728 } else if v_capacity >= new_cap && offset >= len {
729 // The capacity is sufficient, and copying is not too much
730 // overhead: reclaim the buffer!
731
732 // `offset >= len` means: no overlap
733 ptr::copy_nonoverlapping(self.ptr.as_ptr(), ptr, len);
734
735 self.ptr = vptr(ptr);
736 self.cap = v.capacity();
737 } else {
738 if !allocate {
739 return false;
740 }
741
742 // new_cap is calculated in terms of `BytesMut`, not the underlying
743 // `Vec`, so it does not take the offset into account.
744 //
745 // Thus we have to manually add it here.
746 new_cap = new_cap_plus_offset;
747
748 // The vector capacity is not sufficient. The reserve request is
749 // asking for more than the initial buffer capacity. Allocate more
750 // than requested if `new_cap` is not much bigger than the current
751 // capacity.
752 //
753 // There are some situations, using `reserve_exact` that the
754 // buffer capacity could be below `original_capacity`, so do a
755 // check.
756 let double = v.capacity().checked_shl(1).unwrap_or(new_cap);
757
758 new_cap = cmp::max(double, new_cap);
759
760 // No space - allocate more
761 //
762 // The length field of `Shared::vec` is not used by the `BytesMut`;
763 // instead we use the `len` field in the `BytesMut` itself. However,
764 // when calling `reserve`, it doesn't guarantee that data stored in
765 // the unused capacity of the vector is copied over to the new
766 // allocation, so we need to ensure that we don't have any data we
767 // care about in the unused capacity before calling `reserve`.
768 debug_assert!(offset + len <= v.capacity());
769 v.set_len(offset + len);
770 v.reserve(new_cap - v.len());
771
772 // Update the info
773 self.ptr = vptr(v.as_mut_ptr().add(offset));
774 self.cap = v.capacity() - offset;
775 }
776
777 return true;
778 }
779 }
780 if !allocate {
781 return false;
782 }
783
784 let original_capacity_repr = unsafe { (*shared).original_capacity_repr };
785 let original_capacity = original_capacity_from_repr(original_capacity_repr);
786
787 new_cap = cmp::max(new_cap, original_capacity);
788
789 // Create a new vector to store the data
790 let mut v = ManuallyDrop::new(Vec::with_capacity(new_cap));
791
792 // Copy the bytes
793 v.extend_from_slice(self.as_ref());
794
795 // Release the shared handle. This must be done *after* the bytes are
796 // copied.
797 unsafe { release_shared(shared) };
798
799 // Update self
800 let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;
801 self.data = invalid_ptr(data);
802 self.ptr = vptr(v.as_mut_ptr());
803 self.cap = v.capacity();
804 debug_assert_eq!(self.len, v.len());
805 true
806 }
807
808 /// Attempts to cheaply reclaim already allocated capacity for at least `additional` more
809 /// bytes to be inserted into the given `BytesMut` and returns `true` if it succeeded.
810 ///
811 /// `try_reclaim` behaves exactly like `reserve`, except that it never allocates new storage
812 /// and returns a `bool` indicating whether it was successful in doing so:
813 ///
814 /// `try_reclaim` returns false under these conditions:
815 /// - The spare capacity left is less than `additional` bytes AND
816 /// - The existing allocation cannot be reclaimed cheaply or it was less than
817 /// `additional` bytes in size
818 ///
819 /// Reclaiming the allocation cheaply is possible if the `BytesMut` has no outstanding
820 /// references through other `BytesMut`s or `Bytes` which point to the same underlying
821 /// storage.
822 ///
823 /// This method does not preserve data stored in the unused capacity.
824 ///
825 /// # Examples
826 ///
827 /// ```
828 /// use bytes::BytesMut;
829 ///
830 /// let mut buf = BytesMut::with_capacity(64);
831 /// assert_eq!(true, buf.try_reclaim(64));
832 /// assert_eq!(64, buf.capacity());
833 ///
834 /// buf.extend_from_slice(b"abcd");
835 /// let mut split = buf.split();
836 /// assert_eq!(60, buf.capacity());
837 /// assert_eq!(4, split.capacity());
838 /// assert_eq!(false, split.try_reclaim(64));
839 /// assert_eq!(false, buf.try_reclaim(64));
840 /// // The split buffer is filled with "abcd"
841 /// assert_eq!(false, split.try_reclaim(4));
842 /// // buf is empty and has capacity for 60 bytes
843 /// assert_eq!(true, buf.try_reclaim(60));
844 ///
845 /// drop(buf);
846 /// assert_eq!(false, split.try_reclaim(64));
847 ///
848 /// split.clear();
849 /// assert_eq!(4, split.capacity());
850 /// assert_eq!(true, split.try_reclaim(64));
851 /// assert_eq!(64, split.capacity());
852 /// ```
853 // I tried splitting out try_reclaim_inner after the short circuits, but it was inlined
854 // regardless with Rust 1.78.0 so probably not worth it
855 #[inline]
856 #[must_use = "consider BytesMut::reserve if you need an infallible reservation"]
857 pub fn try_reclaim(&mut self, additional: usize) -> bool {
858 let len = self.len();
859 let rem = self.capacity() - len;
860
861 if additional <= rem {
862 // The handle can already store at least `additional` more bytes, so
863 // there is no further work needed to be done.
864 return true;
865 }
866
867 self.reserve_inner(additional, false)
868 }
869
870 /// Appends given bytes to this `BytesMut`.
871 ///
872 /// If this `BytesMut` object does not have enough capacity, it is resized
873 /// first.
874 ///
875 /// # Examples
876 ///
877 /// ```
878 /// use bytes::BytesMut;
879 ///
880 /// let mut buf = BytesMut::with_capacity(0);
881 /// buf.extend_from_slice(b"aaabbb");
882 /// buf.extend_from_slice(b"cccddd");
883 ///
884 /// assert_eq!(b"aaabbbcccddd", &buf[..]);
885 /// ```
886 #[inline]
887 pub fn extend_from_slice(&mut self, extend: &[u8]) {
888 let cnt = extend.len();
889 self.reserve(cnt);
890
891 unsafe {
892 let dst = self.spare_capacity_mut();
893 // Reserved above
894 debug_assert!(dst.len() >= cnt);
895
896 ptr::copy_nonoverlapping(extend.as_ptr(), dst.as_mut_ptr().cast(), cnt);
897 }
898
899 unsafe {
900 self.advance_mut(cnt);
901 }
902 }
903
904 /// Clones the elements in the given `range` within this `BytesMut` and
905 /// appends them to the end.
906 ///
907 /// # Panics
908 ///
909 /// Panics if `range` is out of bounds for this `BytesMut`.
910 ///
911 /// # Examples
912 ///
913 /// ```
914 /// use bytes::BytesMut;
915 ///
916 /// let mut buf = BytesMut::with_capacity(0);
917 /// buf.extend_from_slice(b"aaabbb_");
918 /// buf.extend_from_within(3..6);
919 ///
920 /// assert_eq!(b"aaabbb_bbb", &buf[..]);
921 /// ```
922 pub fn extend_from_within(&mut self, range: impl core::ops::RangeBounds<usize>) {
923 let (begin, end) = crate::range(range, self.len());
924
925 let cnt = end - begin;
926 self.reserve(cnt);
927
928 // SAFETY: range is already checked
929 let src = unsafe { self.as_ptr().add(begin) };
930 let dst = self.spare_capacity_mut();
931
932 // SAFETY: range doesn't overlap with spare capacity
933 unsafe { ptr::copy_nonoverlapping(src, dst.as_mut_ptr().cast(), cnt) }
934
935 // SAFETY: capacity is already reserved and filled with data
936 unsafe { self.advance_mut(cnt) }
937 }
938
939 /// Absorbs a `BytesMut` that was previously split off if they are
940 /// contiguous, otherwise appends its bytes to this `BytesMut`.
941 ///
942 /// If the two `BytesMut` objects were previously contiguous and not mutated
943 /// in a way that causes re-allocation i.e., if `other` was created by
944 /// calling `split_off` on this `BytesMut`, then this is an `O(1)` operation
945 /// that just decreases a reference count and sets a few indices.
946 /// Otherwise this method degenerates to
947 /// `self.extend_from_slice(other.as_ref())`.
948 ///
949 /// # Examples
950 ///
951 /// ```
952 /// use bytes::BytesMut;
953 ///
954 /// let mut buf = BytesMut::with_capacity(64);
955 /// buf.extend_from_slice(b"aaabbbcccddd");
956 ///
957 /// let split = buf.split_off(6);
958 /// assert_eq!(b"aaabbb", &buf[..]);
959 /// assert_eq!(b"cccddd", &split[..]);
960 ///
961 /// buf.unsplit(split);
962 /// assert_eq!(b"aaabbbcccddd", &buf[..]);
963 /// ```
964 pub fn unsplit(&mut self, other: BytesMut) {
965 if self.is_empty() {
966 *self = other;
967 return;
968 }
969
970 if let Err(other) = self.try_unsplit(other) {
971 self.extend_from_slice(other.as_ref());
972 }
973 }
974
975 // private
976
977 // For now, use a `Vec` to manage the memory for us, but we may want to
978 // change that in the future to some alternate allocator strategy.
979 //
980 // Thus, we don't expose an easy way to construct from a `Vec` since an
981 // internal change could make a simple pattern (`BytesMut::from(vec)`)
982 // suddenly a lot more expensive.
983 #[inline]
984 pub(crate) fn from_vec(vec: Vec<u8>) -> BytesMut {
985 let mut vec = ManuallyDrop::new(vec);
986 let ptr = vptr(vec.as_mut_ptr());
987 let len = vec.len();
988 let cap = vec.capacity();
989
990 let original_capacity_repr = original_capacity_to_repr(cap);
991 let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;
992
993 BytesMut {
994 ptr,
995 len,
996 cap,
997 data: invalid_ptr(data),
998 }
999 }
1000
1001 #[inline]
1002 fn as_slice(&self) -> &[u8] {
1003 unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
1004 }
1005
1006 #[inline]
1007 fn as_slice_mut(&mut self) -> &mut [u8] {
1008 unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
1009 }
1010
1011 /// Advance the buffer without bounds checking.
1012 ///
1013 /// # SAFETY
1014 ///
1015 /// The caller must ensure that `count` <= `self.cap`.
1016 pub(crate) unsafe fn advance_unchecked(&mut self, count: usize) {
1017 // Setting the start to 0 is a no-op, so return early if this is the
1018 // case.
1019 if count == 0 {
1020 return;
1021 }
1022
1023 debug_assert!(count <= self.cap, "internal: set_start out of bounds");
1024
1025 let kind = self.kind();
1026
1027 if kind == KIND_VEC {
1028 // Setting the start when in vec representation is a little more
1029 // complicated. First, we have to track how far ahead the
1030 // "start" of the byte buffer from the beginning of the vec. We
1031 // also have to ensure that we don't exceed the maximum shift.
1032 let pos = self.get_vec_pos() + count;
1033
1034 if pos <= MAX_VEC_POS {
1035 self.set_vec_pos(pos);
1036 } else {
1037 // The repr must be upgraded to ARC. This will never happen
1038 // on 64 bit systems and will only happen on 32 bit systems
1039 // when shifting past 134,217,727 bytes. As such, we don't
1040 // worry too much about performance here.
1041 self.promote_to_shared(/*ref_count = */ 1);
1042 }
1043 }
1044
1045 // Updating the start of the view is setting `ptr` to point to the
1046 // new start and updating the `len` field to reflect the new length
1047 // of the view.
1048 self.ptr = vptr(self.ptr.as_ptr().add(count));
1049 self.len = self.len.saturating_sub(count);
1050 self.cap -= count;
1051 }
1052
1053 /// Absorbs a `BytesMut` that was previously split off.
1054 ///
1055 /// If the two `BytesMut` objects were previously contiguous, i.e., if
1056 /// `other` was created by calling `split_off` on this `BytesMut`, then
1057 /// this is an `O(1)` operation that just decreases a reference
1058 /// count and sets a few indices. Otherwise this method returns an error
1059 /// containing the original `other`.
1060 ///
1061 /// # Examples
1062 ///
1063 /// ```
1064 /// use bytes::BytesMut;
1065 ///
1066 /// let mut buf = BytesMut::with_capacity(64);
1067 /// buf.extend_from_slice(b"aaabbbcccddd");
1068 ///
1069 /// let mut split_1 = buf.split_off(3);
1070 /// let split_2 = split_1.split_off(3);
1071 /// assert_eq!(b"aaa", &buf[..]);
1072 /// assert_eq!(b"bbb", &split_1[..]);
1073 /// assert_eq!(b"cccddd", &split_2[..]);
1074 ///
1075 /// let split_2 = buf.try_unsplit(split_2).unwrap_err();
1076 ///
1077 /// buf.try_unsplit(split_1).unwrap();
1078 /// buf.try_unsplit(split_2).unwrap();
1079 /// assert_eq!(b"aaabbbcccddd", &buf[..]);
1080 /// ```
1081 pub fn try_unsplit(&mut self, other: BytesMut) -> Result<(), BytesMut> {
1082 if other.capacity() == 0 {
1083 return Ok(());
1084 }
1085
1086 let ptr = unsafe { self.ptr.as_ptr().add(self.len) };
1087 if ptr == other.ptr.as_ptr()
1088 && self.kind() == KIND_ARC
1089 && other.kind() == KIND_ARC
1090 && self.data == other.data
1091 {
1092 // Contiguous blocks, just combine directly
1093 self.len += other.len;
1094 self.cap += other.cap;
1095 Ok(())
1096 } else {
1097 Err(other)
1098 }
1099 }
1100
1101 #[inline]
1102 fn kind(&self) -> usize {
1103 self.data as usize & KIND_MASK
1104 }
1105
1106 unsafe fn promote_to_shared(&mut self, ref_cnt: usize) {
1107 debug_assert_eq!(self.kind(), KIND_VEC);
1108 debug_assert!(ref_cnt == 1 || ref_cnt == 2);
1109
1110 let original_capacity_repr =
1111 (self.data as usize & ORIGINAL_CAPACITY_MASK) >> ORIGINAL_CAPACITY_OFFSET;
1112
1113 // The vec offset cannot be concurrently mutated, so there
1114 // should be no danger reading it.
1115 let off = (self.data as usize) >> VEC_POS_OFFSET;
1116
1117 // First, allocate a new `Shared` instance containing the
1118 // `Vec` fields. It's important to note that `ptr`, `len`,
1119 // and `cap` cannot be mutated without having `&mut self`.
1120 // This means that these fields will not be concurrently
1121 // updated and since the buffer hasn't been promoted to an
1122 // `Arc`, those three fields still are the components of the
1123 // vector.
1124 //
1125 // Explicitly allocate before invoking rebuild_vec() so that
1126 // the vector is not dropped if Box::new() panics.
1127 let shared = Box::new(MaybeUninit::<Shared>::uninit());
1128 let shared = Shared::init_to_raw(
1129 shared,
1130 Shared {
1131 vec: rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off),
1132 original_capacity_repr,
1133 ref_count: AtomicUsize::new(ref_cnt),
1134 },
1135 );
1136
1137 // The pointer should be aligned, so this assert should
1138 // always succeed.
1139 debug_assert_eq!(shared as usize & KIND_MASK, KIND_ARC);
1140
1141 self.data = shared;
1142 }
1143
1144 /// Makes an exact shallow clone of `self`.
1145 ///
1146 /// The kind of `self` doesn't matter, but this is unsafe
1147 /// because the clone will have the same offsets. You must
1148 /// be sure the returned value to the user doesn't allow
1149 /// two views into the same range.
1150 #[inline]
1151 unsafe fn shallow_clone(&mut self) -> BytesMut {
1152 if self.kind() == KIND_ARC {
1153 increment_shared(self.data);
1154 ptr::read(self)
1155 } else {
1156 self.promote_to_shared(/*ref_count = */ 2);
1157 ptr::read(self)
1158 }
1159 }
1160
1161 #[inline]
1162 unsafe fn get_vec_pos(&self) -> usize {
1163 debug_assert_eq!(self.kind(), KIND_VEC);
1164
1165 self.data as usize >> VEC_POS_OFFSET
1166 }
1167
1168 #[inline]
1169 unsafe fn set_vec_pos(&mut self, pos: usize) {
1170 debug_assert_eq!(self.kind(), KIND_VEC);
1171 debug_assert!(pos <= MAX_VEC_POS);
1172
1173 self.data = invalid_ptr((pos << VEC_POS_OFFSET) | (self.data as usize & NOT_VEC_POS_MASK));
1174 }
1175
1176 /// Returns the remaining spare capacity of the buffer as a slice of `MaybeUninit<u8>`.
1177 ///
1178 /// The returned slice can be used to fill the buffer with data (e.g. by
1179 /// reading from a file) before marking the data as initialized using the
1180 /// [`set_len`] method.
1181 ///
1182 /// [`set_len`]: BytesMut::set_len
1183 ///
1184 /// # Examples
1185 ///
1186 /// ```
1187 /// use bytes::BytesMut;
1188 ///
1189 /// // Allocate buffer big enough for 10 bytes.
1190 /// let mut buf = BytesMut::with_capacity(10);
1191 ///
1192 /// // Fill in the first 3 elements.
1193 /// let uninit = buf.spare_capacity_mut();
1194 /// uninit[0].write(0);
1195 /// uninit[1].write(1);
1196 /// uninit[2].write(2);
1197 ///
1198 /// // Mark the first 3 bytes of the buffer as being initialized.
1199 /// unsafe {
1200 /// buf.set_len(3);
1201 /// }
1202 ///
1203 /// assert_eq!(&buf[..], &[0, 1, 2]);
1204 /// ```
1205 #[inline]
1206 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1207 unsafe {
1208 let ptr = self.ptr.as_ptr().add(self.len);
1209 let len = self.cap - self.len;
1210
1211 slice::from_raw_parts_mut(ptr.cast(), len)
1212 }
1213 }
1214}
1215
1216impl Drop for BytesMut {
1217 fn drop(&mut self) {
1218 let kind = self.kind();
1219
1220 if kind == KIND_VEC {
1221 unsafe {
1222 let off = self.get_vec_pos();
1223
1224 // Vector storage, free the vector
1225 let _ = rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off);
1226 }
1227 } else if kind == KIND_ARC {
1228 unsafe { release_shared(self.data) };
1229 }
1230 }
1231}
1232
1233impl Buf for BytesMut {
1234 #[inline]
1235 fn remaining(&self) -> usize {
1236 self.len()
1237 }
1238
1239 #[inline]
1240 fn chunk(&self) -> &[u8] {
1241 self.as_slice()
1242 }
1243
1244 #[inline]
1245 fn advance(&mut self, cnt: usize) {
1246 assert!(
1247 cnt <= self.remaining(),
1248 "cannot advance past `remaining`: {:?} <= {:?}",
1249 cnt,
1250 self.remaining(),
1251 );
1252 unsafe {
1253 // SAFETY: We've checked that `cnt` <= `self.remaining()` and we know that
1254 // `self.remaining()` <= `self.cap`.
1255 self.advance_unchecked(cnt);
1256 }
1257 }
1258
1259 fn copy_to_bytes(&mut self, len: usize) -> Bytes {
1260 self.split_to(len).freeze()
1261 }
1262}
1263
1264unsafe impl BufMut for BytesMut {
1265 #[inline]
1266 fn remaining_mut(&self) -> usize {
1267 // Max allocation size is isize::MAX.
1268 isize::MAX as usize - self.len()
1269 }
1270
1271 #[inline]
1272 unsafe fn advance_mut(&mut self, cnt: usize) {
1273 let remaining = self.cap - self.len();
1274 if cnt > remaining {
1275 super::panic_advance(&TryGetError {
1276 requested: cnt,
1277 available: remaining,
1278 });
1279 }
1280 // Addition won't overflow since it is at most `self.cap`.
1281 self.len = self.len() + cnt;
1282 }
1283
1284 #[inline]
1285 fn chunk_mut(&mut self) -> &mut UninitSlice {
1286 if self.capacity() == self.len() {
1287 self.reserve(64);
1288 }
1289 self.spare_capacity_mut().into()
1290 }
1291
1292 // Specialize these methods so they can skip checking `remaining_mut`
1293 // and `advance_mut`.
1294
1295 fn put<T: Buf>(&mut self, mut src: T)
1296 where
1297 Self: Sized,
1298 {
1299 if !src.has_remaining() {
1300 // prevent calling `copy_to_bytes`->`put`->`copy_to_bytes` infintely when src is empty
1301 return;
1302 } else if self.capacity() == 0 {
1303 // When capacity is zero, try reusing allocation of `src`.
1304 let src_copy = src.copy_to_bytes(src.remaining());
1305 drop(src);
1306 match src_copy.try_into_mut() {
1307 Ok(bytes_mut) => *self = bytes_mut,
1308 Err(bytes) => self.extend_from_slice(&bytes),
1309 }
1310 } else {
1311 // In case the src isn't contiguous, reserve upfront.
1312 self.reserve(src.remaining());
1313
1314 while src.has_remaining() {
1315 let s = src.chunk();
1316 let l = s.len();
1317 self.extend_from_slice(s);
1318 src.advance(l);
1319 }
1320 }
1321 }
1322
1323 fn put_slice(&mut self, src: &[u8]) {
1324 self.extend_from_slice(src);
1325 }
1326
1327 fn put_bytes(&mut self, val: u8, cnt: usize) {
1328 self.reserve(cnt);
1329 unsafe {
1330 let dst = self.spare_capacity_mut();
1331 // Reserved above
1332 debug_assert!(dst.len() >= cnt);
1333
1334 ptr::write_bytes(dst.as_mut_ptr(), val, cnt);
1335
1336 self.advance_mut(cnt);
1337 }
1338 }
1339}
1340
1341impl AsRef<[u8]> for BytesMut {
1342 #[inline]
1343 fn as_ref(&self) -> &[u8] {
1344 self.as_slice()
1345 }
1346}
1347
1348impl Deref for BytesMut {
1349 type Target = [u8];
1350
1351 #[inline]
1352 fn deref(&self) -> &[u8] {
1353 self.as_ref()
1354 }
1355}
1356
1357impl AsMut<[u8]> for BytesMut {
1358 #[inline]
1359 fn as_mut(&mut self) -> &mut [u8] {
1360 self.as_slice_mut()
1361 }
1362}
1363
1364impl DerefMut for BytesMut {
1365 #[inline]
1366 fn deref_mut(&mut self) -> &mut [u8] {
1367 self.as_mut()
1368 }
1369}
1370
1371impl<'a> From<&'a [u8]> for BytesMut {
1372 fn from(src: &'a [u8]) -> BytesMut {
1373 BytesMut::from_vec(src.to_vec())
1374 }
1375}
1376
1377impl<'a> From<&'a str> for BytesMut {
1378 fn from(src: &'a str) -> BytesMut {
1379 BytesMut::from(src.as_bytes())
1380 }
1381}
1382
1383impl From<BytesMut> for Bytes {
1384 fn from(src: BytesMut) -> Bytes {
1385 src.freeze()
1386 }
1387}
1388
1389impl PartialEq for BytesMut {
1390 fn eq(&self, other: &BytesMut) -> bool {
1391 self.as_slice() == other.as_slice()
1392 }
1393}
1394
1395impl PartialOrd for BytesMut {
1396 fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1397 Some(self.cmp(other))
1398 }
1399}
1400
1401impl Ord for BytesMut {
1402 fn cmp(&self, other: &BytesMut) -> cmp::Ordering {
1403 self.as_slice().cmp(other.as_slice())
1404 }
1405}
1406
1407impl Eq for BytesMut {}
1408
1409impl Default for BytesMut {
1410 #[inline]
1411 fn default() -> BytesMut {
1412 BytesMut::new()
1413 }
1414}
1415
1416impl hash::Hash for BytesMut {
1417 fn hash<H>(&self, state: &mut H)
1418 where
1419 H: hash::Hasher,
1420 {
1421 let s: &[u8] = self.as_ref();
1422 s.hash(state);
1423 }
1424}
1425
1426impl Borrow<[u8]> for BytesMut {
1427 fn borrow(&self) -> &[u8] {
1428 self.as_ref()
1429 }
1430}
1431
1432impl BorrowMut<[u8]> for BytesMut {
1433 fn borrow_mut(&mut self) -> &mut [u8] {
1434 self.as_mut()
1435 }
1436}
1437
1438impl fmt::Write for BytesMut {
1439 #[inline]
1440 fn write_str(&mut self, s: &str) -> fmt::Result {
1441 if self.remaining_mut() >= s.len() {
1442 self.put_slice(s.as_bytes());
1443 Ok(())
1444 } else {
1445 Err(fmt::Error)
1446 }
1447 }
1448
1449 #[inline]
1450 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
1451 fmt::write(self, args)
1452 }
1453}
1454
1455impl Clone for BytesMut {
1456 fn clone(&self) -> BytesMut {
1457 BytesMut::from(&self[..])
1458 }
1459}
1460
1461impl IntoIterator for BytesMut {
1462 type Item = u8;
1463 type IntoIter = IntoIter<BytesMut>;
1464
1465 fn into_iter(self) -> Self::IntoIter {
1466 IntoIter::new(self)
1467 }
1468}
1469
1470impl<'a> IntoIterator for &'a BytesMut {
1471 type Item = &'a u8;
1472 type IntoIter = core::slice::Iter<'a, u8>;
1473
1474 fn into_iter(self) -> Self::IntoIter {
1475 self.as_ref().iter()
1476 }
1477}
1478
1479impl Extend<u8> for BytesMut {
1480 fn extend<T>(&mut self, iter: T)
1481 where
1482 T: IntoIterator<Item = u8>,
1483 {
1484 let iter = iter.into_iter();
1485
1486 let (lower, _) = iter.size_hint();
1487 self.reserve(lower);
1488
1489 // TODO: optimize
1490 // 1. If self.kind() == KIND_VEC, use Vec::extend
1491 for b in iter {
1492 self.put_u8(b);
1493 }
1494 }
1495}
1496
1497impl<'a> Extend<&'a u8> for BytesMut {
1498 fn extend<T>(&mut self, iter: T)
1499 where
1500 T: IntoIterator<Item = &'a u8>,
1501 {
1502 self.extend(iter.into_iter().copied())
1503 }
1504}
1505
1506impl Extend<Bytes> for BytesMut {
1507 fn extend<T>(&mut self, iter: T)
1508 where
1509 T: IntoIterator<Item = Bytes>,
1510 {
1511 for bytes in iter {
1512 self.extend_from_slice(&bytes)
1513 }
1514 }
1515}
1516
1517impl FromIterator<u8> for BytesMut {
1518 fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
1519 BytesMut::from_vec(Vec::from_iter(into_iter))
1520 }
1521}
1522
1523impl<'a> FromIterator<&'a u8> for BytesMut {
1524 fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
1525 BytesMut::from_iter(into_iter.into_iter().copied())
1526 }
1527}
1528
1529/*
1530 *
1531 * ===== Inner =====
1532 *
1533 */
1534
1535unsafe fn increment_shared(ptr: *mut Shared) {
1536 let old_size = (*ptr).ref_count.fetch_add(1, Ordering::Relaxed);
1537
1538 if old_size > isize::MAX as usize {
1539 crate::abort();
1540 }
1541}
1542
1543unsafe fn release_shared(ptr: *mut Shared) {
1544 // `Shared` storage... follow the drop steps from Arc.
1545 if (*ptr).ref_count.fetch_sub(1, Ordering::Release) != 1 {
1546 return;
1547 }
1548
1549 // This fence is needed to prevent reordering of use of the data and
1550 // deletion of the data. Because it is marked `Release`, the decreasing
1551 // of the reference count synchronizes with this `Acquire` fence. This
1552 // means that use of the data happens before decreasing the reference
1553 // count, which happens before this fence, which happens before the
1554 // deletion of the data.
1555 //
1556 // As explained in the [Boost documentation][1],
1557 //
1558 // > It is important to enforce any possible access to the object in one
1559 // > thread (through an existing reference) to *happen before* deleting
1560 // > the object in a different thread. This is achieved by a "release"
1561 // > operation after dropping a reference (any access to the object
1562 // > through this reference must obviously happened before), and an
1563 // > "acquire" operation before deleting the object.
1564 //
1565 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
1566 //
1567 // Thread sanitizer does not support atomic fences. Use an atomic load
1568 // instead.
1569 (*ptr).ref_count.load(Ordering::Acquire);
1570
1571 // Drop the data
1572 drop(Box::from_raw(ptr));
1573}
1574
1575impl Shared {
1576 fn is_unique(&self) -> bool {
1577 // The goal is to check if the current handle is the only handle
1578 // that currently has access to the buffer. This is done by
1579 // checking if the `ref_count` is currently 1.
1580 //
1581 // The `Acquire` ordering synchronizes with the `Release` as
1582 // part of the `fetch_sub` in `release_shared`. The `fetch_sub`
1583 // operation guarantees that any mutations done in other threads
1584 // are ordered before the `ref_count` is decremented. As such,
1585 // this `Acquire` will guarantee that those mutations are
1586 // visible to the current thread.
1587 self.ref_count.load(Ordering::Acquire) == 1
1588 }
1589}
1590
1591#[inline]
1592fn original_capacity_to_repr(cap: usize) -> usize {
1593 let width = PTR_WIDTH - ((cap >> MIN_ORIGINAL_CAPACITY_WIDTH).leading_zeros() as usize);
1594 cmp::min(
1595 width,
1596 MAX_ORIGINAL_CAPACITY_WIDTH - MIN_ORIGINAL_CAPACITY_WIDTH,
1597 )
1598}
1599
1600fn original_capacity_from_repr(repr: usize) -> usize {
1601 if repr == 0 {
1602 return 0;
1603 }
1604
1605 1 << (repr + (MIN_ORIGINAL_CAPACITY_WIDTH - 1))
1606}
1607
1608#[cfg(test)]
1609mod tests {
1610 use super::*;
1611
1612 #[test]
1613 fn test_original_capacity_to_repr() {
1614 assert_eq!(original_capacity_to_repr(0), 0);
1615
1616 let max_width = 32;
1617
1618 for width in 1..(max_width + 1) {
1619 let cap = 1 << width - 1;
1620
1621 let expected = if width < MIN_ORIGINAL_CAPACITY_WIDTH {
1622 0
1623 } else if width < MAX_ORIGINAL_CAPACITY_WIDTH {
1624 width - MIN_ORIGINAL_CAPACITY_WIDTH
1625 } else {
1626 MAX_ORIGINAL_CAPACITY_WIDTH - MIN_ORIGINAL_CAPACITY_WIDTH
1627 };
1628
1629 assert_eq!(original_capacity_to_repr(cap), expected);
1630
1631 if width > 1 {
1632 assert_eq!(original_capacity_to_repr(cap + 1), expected);
1633 }
1634
1635 // MIN_ORIGINAL_CAPACITY_WIDTH must be bigger than 7 to pass tests below
1636 if width == MIN_ORIGINAL_CAPACITY_WIDTH + 1 {
1637 assert_eq!(original_capacity_to_repr(cap - 24), expected - 1);
1638 assert_eq!(original_capacity_to_repr(cap + 76), expected);
1639 } else if width == MIN_ORIGINAL_CAPACITY_WIDTH + 2 {
1640 assert_eq!(original_capacity_to_repr(cap - 1), expected - 1);
1641 assert_eq!(original_capacity_to_repr(cap - 48), expected - 1);
1642 }
1643 }
1644 }
1645
1646 #[test]
1647 fn test_original_capacity_from_repr() {
1648 assert_eq!(0, original_capacity_from_repr(0));
1649
1650 let min_cap = 1 << MIN_ORIGINAL_CAPACITY_WIDTH;
1651
1652 assert_eq!(min_cap, original_capacity_from_repr(1));
1653 assert_eq!(min_cap * 2, original_capacity_from_repr(2));
1654 assert_eq!(min_cap * 4, original_capacity_from_repr(3));
1655 assert_eq!(min_cap * 8, original_capacity_from_repr(4));
1656 assert_eq!(min_cap * 16, original_capacity_from_repr(5));
1657 assert_eq!(min_cap * 32, original_capacity_from_repr(6));
1658 assert_eq!(min_cap * 64, original_capacity_from_repr(7));
1659 }
1660}
1661
1662unsafe impl Send for BytesMut {}
1663unsafe impl Sync for BytesMut {}
1664
1665/*
1666 *
1667 * ===== PartialEq / PartialOrd =====
1668 *
1669 */
1670
1671impl PartialEq<[u8]> for BytesMut {
1672 fn eq(&self, other: &[u8]) -> bool {
1673 &**self == other
1674 }
1675}
1676
1677impl PartialOrd<[u8]> for BytesMut {
1678 fn partial_cmp(&self, other: &[u8]) -> Option<cmp::Ordering> {
1679 (**self).partial_cmp(other)
1680 }
1681}
1682
1683impl PartialEq<BytesMut> for [u8] {
1684 fn eq(&self, other: &BytesMut) -> bool {
1685 *other == *self
1686 }
1687}
1688
1689impl PartialOrd<BytesMut> for [u8] {
1690 fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1691 <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other)
1692 }
1693}
1694
1695impl PartialEq<str> for BytesMut {
1696 fn eq(&self, other: &str) -> bool {
1697 &**self == other.as_bytes()
1698 }
1699}
1700
1701impl PartialOrd<str> for BytesMut {
1702 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1703 (**self).partial_cmp(other.as_bytes())
1704 }
1705}
1706
1707impl PartialEq<BytesMut> for str {
1708 fn eq(&self, other: &BytesMut) -> bool {
1709 *other == *self
1710 }
1711}
1712
1713impl PartialOrd<BytesMut> for str {
1714 fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1715 <[u8] as PartialOrd<[u8]>>::partial_cmp(self.as_bytes(), other)
1716 }
1717}
1718
1719impl PartialEq<Vec<u8>> for BytesMut {
1720 fn eq(&self, other: &Vec<u8>) -> bool {
1721 *self == other[..]
1722 }
1723}
1724
1725impl PartialOrd<Vec<u8>> for BytesMut {
1726 fn partial_cmp(&self, other: &Vec<u8>) -> Option<cmp::Ordering> {
1727 (**self).partial_cmp(&other[..])
1728 }
1729}
1730
1731impl PartialEq<BytesMut> for Vec<u8> {
1732 fn eq(&self, other: &BytesMut) -> bool {
1733 *other == *self
1734 }
1735}
1736
1737impl PartialOrd<BytesMut> for Vec<u8> {
1738 fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1739 other.partial_cmp(self)
1740 }
1741}
1742
1743impl PartialEq<String> for BytesMut {
1744 fn eq(&self, other: &String) -> bool {
1745 *self == other[..]
1746 }
1747}
1748
1749impl PartialOrd<String> for BytesMut {
1750 fn partial_cmp(&self, other: &String) -> Option<cmp::Ordering> {
1751 (**self).partial_cmp(other.as_bytes())
1752 }
1753}
1754
1755impl PartialEq<BytesMut> for String {
1756 fn eq(&self, other: &BytesMut) -> bool {
1757 *other == *self
1758 }
1759}
1760
1761impl PartialOrd<BytesMut> for String {
1762 fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1763 <[u8] as PartialOrd<[u8]>>::partial_cmp(self.as_bytes(), other)
1764 }
1765}
1766
1767impl<'a, T: ?Sized> PartialEq<&'a T> for BytesMut
1768where
1769 BytesMut: PartialEq<T>,
1770{
1771 fn eq(&self, other: &&'a T) -> bool {
1772 *self == **other
1773 }
1774}
1775
1776impl<'a, T: ?Sized> PartialOrd<&'a T> for BytesMut
1777where
1778 BytesMut: PartialOrd<T>,
1779{
1780 fn partial_cmp(&self, other: &&'a T) -> Option<cmp::Ordering> {
1781 self.partial_cmp(*other)
1782 }
1783}
1784
1785impl PartialEq<BytesMut> for &[u8] {
1786 fn eq(&self, other: &BytesMut) -> bool {
1787 *other == *self
1788 }
1789}
1790
1791impl PartialOrd<BytesMut> for &[u8] {
1792 fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1793 <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other)
1794 }
1795}
1796
1797impl PartialEq<BytesMut> for &str {
1798 fn eq(&self, other: &BytesMut) -> bool {
1799 *other == *self
1800 }
1801}
1802
1803impl PartialOrd<BytesMut> for &str {
1804 fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1805 other.partial_cmp(self)
1806 }
1807}
1808
1809impl PartialEq<BytesMut> for Bytes {
1810 fn eq(&self, other: &BytesMut) -> bool {
1811 other[..] == self[..]
1812 }
1813}
1814
1815impl PartialEq<Bytes> for BytesMut {
1816 fn eq(&self, other: &Bytes) -> bool {
1817 other[..] == self[..]
1818 }
1819}
1820
1821impl From<BytesMut> for Vec<u8> {
1822 fn from(bytes: BytesMut) -> Self {
1823 let kind = bytes.kind();
1824 let bytes = ManuallyDrop::new(bytes);
1825
1826 let mut vec = if kind == KIND_VEC {
1827 unsafe {
1828 let off = bytes.get_vec_pos();
1829 rebuild_vec(bytes.ptr.as_ptr(), bytes.len, bytes.cap, off)
1830 }
1831 } else {
1832 let shared = bytes.data;
1833
1834 if unsafe { (*shared).is_unique() } {
1835 let vec = core::mem::take(unsafe { &mut (*shared).vec });
1836
1837 unsafe { release_shared(shared) };
1838
1839 vec
1840 } else {
1841 return ManuallyDrop::into_inner(bytes).deref().to_vec();
1842 }
1843 };
1844
1845 let len = bytes.len;
1846
1847 unsafe {
1848 ptr::copy(bytes.ptr.as_ptr(), vec.as_mut_ptr(), len);
1849 vec.set_len(len);
1850 }
1851
1852 vec
1853 }
1854}
1855
1856#[inline]
1857fn vptr(ptr: *mut u8) -> NonNull<u8> {
1858 if cfg!(debug_assertions) {
1859 NonNull::new(ptr).expect("Vec pointer should be non-null")
1860 } else {
1861 unsafe { NonNull::new_unchecked(ptr) }
1862 }
1863}
1864
1865/// Returns a dangling pointer with the given address. This is used to store
1866/// integer data in pointer fields.
1867///
1868/// It is equivalent to `addr as *mut T`, but this fails on miri when strict
1869/// provenance checking is enabled.
1870#[inline]
1871fn invalid_ptr<T>(addr: usize) -> *mut T {
1872 let ptr = core::ptr::null_mut::<u8>().wrapping_add(addr);
1873 debug_assert_eq!(ptr as usize, addr);
1874 ptr.cast::<T>()
1875}
1876
1877unsafe fn rebuild_vec(ptr: *mut u8, mut len: usize, mut cap: usize, off: usize) -> Vec<u8> {
1878 let ptr = ptr.sub(off);
1879 len += off;
1880 cap += off;
1881
1882 Vec::from_raw_parts(ptr, len, cap)
1883}
1884
1885// ===== impl SharedVtable =====
1886
1887static SHARED_VTABLE: Vtable = Vtable {
1888 clone: shared_v_clone,
1889 into_vec: shared_v_to_vec,
1890 into_mut: shared_v_to_mut,
1891 is_unique: shared_v_is_unique,
1892 drop: shared_v_drop,
1893};
1894
1895unsafe fn shared_v_clone(data: &AtomicPtr<()>, ptr: *const u8, len: usize) -> Bytes {
1896 let shared = data.load(Ordering::Relaxed) as *mut Shared;
1897 increment_shared(shared);
1898
1899 let data = AtomicPtr::new(shared as *mut ());
1900 Bytes::with_vtable(ptr, len, data, &SHARED_VTABLE)
1901}
1902
1903unsafe fn shared_v_to_vec(shared: *mut (), ptr: *const u8, len: usize) -> Vec<u8> {
1904 let shared: *mut Shared = shared.cast();
1905
1906 if (*shared).is_unique() {
1907 let shared = &mut *shared;
1908
1909 // Drop shared
1910 let mut vec = core::mem::take(&mut shared.vec);
1911 release_shared(shared);
1912
1913 // Copy back buffer
1914 ptr::copy(ptr, vec.as_mut_ptr(), len);
1915 vec.set_len(len);
1916
1917 vec
1918 } else {
1919 let v = slice::from_raw_parts(ptr, len).to_vec();
1920 release_shared(shared);
1921 v
1922 }
1923}
1924
1925unsafe fn shared_v_to_mut(shared: *mut (), ptr: *const u8, len: usize) -> BytesMut {
1926 let shared: *mut Shared = shared.cast();
1927
1928 if (*shared).is_unique() {
1929 let shared = &mut *shared;
1930
1931 // The capacity is always the original capacity of the buffer
1932 // minus the offset from the start of the buffer
1933 let v = &mut shared.vec;
1934 let v_capacity = v.capacity();
1935 let v_ptr = v.as_mut_ptr();
1936 let offset = ptr.offset_from(v_ptr) as usize;
1937 let cap = v_capacity - offset;
1938
1939 let ptr = vptr(ptr as *mut u8);
1940
1941 BytesMut {
1942 ptr,
1943 len,
1944 cap,
1945 data: shared,
1946 }
1947 } else {
1948 let v = slice::from_raw_parts(ptr, len).to_vec();
1949 release_shared(shared);
1950 BytesMut::from_vec(v)
1951 }
1952}
1953
1954unsafe fn shared_v_is_unique(data: &AtomicPtr<()>) -> bool {
1955 let shared = data.load(Ordering::Acquire);
1956 let ref_count = (*shared.cast::<Shared>()).ref_count.load(Ordering::Relaxed);
1957 ref_count == 1
1958}
1959
1960unsafe fn shared_v_drop(shared: *mut (), _ptr: *const u8, _len: usize) {
1961 release_shared(shared.cast());
1962}
1963
1964// compile-fails
1965
1966/// ```compile_fail
1967/// use bytes::BytesMut;
1968/// #[deny(unused_must_use)]
1969/// {
1970/// let mut b1 = BytesMut::from("hello world");
1971/// b1.split_to(6);
1972/// }
1973/// ```
1974fn _split_to_must_use() {}
1975
1976/// ```compile_fail
1977/// use bytes::BytesMut;
1978/// #[deny(unused_must_use)]
1979/// {
1980/// let mut b1 = BytesMut::from("hello world");
1981/// b1.split_off(6);
1982/// }
1983/// ```
1984fn _split_off_must_use() {}
1985
1986/// ```compile_fail
1987/// use bytes::BytesMut;
1988/// #[deny(unused_must_use)]
1989/// {
1990/// let mut b1 = BytesMut::from("hello world");
1991/// b1.split();
1992/// }
1993/// ```
1994fn _split_must_use() {}
1995
1996// fuzz tests
1997#[cfg(all(test, loom))]
1998mod fuzz {
1999 use loom::sync::Arc;
2000 use loom::thread;
2001
2002 use super::BytesMut;
2003 use crate::Bytes;
2004
2005 #[test]
2006 fn bytes_mut_cloning_frozen() {
2007 loom::model(|| {
2008 let a = BytesMut::from(&b"abcdefgh"[..]).split().freeze();
2009 let addr = a.as_ptr() as usize;
2010
2011 // test the Bytes::clone is Sync by putting it in an Arc
2012 let a1 = Arc::new(a);
2013 let a2 = a1.clone();
2014
2015 let t1 = thread::spawn(move || {
2016 let b: Bytes = (*a1).clone();
2017 assert_eq!(b.as_ptr() as usize, addr);
2018 });
2019
2020 let t2 = thread::spawn(move || {
2021 let b: Bytes = (*a2).clone();
2022 assert_eq!(b.as_ptr() as usize, addr);
2023 });
2024
2025 t1.join().unwrap();
2026 t2.join().unwrap();
2027 });
2028 }
2029}