Coverage Report

Created: 2026-01-10 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/bytes-1.11.0/src/bytes_mut.rs
Line
Count
Source
1
use core::mem::{self, ManuallyDrop, MaybeUninit};
2
use core::ops::{Deref, DerefMut};
3
use core::ptr::{self, NonNull};
4
use core::{cmp, fmt, hash, slice};
5
6
use alloc::{
7
    borrow::{Borrow, BorrowMut},
8
    boxed::Box,
9
    string::String,
10
    vec,
11
    vec::Vec,
12
};
13
14
use crate::buf::{IntoIter, UninitSlice};
15
use crate::bytes::Vtable;
16
#[allow(unused)]
17
use crate::loom::sync::atomic::AtomicMut;
18
use crate::loom::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
19
use 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
/// ```
60
pub 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.
76
struct 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.
86
const _: [(); 0 - mem::align_of::<Shared>() % 2] = []; // Assert that the alignment of `Shared` is divisible by 2.
87
88
// Buffer storage strategy flags.
89
const KIND_ARC: usize = 0b0;
90
const KIND_VEC: usize = 0b1;
91
const KIND_MASK: usize = 0b1;
92
93
// The max original capacity value. Any `Bytes` allocated with a greater initial
94
// capacity will default to this.
95
const 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.
98
const 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.
101
const ORIGINAL_CAPACITY_MASK: usize = 0b11100;
102
const ORIGINAL_CAPACITY_OFFSET: usize = 2;
103
104
const 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.
109
const MAX_VEC_POS: usize = usize::MAX >> VEC_POS_OFFSET;
110
const NOT_VEC_POS_MASK: usize = 0b11111;
111
112
#[cfg(target_pointer_width = "64")]
113
const PTR_WIDTH: usize = 64;
114
#[cfg(target_pointer_width = "32")]
115
const PTR_WIDTH: usize = 32;
116
117
/*
118
 *
119
 * ===== BytesMut =====
120
 *
121
 */
122
123
impl 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
0
    pub fn with_capacity(capacity: usize) -> BytesMut {
148
0
        BytesMut::from_vec(Vec::with_capacity(capacity))
149
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::with_capacity
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::with_capacity
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
0
    pub fn new() -> BytesMut {
172
0
        BytesMut::with_capacity(0)
173
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::new
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::new
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
0
    pub fn len(&self) -> usize {
187
0
        self.len
188
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::len
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::len
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
0
    pub fn is_empty(&self) -> bool {
202
0
        self.len == 0
203
0
    }
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
0
    pub fn capacity(&self) -> usize {
217
0
        self.cap
218
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::capacity
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::capacity
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
0
    pub fn freeze(self) -> Bytes {
246
0
        let bytes = ManuallyDrop::new(self);
247
0
        if bytes.kind() == KIND_VEC {
248
            // Just re-use `Bytes` internal Vec vtable
249
            unsafe {
250
0
                let off = bytes.get_vec_pos();
251
0
                let vec = rebuild_vec(bytes.ptr.as_ptr(), bytes.len, bytes.cap, off);
252
0
                let mut b: Bytes = vec.into();
253
0
                b.advance(off);
254
0
                b
255
            }
256
        } else {
257
0
            debug_assert_eq!(bytes.kind(), KIND_ARC);
258
259
0
            let ptr = bytes.ptr.as_ptr();
260
0
            let len = bytes.len;
261
0
            let data = AtomicPtr::new(bytes.data.cast());
262
0
            unsafe { Bytes::with_vtable(ptr, len, data, &SHARED_VTABLE) }
263
        }
264
0
    }
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
0
    pub fn zeroed(len: usize) -> BytesMut {
287
0
        BytesMut::from_vec(vec![0; len])
288
0
    }
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
0
    pub fn split_off(&mut self, at: usize) -> BytesMut {
320
0
        assert!(
321
0
            at <= self.capacity(),
322
0
            "split_off out of bounds: {:?} <= {:?}",
323
            at,
324
0
            self.capacity(),
325
        );
326
        unsafe {
327
0
            let mut other = self.shallow_clone();
328
            // SAFETY: We've checked that `at` <= `self.capacity()` above.
329
0
            other.advance_unchecked(at);
330
0
            self.cap = at;
331
0
            self.len = cmp::min(self.len, at);
332
0
            other
333
        }
334
0
    }
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
0
    pub fn split(&mut self) -> BytesMut {
363
0
        let len = self.len();
364
0
        self.split_to(len)
365
0
    }
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
0
    pub fn split_to(&mut self, at: usize) -> BytesMut {
395
0
        assert!(
396
0
            at <= self.len(),
397
0
            "split_to out of bounds: {:?} <= {:?}",
398
            at,
399
0
            self.len(),
400
        );
401
402
        unsafe {
403
0
            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
0
            self.advance_unchecked(at);
407
0
            other.cap = at;
408
0
            other.len = at;
409
0
            other
410
        }
411
0
    }
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
0
    pub fn truncate(&mut self, len: usize) {
434
0
        if len <= self.len() {
435
0
            // SAFETY: Shrinking the buffer cannot expose uninitialized bytes.
436
0
            unsafe { self.set_len(len) };
437
0
        }
438
0
    }
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
0
    pub fn clear(&mut self) {
452
        // SAFETY: Setting the length to zero cannot expose uninitialized bytes.
453
0
        unsafe { self.set_len(0) };
454
0
    }
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
0
    pub fn resize(&mut self, new_len: usize, value: u8) {
479
0
        let additional = if let Some(additional) = new_len.checked_sub(self.len()) {
480
0
            additional
481
        } else {
482
0
            self.truncate(new_len);
483
0
            return;
484
        };
485
486
0
        if additional == 0 {
487
0
            return;
488
0
        }
489
490
0
        self.reserve(additional);
491
0
        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
0
        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
0
        unsafe { self.set_len(new_len) };
499
0
    }
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
0
    pub unsafe fn set_len(&mut self, len: usize) {
528
0
        debug_assert!(len <= self.cap, "set_len out of bounds");
529
0
        self.len = len;
530
0
    }
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
0
    pub fn reserve(&mut self, additional: usize) {
592
0
        let len = self.len();
593
0
        let rem = self.capacity() - len;
594
595
0
        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
0
            return;
599
0
        }
600
601
        // will always succeed
602
0
        let _ = self.reserve_inner(additional, true);
603
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::reserve
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::reserve
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
0
    fn reserve_inner(&mut self, additional: usize, allocate: bool) -> bool {
608
0
        let len = self.len();
609
0
        let kind = self.kind();
610
611
0
        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
0
                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
0
                if self.capacity() - self.len() + off >= additional && off >= self.len() {
637
0
                    // There's enough space, and it's not too much overhead:
638
0
                    // reuse the space!
639
0
                    //
640
0
                    // Just move the pointer back to the start after copying
641
0
                    // data back.
642
0
                    let base_ptr = self.ptr.as_ptr().sub(off);
643
0
                    // Since `off >= self.len()`, the two regions don't overlap.
644
0
                    ptr::copy_nonoverlapping(self.ptr.as_ptr(), base_ptr, self.len);
645
0
                    self.ptr = vptr(base_ptr);
646
0
                    self.set_vec_pos(0);
647
0
648
0
                    // Length stays constant, but since we moved backwards we
649
0
                    // can gain capacity back.
650
0
                    self.cap += off;
651
0
                } else {
652
0
                    if !allocate {
653
0
                        return false;
654
0
                    }
655
                    // Not enough space, or reusing might be too much overhead:
656
                    // allocate more space!
657
0
                    let mut v =
658
0
                        ManuallyDrop::new(rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off));
659
0
                    v.reserve(additional);
660
661
                    // Update the info
662
0
                    self.ptr = vptr(v.as_mut_ptr().add(off));
663
0
                    self.cap = v.capacity() - off;
664
0
                    debug_assert_eq!(self.len, v.len() - off);
665
                }
666
667
0
                return true;
668
            }
669
0
        }
670
671
0
        debug_assert_eq!(kind, KIND_ARC);
672
0
        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
0
        let mut new_cap = match len.checked_add(additional) {
679
0
            Some(new_cap) => new_cap,
680
0
            None if !allocate => return false,
681
0
            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
0
            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
0
                let v = &mut (*shared).vec;
692
693
0
                let v_capacity = v.capacity();
694
0
                let ptr = v.as_mut_ptr();
695
696
0
                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
0
                if v_capacity >= new_cap + offset {
701
0
                    self.cap = new_cap;
702
0
                    // no copy is necessary
703
0
                } else if v_capacity >= new_cap && offset >= len {
704
0
                    // The capacity is sufficient, and copying is not too much
705
0
                    // overhead: reclaim the buffer!
706
0
707
0
                    // `offset >= len` means: no overlap
708
0
                    ptr::copy_nonoverlapping(self.ptr.as_ptr(), ptr, len);
709
0
710
0
                    self.ptr = vptr(ptr);
711
0
                    self.cap = v.capacity();
712
0
                } else {
713
0
                    if !allocate {
714
0
                        return false;
715
0
                    }
716
                    // calculate offset
717
0
                    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
0
                    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
0
                    let double = v.capacity().checked_shl(1).unwrap_or(new_cap);
734
735
0
                    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
0
                    debug_assert!(off + len <= v.capacity());
746
0
                    v.set_len(off + len);
747
0
                    v.reserve(new_cap - v.len());
748
749
                    // Update the info
750
0
                    self.ptr = vptr(v.as_mut_ptr().add(off));
751
0
                    self.cap = v.capacity() - off;
752
                }
753
754
0
                return true;
755
0
            }
756
        }
757
0
        if !allocate {
758
0
            return false;
759
0
        }
760
761
0
        let original_capacity_repr = unsafe { (*shared).original_capacity_repr };
762
0
        let original_capacity = original_capacity_from_repr(original_capacity_repr);
763
764
0
        new_cap = cmp::max(new_cap, original_capacity);
765
766
        // Create a new vector to store the data
767
0
        let mut v = ManuallyDrop::new(Vec::with_capacity(new_cap));
768
769
        // Copy the bytes
770
0
        v.extend_from_slice(self.as_ref());
771
772
        // Release the shared handle. This must be done *after* the bytes are
773
        // copied.
774
0
        unsafe { release_shared(shared) };
775
776
        // Update self
777
0
        let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;
778
0
        self.data = invalid_ptr(data);
779
0
        self.ptr = vptr(v.as_mut_ptr());
780
0
        self.cap = v.capacity();
781
0
        debug_assert_eq!(self.len, v.len());
782
0
        true
783
0
    }
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
0
    pub fn try_reclaim(&mut self, additional: usize) -> bool {
833
0
        let len = self.len();
834
0
        let rem = self.capacity() - len;
835
836
0
        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
0
            return true;
840
0
        }
841
842
0
        self.reserve_inner(additional, false)
843
0
    }
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
0
    pub fn extend_from_slice(&mut self, extend: &[u8]) {
863
0
        let cnt = extend.len();
864
0
        self.reserve(cnt);
865
866
        unsafe {
867
0
            let dst = self.spare_capacity_mut();
868
            // Reserved above
869
0
            debug_assert!(dst.len() >= cnt);
870
871
0
            ptr::copy_nonoverlapping(extend.as_ptr(), dst.as_mut_ptr().cast(), cnt);
872
        }
873
874
0
        unsafe {
875
0
            self.advance_mut(cnt);
876
0
        }
877
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::extend_from_slice
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::extend_from_slice
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
0
    pub fn unsplit(&mut self, other: BytesMut) {
904
0
        if self.is_empty() {
905
0
            *self = other;
906
0
            return;
907
0
        }
908
909
0
        if let Err(other) = self.try_unsplit(other) {
910
0
            self.extend_from_slice(other.as_ref());
911
0
        }
912
0
    }
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
0
    pub(crate) fn from_vec(vec: Vec<u8>) -> BytesMut {
924
0
        let mut vec = ManuallyDrop::new(vec);
925
0
        let ptr = vptr(vec.as_mut_ptr());
926
0
        let len = vec.len();
927
0
        let cap = vec.capacity();
928
929
0
        let original_capacity_repr = original_capacity_to_repr(cap);
930
0
        let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;
931
932
0
        BytesMut {
933
0
            ptr,
934
0
            len,
935
0
            cap,
936
0
            data: invalid_ptr(data),
937
0
        }
938
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::from_vec
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::from_vec
939
940
    #[inline]
941
0
    fn as_slice(&self) -> &[u8] {
942
0
        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
943
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::as_slice
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::as_slice
944
945
    #[inline]
946
0
    fn as_slice_mut(&mut self) -> &mut [u8] {
947
0
        unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
948
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::as_slice_mut
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::as_slice_mut
949
950
    /// Advance the buffer without bounds checking.
951
    ///
952
    /// # SAFETY
953
    ///
954
    /// The caller must ensure that `count` <= `self.cap`.
955
0
    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
0
        if count == 0 {
959
0
            return;
960
0
        }
961
962
0
        debug_assert!(count <= self.cap, "internal: set_start out of bounds");
963
964
0
        let kind = self.kind();
965
966
0
        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
0
            let pos = self.get_vec_pos() + count;
972
973
0
            if pos <= MAX_VEC_POS {
974
0
                self.set_vec_pos(pos);
975
0
            } else {
976
0
                // The repr must be upgraded to ARC. This will never happen
977
0
                // on 64 bit systems and will only happen on 32 bit systems
978
0
                // when shifting past 134,217,727 bytes. As such, we don't
979
0
                // worry too much about performance here.
980
0
                self.promote_to_shared(/*ref_count = */ 1);
981
0
            }
982
0
        }
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
0
        self.ptr = vptr(self.ptr.as_ptr().add(count));
988
0
        self.len = self.len.saturating_sub(count);
989
0
        self.cap -= count;
990
0
    }
991
992
0
    fn try_unsplit(&mut self, other: BytesMut) -> Result<(), BytesMut> {
993
0
        if other.capacity() == 0 {
994
0
            return Ok(());
995
0
        }
996
997
0
        let ptr = unsafe { self.ptr.as_ptr().add(self.len) };
998
0
        if ptr == other.ptr.as_ptr()
999
0
            && self.kind() == KIND_ARC
1000
0
            && other.kind() == KIND_ARC
1001
0
            && self.data == other.data
1002
        {
1003
            // Contiguous blocks, just combine directly
1004
0
            self.len += other.len;
1005
0
            self.cap += other.cap;
1006
0
            Ok(())
1007
        } else {
1008
0
            Err(other)
1009
        }
1010
0
    }
1011
1012
    #[inline]
1013
0
    fn kind(&self) -> usize {
1014
0
        self.data as usize & KIND_MASK
1015
0
    }
1016
1017
0
    unsafe fn promote_to_shared(&mut self, ref_cnt: usize) {
1018
0
        debug_assert_eq!(self.kind(), KIND_VEC);
1019
0
        debug_assert!(ref_cnt == 1 || ref_cnt == 2);
1020
1021
0
        let original_capacity_repr =
1022
0
            (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
0
        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
0
        let shared = Box::new(Shared {
1036
0
            vec: rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off),
1037
0
            original_capacity_repr,
1038
0
            ref_count: AtomicUsize::new(ref_cnt),
1039
0
        });
1040
1041
0
        let shared = Box::into_raw(shared);
1042
1043
        // The pointer should be aligned, so this assert should
1044
        // always succeed.
1045
0
        debug_assert_eq!(shared as usize & KIND_MASK, KIND_ARC);
1046
1047
0
        self.data = shared;
1048
0
    }
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
0
    unsafe fn shallow_clone(&mut self) -> BytesMut {
1058
0
        if self.kind() == KIND_ARC {
1059
0
            increment_shared(self.data);
1060
0
            ptr::read(self)
1061
        } else {
1062
0
            self.promote_to_shared(/*ref_count = */ 2);
1063
0
            ptr::read(self)
1064
        }
1065
0
    }
1066
1067
    #[inline]
1068
0
    unsafe fn get_vec_pos(&self) -> usize {
1069
0
        debug_assert_eq!(self.kind(), KIND_VEC);
1070
1071
0
        self.data as usize >> VEC_POS_OFFSET
1072
0
    }
1073
1074
    #[inline]
1075
0
    unsafe fn set_vec_pos(&mut self, pos: usize) {
1076
0
        debug_assert_eq!(self.kind(), KIND_VEC);
1077
0
        debug_assert!(pos <= MAX_VEC_POS);
1078
1079
0
        self.data = invalid_ptr((pos << VEC_POS_OFFSET) | (self.data as usize & NOT_VEC_POS_MASK));
1080
0
    }
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
0
    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1113
0
        unsafe {
1114
0
            let ptr = self.ptr.as_ptr().add(self.len);
1115
0
            let len = self.cap - self.len;
1116
0
1117
0
            slice::from_raw_parts_mut(ptr.cast(), len)
1118
0
        }
1119
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::spare_capacity_mut
Unexecuted instantiation: <bytes::bytes_mut::BytesMut>::spare_capacity_mut
1120
}
1121
1122
impl Drop for BytesMut {
1123
0
    fn drop(&mut self) {
1124
0
        let kind = self.kind();
1125
1126
0
        if kind == KIND_VEC {
1127
0
            unsafe {
1128
0
                let off = self.get_vec_pos();
1129
0
1130
0
                // Vector storage, free the vector
1131
0
                let _ = rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off);
1132
0
            }
1133
0
        } else if kind == KIND_ARC {
1134
0
            unsafe { release_shared(self.data) };
1135
0
        }
1136
0
    }
1137
}
1138
1139
impl Buf for BytesMut {
1140
    #[inline]
1141
0
    fn remaining(&self) -> usize {
1142
0
        self.len()
1143
0
    }
1144
1145
    #[inline]
1146
0
    fn chunk(&self) -> &[u8] {
1147
0
        self.as_slice()
1148
0
    }
1149
1150
    #[inline]
1151
0
    fn advance(&mut self, cnt: usize) {
1152
0
        assert!(
1153
0
            cnt <= self.remaining(),
1154
0
            "cannot advance past `remaining`: {:?} <= {:?}",
1155
            cnt,
1156
0
            self.remaining(),
1157
        );
1158
0
        unsafe {
1159
0
            // SAFETY: We've checked that `cnt` <= `self.remaining()` and we know that
1160
0
            // `self.remaining()` <= `self.cap`.
1161
0
            self.advance_unchecked(cnt);
1162
0
        }
1163
0
    }
1164
1165
0
    fn copy_to_bytes(&mut self, len: usize) -> Bytes {
1166
0
        self.split_to(len).freeze()
1167
0
    }
1168
}
1169
1170
unsafe impl BufMut for BytesMut {
1171
    #[inline]
1172
0
    fn remaining_mut(&self) -> usize {
1173
        // Max allocation size is isize::MAX.
1174
0
        isize::MAX as usize - self.len()
1175
0
    }
1176
1177
    #[inline]
1178
0
    unsafe fn advance_mut(&mut self, cnt: usize) {
1179
0
        let remaining = self.cap - self.len();
1180
0
        if cnt > remaining {
1181
0
            super::panic_advance(&TryGetError {
1182
0
                requested: cnt,
1183
0
                available: remaining,
1184
0
            });
1185
0
        }
1186
        // Addition won't overflow since it is at most `self.cap`.
1187
0
        self.len = self.len() + cnt;
1188
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as bytes::buf::buf_mut::BufMut>::advance_mut
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as bytes::buf::buf_mut::BufMut>::advance_mut
1189
1190
    #[inline]
1191
0
    fn chunk_mut(&mut self) -> &mut UninitSlice {
1192
0
        if self.capacity() == self.len() {
1193
0
            self.reserve(64);
1194
0
        }
1195
0
        self.spare_capacity_mut().into()
1196
0
    }
1197
1198
    // Specialize these methods so they can skip checking `remaining_mut`
1199
    // and `advance_mut`.
1200
1201
0
    fn put<T: Buf>(&mut self, mut src: T)
1202
0
    where
1203
0
        Self: Sized,
1204
    {
1205
0
        if !src.has_remaining() {
1206
            // prevent calling `copy_to_bytes`->`put`->`copy_to_bytes` infintely when src is empty
1207
0
            return;
1208
0
        } else if self.capacity() == 0 {
1209
            // When capacity is zero, try reusing allocation of `src`.
1210
0
            let src_copy = src.copy_to_bytes(src.remaining());
1211
0
            drop(src);
1212
0
            match src_copy.try_into_mut() {
1213
0
                Ok(bytes_mut) => *self = bytes_mut,
1214
0
                Err(bytes) => self.extend_from_slice(&bytes),
1215
            }
1216
        } else {
1217
            // In case the src isn't contiguous, reserve upfront.
1218
0
            self.reserve(src.remaining());
1219
1220
0
            while src.has_remaining() {
1221
0
                let s = src.chunk();
1222
0
                let l = s.len();
1223
0
                self.extend_from_slice(s);
1224
0
                src.advance(l);
1225
0
            }
1226
        }
1227
0
    }
1228
1229
0
    fn put_slice(&mut self, src: &[u8]) {
1230
0
        self.extend_from_slice(src);
1231
0
    }
1232
1233
0
    fn put_bytes(&mut self, val: u8, cnt: usize) {
1234
0
        self.reserve(cnt);
1235
        unsafe {
1236
0
            let dst = self.spare_capacity_mut();
1237
            // Reserved above
1238
0
            debug_assert!(dst.len() >= cnt);
1239
1240
0
            ptr::write_bytes(dst.as_mut_ptr(), val, cnt);
1241
1242
0
            self.advance_mut(cnt);
1243
        }
1244
0
    }
1245
}
1246
1247
impl AsRef<[u8]> for BytesMut {
1248
    #[inline]
1249
0
    fn as_ref(&self) -> &[u8] {
1250
0
        self.as_slice()
1251
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as core::convert::AsRef<[u8]>>::as_ref
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as core::convert::AsRef<[u8]>>::as_ref
1252
}
1253
1254
impl Deref for BytesMut {
1255
    type Target = [u8];
1256
1257
    #[inline]
1258
0
    fn deref(&self) -> &[u8] {
1259
0
        self.as_ref()
1260
0
    }
1261
}
1262
1263
impl AsMut<[u8]> for BytesMut {
1264
    #[inline]
1265
0
    fn as_mut(&mut self) -> &mut [u8] {
1266
0
        self.as_slice_mut()
1267
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as core::convert::AsMut<[u8]>>::as_mut
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as core::convert::AsMut<[u8]>>::as_mut
1268
}
1269
1270
impl DerefMut for BytesMut {
1271
    #[inline]
1272
0
    fn deref_mut(&mut self) -> &mut [u8] {
1273
0
        self.as_mut()
1274
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as core::ops::deref::DerefMut>::deref_mut
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as core::ops::deref::DerefMut>::deref_mut
1275
}
1276
1277
impl<'a> From<&'a [u8]> for BytesMut {
1278
0
    fn from(src: &'a [u8]) -> BytesMut {
1279
0
        BytesMut::from_vec(src.to_vec())
1280
0
    }
1281
}
1282
1283
impl<'a> From<&'a str> for BytesMut {
1284
0
    fn from(src: &'a str) -> BytesMut {
1285
0
        BytesMut::from(src.as_bytes())
1286
0
    }
1287
}
1288
1289
impl From<BytesMut> for Bytes {
1290
0
    fn from(src: BytesMut) -> Bytes {
1291
0
        src.freeze()
1292
0
    }
1293
}
1294
1295
impl PartialEq for BytesMut {
1296
0
    fn eq(&self, other: &BytesMut) -> bool {
1297
0
        self.as_slice() == other.as_slice()
1298
0
    }
1299
}
1300
1301
impl PartialOrd for BytesMut {
1302
0
    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1303
0
        Some(self.cmp(other))
1304
0
    }
1305
}
1306
1307
impl Ord for BytesMut {
1308
0
    fn cmp(&self, other: &BytesMut) -> cmp::Ordering {
1309
0
        self.as_slice().cmp(other.as_slice())
1310
0
    }
1311
}
1312
1313
impl Eq for BytesMut {}
1314
1315
impl Default for BytesMut {
1316
    #[inline]
1317
0
    fn default() -> BytesMut {
1318
0
        BytesMut::new()
1319
0
    }
1320
}
1321
1322
impl hash::Hash for BytesMut {
1323
0
    fn hash<H>(&self, state: &mut H)
1324
0
    where
1325
0
        H: hash::Hasher,
1326
    {
1327
0
        let s: &[u8] = self.as_ref();
1328
0
        s.hash(state);
1329
0
    }
1330
}
1331
1332
impl Borrow<[u8]> for BytesMut {
1333
0
    fn borrow(&self) -> &[u8] {
1334
0
        self.as_ref()
1335
0
    }
1336
}
1337
1338
impl BorrowMut<[u8]> for BytesMut {
1339
0
    fn borrow_mut(&mut self) -> &mut [u8] {
1340
0
        self.as_mut()
1341
0
    }
1342
}
1343
1344
impl fmt::Write for BytesMut {
1345
    #[inline]
1346
0
    fn write_str(&mut self, s: &str) -> fmt::Result {
1347
0
        if self.remaining_mut() >= s.len() {
1348
0
            self.put_slice(s.as_bytes());
1349
0
            Ok(())
1350
        } else {
1351
0
            Err(fmt::Error)
1352
        }
1353
0
    }
1354
1355
    #[inline]
1356
0
    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
1357
0
        fmt::write(self, args)
1358
0
    }
1359
}
1360
1361
impl Clone for BytesMut {
1362
0
    fn clone(&self) -> BytesMut {
1363
0
        BytesMut::from(&self[..])
1364
0
    }
1365
}
1366
1367
impl IntoIterator for BytesMut {
1368
    type Item = u8;
1369
    type IntoIter = IntoIter<BytesMut>;
1370
1371
0
    fn into_iter(self) -> Self::IntoIter {
1372
0
        IntoIter::new(self)
1373
0
    }
1374
}
1375
1376
impl<'a> IntoIterator for &'a BytesMut {
1377
    type Item = &'a u8;
1378
    type IntoIter = core::slice::Iter<'a, u8>;
1379
1380
0
    fn into_iter(self) -> Self::IntoIter {
1381
0
        self.as_ref().iter()
1382
0
    }
1383
}
1384
1385
impl Extend<u8> for BytesMut {
1386
0
    fn extend<T>(&mut self, iter: T)
1387
0
    where
1388
0
        T: IntoIterator<Item = u8>,
1389
    {
1390
0
        let iter = iter.into_iter();
1391
1392
0
        let (lower, _) = iter.size_hint();
1393
0
        self.reserve(lower);
1394
1395
        // TODO: optimize
1396
        // 1. If self.kind() == KIND_VEC, use Vec::extend
1397
0
        for b in iter {
1398
0
            self.put_u8(b);
1399
0
        }
1400
0
    }
1401
}
1402
1403
impl<'a> Extend<&'a u8> for BytesMut {
1404
0
    fn extend<T>(&mut self, iter: T)
1405
0
    where
1406
0
        T: IntoIterator<Item = &'a u8>,
1407
    {
1408
0
        self.extend(iter.into_iter().copied())
1409
0
    }
1410
}
1411
1412
impl Extend<Bytes> for BytesMut {
1413
0
    fn extend<T>(&mut self, iter: T)
1414
0
    where
1415
0
        T: IntoIterator<Item = Bytes>,
1416
    {
1417
0
        for bytes in iter {
1418
0
            self.extend_from_slice(&bytes)
1419
        }
1420
0
    }
1421
}
1422
1423
impl FromIterator<u8> for BytesMut {
1424
0
    fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
1425
0
        BytesMut::from_vec(Vec::from_iter(into_iter))
1426
0
    }
1427
}
1428
1429
impl<'a> FromIterator<&'a u8> for BytesMut {
1430
0
    fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
1431
0
        BytesMut::from_iter(into_iter.into_iter().copied())
1432
0
    }
1433
}
1434
1435
/*
1436
 *
1437
 * ===== Inner =====
1438
 *
1439
 */
1440
1441
0
unsafe fn increment_shared(ptr: *mut Shared) {
1442
0
    let old_size = (*ptr).ref_count.fetch_add(1, Ordering::Relaxed);
1443
1444
0
    if old_size > isize::MAX as usize {
1445
0
        crate::abort();
1446
0
    }
1447
0
}
1448
1449
0
unsafe fn release_shared(ptr: *mut Shared) {
1450
    // `Shared` storage... follow the drop steps from Arc.
1451
0
    if (*ptr).ref_count.fetch_sub(1, Ordering::Release) != 1 {
1452
0
        return;
1453
0
    }
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
0
    (*ptr).ref_count.load(Ordering::Acquire);
1476
1477
    // Drop the data
1478
0
    drop(Box::from_raw(ptr));
1479
0
}
1480
1481
impl Shared {
1482
0
    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
0
        self.ref_count.load(Ordering::Acquire) == 1
1494
0
    }
1495
}
1496
1497
#[inline]
1498
0
fn original_capacity_to_repr(cap: usize) -> usize {
1499
0
    let width = PTR_WIDTH - ((cap >> MIN_ORIGINAL_CAPACITY_WIDTH).leading_zeros() as usize);
1500
0
    cmp::min(
1501
0
        width,
1502
0
        MAX_ORIGINAL_CAPACITY_WIDTH - MIN_ORIGINAL_CAPACITY_WIDTH,
1503
    )
1504
0
}
Unexecuted instantiation: bytes::bytes_mut::original_capacity_to_repr
Unexecuted instantiation: bytes::bytes_mut::original_capacity_to_repr
1505
1506
0
fn original_capacity_from_repr(repr: usize) -> usize {
1507
0
    if repr == 0 {
1508
0
        return 0;
1509
0
    }
1510
1511
0
    1 << (repr + (MIN_ORIGINAL_CAPACITY_WIDTH - 1))
1512
0
}
1513
1514
#[cfg(test)]
1515
mod 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
1568
unsafe impl Send for BytesMut {}
1569
unsafe impl Sync for BytesMut {}
1570
1571
/*
1572
 *
1573
 * ===== PartialEq / PartialOrd =====
1574
 *
1575
 */
1576
1577
impl PartialEq<[u8]> for BytesMut {
1578
0
    fn eq(&self, other: &[u8]) -> bool {
1579
0
        &**self == other
1580
0
    }
1581
}
1582
1583
impl PartialOrd<[u8]> for BytesMut {
1584
0
    fn partial_cmp(&self, other: &[u8]) -> Option<cmp::Ordering> {
1585
0
        (**self).partial_cmp(other)
1586
0
    }
1587
}
1588
1589
impl PartialEq<BytesMut> for [u8] {
1590
0
    fn eq(&self, other: &BytesMut) -> bool {
1591
0
        *other == *self
1592
0
    }
1593
}
1594
1595
impl PartialOrd<BytesMut> for [u8] {
1596
0
    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1597
0
        <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other)
1598
0
    }
1599
}
1600
1601
impl PartialEq<str> for BytesMut {
1602
0
    fn eq(&self, other: &str) -> bool {
1603
0
        &**self == other.as_bytes()
1604
0
    }
1605
}
1606
1607
impl PartialOrd<str> for BytesMut {
1608
0
    fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1609
0
        (**self).partial_cmp(other.as_bytes())
1610
0
    }
1611
}
1612
1613
impl PartialEq<BytesMut> for str {
1614
0
    fn eq(&self, other: &BytesMut) -> bool {
1615
0
        *other == *self
1616
0
    }
1617
}
1618
1619
impl PartialOrd<BytesMut> for str {
1620
0
    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1621
0
        <[u8] as PartialOrd<[u8]>>::partial_cmp(self.as_bytes(), other)
1622
0
    }
1623
}
1624
1625
impl PartialEq<Vec<u8>> for BytesMut {
1626
0
    fn eq(&self, other: &Vec<u8>) -> bool {
1627
0
        *self == other[..]
1628
0
    }
1629
}
1630
1631
impl PartialOrd<Vec<u8>> for BytesMut {
1632
0
    fn partial_cmp(&self, other: &Vec<u8>) -> Option<cmp::Ordering> {
1633
0
        (**self).partial_cmp(&other[..])
1634
0
    }
1635
}
1636
1637
impl PartialEq<BytesMut> for Vec<u8> {
1638
0
    fn eq(&self, other: &BytesMut) -> bool {
1639
0
        *other == *self
1640
0
    }
1641
}
1642
1643
impl PartialOrd<BytesMut> for Vec<u8> {
1644
0
    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1645
0
        other.partial_cmp(self)
1646
0
    }
1647
}
1648
1649
impl PartialEq<String> for BytesMut {
1650
0
    fn eq(&self, other: &String) -> bool {
1651
0
        *self == other[..]
1652
0
    }
1653
}
1654
1655
impl PartialOrd<String> for BytesMut {
1656
0
    fn partial_cmp(&self, other: &String) -> Option<cmp::Ordering> {
1657
0
        (**self).partial_cmp(other.as_bytes())
1658
0
    }
1659
}
1660
1661
impl PartialEq<BytesMut> for String {
1662
0
    fn eq(&self, other: &BytesMut) -> bool {
1663
0
        *other == *self
1664
0
    }
1665
}
1666
1667
impl PartialOrd<BytesMut> for String {
1668
0
    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1669
0
        <[u8] as PartialOrd<[u8]>>::partial_cmp(self.as_bytes(), other)
1670
0
    }
1671
}
1672
1673
impl<'a, T: ?Sized> PartialEq<&'a T> for BytesMut
1674
where
1675
    BytesMut: PartialEq<T>,
1676
{
1677
0
    fn eq(&self, other: &&'a T) -> bool {
1678
0
        *self == **other
1679
0
    }
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as core::cmp::PartialEq<&[u8]>>::eq
Unexecuted instantiation: <bytes::bytes_mut::BytesMut as core::cmp::PartialEq<&str>>::eq
1680
}
1681
1682
impl<'a, T: ?Sized> PartialOrd<&'a T> for BytesMut
1683
where
1684
    BytesMut: PartialOrd<T>,
1685
{
1686
0
    fn partial_cmp(&self, other: &&'a T) -> Option<cmp::Ordering> {
1687
0
        self.partial_cmp(*other)
1688
0
    }
1689
}
1690
1691
impl PartialEq<BytesMut> for &[u8] {
1692
0
    fn eq(&self, other: &BytesMut) -> bool {
1693
0
        *other == *self
1694
0
    }
1695
}
1696
1697
impl PartialOrd<BytesMut> for &[u8] {
1698
0
    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1699
0
        <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other)
1700
0
    }
1701
}
1702
1703
impl PartialEq<BytesMut> for &str {
1704
0
    fn eq(&self, other: &BytesMut) -> bool {
1705
0
        *other == *self
1706
0
    }
1707
}
1708
1709
impl PartialOrd<BytesMut> for &str {
1710
0
    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1711
0
        other.partial_cmp(self)
1712
0
    }
1713
}
1714
1715
impl PartialEq<BytesMut> for Bytes {
1716
0
    fn eq(&self, other: &BytesMut) -> bool {
1717
0
        other[..] == self[..]
1718
0
    }
1719
}
1720
1721
impl PartialEq<Bytes> for BytesMut {
1722
0
    fn eq(&self, other: &Bytes) -> bool {
1723
0
        other[..] == self[..]
1724
0
    }
1725
}
1726
1727
impl From<BytesMut> for Vec<u8> {
1728
0
    fn from(bytes: BytesMut) -> Self {
1729
0
        let kind = bytes.kind();
1730
0
        let bytes = ManuallyDrop::new(bytes);
1731
1732
0
        let mut vec = if kind == KIND_VEC {
1733
            unsafe {
1734
0
                let off = bytes.get_vec_pos();
1735
0
                rebuild_vec(bytes.ptr.as_ptr(), bytes.len, bytes.cap, off)
1736
            }
1737
        } else {
1738
0
            let shared = bytes.data;
1739
1740
0
            if unsafe { (*shared).is_unique() } {
1741
0
                let vec = core::mem::take(unsafe { &mut (*shared).vec });
1742
1743
0
                unsafe { release_shared(shared) };
1744
1745
0
                vec
1746
            } else {
1747
0
                return ManuallyDrop::into_inner(bytes).deref().to_vec();
1748
            }
1749
        };
1750
1751
0
        let len = bytes.len;
1752
1753
0
        unsafe {
1754
0
            ptr::copy(bytes.ptr.as_ptr(), vec.as_mut_ptr(), len);
1755
0
            vec.set_len(len);
1756
0
        }
1757
1758
0
        vec
1759
0
    }
1760
}
1761
1762
#[inline]
1763
0
fn vptr(ptr: *mut u8) -> NonNull<u8> {
1764
0
    if cfg!(debug_assertions) {
1765
0
        NonNull::new(ptr).expect("Vec pointer should be non-null")
1766
    } else {
1767
0
        unsafe { NonNull::new_unchecked(ptr) }
1768
    }
1769
0
}
Unexecuted instantiation: bytes::bytes_mut::vptr
Unexecuted instantiation: bytes::bytes_mut::vptr
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]
1777
0
fn invalid_ptr<T>(addr: usize) -> *mut T {
1778
0
    let ptr = core::ptr::null_mut::<u8>().wrapping_add(addr);
1779
0
    debug_assert_eq!(ptr as usize, addr);
1780
0
    ptr.cast::<T>()
1781
0
}
1782
1783
0
unsafe fn rebuild_vec(ptr: *mut u8, mut len: usize, mut cap: usize, off: usize) -> Vec<u8> {
1784
0
    let ptr = ptr.sub(off);
1785
0
    len += off;
1786
0
    cap += off;
1787
1788
0
    Vec::from_raw_parts(ptr, len, cap)
1789
0
}
1790
1791
// ===== impl SharedVtable =====
1792
1793
static 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
1801
0
unsafe fn shared_v_clone(data: &AtomicPtr<()>, ptr: *const u8, len: usize) -> Bytes {
1802
0
    let shared = data.load(Ordering::Relaxed) as *mut Shared;
1803
0
    increment_shared(shared);
1804
1805
0
    let data = AtomicPtr::new(shared as *mut ());
1806
0
    Bytes::with_vtable(ptr, len, data, &SHARED_VTABLE)
1807
0
}
1808
1809
0
unsafe fn shared_v_to_vec(data: &AtomicPtr<()>, ptr: *const u8, len: usize) -> Vec<u8> {
1810
0
    let shared: *mut Shared = data.load(Ordering::Relaxed).cast();
1811
1812
0
    if (*shared).is_unique() {
1813
0
        let shared = &mut *shared;
1814
1815
        // Drop shared
1816
0
        let mut vec = core::mem::take(&mut shared.vec);
1817
0
        release_shared(shared);
1818
1819
        // Copy back buffer
1820
0
        ptr::copy(ptr, vec.as_mut_ptr(), len);
1821
0
        vec.set_len(len);
1822
1823
0
        vec
1824
    } else {
1825
0
        let v = slice::from_raw_parts(ptr, len).to_vec();
1826
0
        release_shared(shared);
1827
0
        v
1828
    }
1829
0
}
1830
1831
0
unsafe fn shared_v_to_mut(data: &AtomicPtr<()>, ptr: *const u8, len: usize) -> BytesMut {
1832
0
    let shared: *mut Shared = data.load(Ordering::Relaxed).cast();
1833
1834
0
    if (*shared).is_unique() {
1835
0
        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
0
        let v = &mut shared.vec;
1840
0
        let v_capacity = v.capacity();
1841
0
        let v_ptr = v.as_mut_ptr();
1842
0
        let offset = ptr.offset_from(v_ptr) as usize;
1843
0
        let cap = v_capacity - offset;
1844
1845
0
        let ptr = vptr(ptr as *mut u8);
1846
1847
0
        BytesMut {
1848
0
            ptr,
1849
0
            len,
1850
0
            cap,
1851
0
            data: shared,
1852
0
        }
1853
    } else {
1854
0
        let v = slice::from_raw_parts(ptr, len).to_vec();
1855
0
        release_shared(shared);
1856
0
        BytesMut::from_vec(v)
1857
    }
1858
0
}
1859
1860
0
unsafe fn shared_v_is_unique(data: &AtomicPtr<()>) -> bool {
1861
0
    let shared = data.load(Ordering::Acquire);
1862
0
    let ref_count = (*shared.cast::<Shared>()).ref_count.load(Ordering::Relaxed);
1863
0
    ref_count == 1
1864
0
}
1865
1866
0
unsafe fn shared_v_drop(data: &mut AtomicPtr<()>, _ptr: *const u8, _len: usize) {
1867
0
    data.with_mut(|shared| {
1868
0
        release_shared(*shared as *mut Shared);
1869
0
    });
1870
0
}
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
/// ```
1882
0
fn _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
/// ```
1892
0
fn _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
/// ```
1902
0
fn _split_must_use() {}
1903
1904
// fuzz tests
1905
#[cfg(all(test, loom))]
1906
mod 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
}