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