/
bytes_mut.rs
1468 lines (1285 loc) · 41.3 KB
/
bytes_mut.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use core::{cmp, fmt, hash, isize, mem, slice, usize};
use core::ops::{Deref, DerefMut};
use core::ptr::{self, NonNull};
use core::iter::{FromIterator, Iterator};
use alloc::{vec::Vec, string::String, boxed::Box, borrow::{Borrow, BorrowMut}};
use crate::{Bytes, Buf, BufMut};
use crate::bytes::Vtable;
use crate::buf::IntoIter;
use crate::debug;
use crate::loom::sync::atomic::{self, AtomicPtr, AtomicUsize, Ordering};
/// A unique reference to a contiguous slice of memory.
///
/// `BytesMut` represents a unique view into a potentially shared memory region.
/// Given the uniqueness guarantee, owners of `BytesMut` handles are able to
/// mutate the memory. It is similar to a `Vec<u8>` but with less copies and
/// allocations.
///
/// # Growth
///
/// One key difference from `Vec<u8>` is that most operations **do not
/// implicitly grow the buffer**. This means that calling `my_bytes.put("hello
/// world");` could panic if `my_bytes` does not have enough capacity. Before
/// writing to the buffer, ensure that there is enough remaining capacity by
/// calling `my_bytes.remaining_mut()`. In general, avoiding calls to `reserve`
/// is preferable.
///
/// The only exception is `extend` which implicitly reserves required capacity.
///
/// # Examples
///
/// ```
/// use bytes::{BytesMut, BufMut};
///
/// let mut buf = BytesMut::with_capacity(64);
///
/// buf.put_u8(b'h');
/// buf.put_u8(b'e');
/// buf.put(&b"llo"[..]);
///
/// assert_eq!(&buf[..], b"hello");
///
/// // Freeze the buffer so that it can be shared
/// let a = buf.freeze();
///
/// // This does not allocate, instead `b` points to the same memory.
/// let b = a.clone();
///
/// assert_eq!(&a[..], b"hello");
/// assert_eq!(&b[..], b"hello");
/// ```
pub struct BytesMut {
ptr: NonNull<u8>,
len: usize,
cap: usize,
data: *mut Shared,
}
// Thread-safe reference-counted container for the shared storage. This mostly
// the same as `core::sync::Arc` but without the weak counter. The ref counting
// fns are based on the ones found in `std`.
//
// The main reason to use `Shared` instead of `core::sync::Arc` is that it ends
// up making the overall code simpler and easier to reason about. This is due to
// some of the logic around setting `Inner::arc` and other ways the `arc` field
// is used. Using `Arc` ended up requiring a number of funky transmutes and
// other shenanigans to make it work.
struct Shared {
vec: Vec<u8>,
original_capacity_repr: usize,
ref_count: AtomicUsize,
}
// Buffer storage strategy flags.
const KIND_ARC: usize = 0b0;
const KIND_VEC: usize = 0b1;
const KIND_MASK: usize = 0b1;
// The max original capacity value. Any `Bytes` allocated with a greater initial
// capacity will default to this.
const MAX_ORIGINAL_CAPACITY_WIDTH: usize = 17;
// The original capacity algorithm will not take effect unless the originally
// allocated capacity was at least 1kb in size.
const MIN_ORIGINAL_CAPACITY_WIDTH: usize = 10;
// The original capacity is stored in powers of 2 starting at 1kb to a max of
// 64kb. Representing it as such requires only 3 bits of storage.
const ORIGINAL_CAPACITY_MASK: usize = 0b11100;
const ORIGINAL_CAPACITY_OFFSET: usize = 2;
// When the storage is in the `Vec` representation, the pointer can be advanced
// at most this value. This is due to the amount of storage available to track
// the offset is usize - number of KIND bits and number of ORIGINAL_CAPACITY
// bits.
const VEC_POS_OFFSET: usize = 5;
const MAX_VEC_POS: usize = usize::MAX >> VEC_POS_OFFSET;
const NOT_VEC_POS_MASK: usize = 0b11111;
#[cfg(target_pointer_width = "64")]
const PTR_WIDTH: usize = 64;
#[cfg(target_pointer_width = "32")]
const PTR_WIDTH: usize = 32;
/*
*
* ===== BytesMut =====
*
*/
impl BytesMut {
/// Creates a new `BytesMut` with the specified capacity.
///
/// The returned `BytesMut` will be able to hold at least `capacity` bytes
/// without reallocating. If `capacity` is under `4 * size_of::<usize>() - 1`,
/// then `BytesMut` will not allocate.
///
/// It is important to note that this function does not specify the length
/// of the returned `BytesMut`, but only the capacity.
///
/// # Examples
///
/// ```
/// use bytes::{BytesMut, BufMut};
///
/// let mut bytes = BytesMut::with_capacity(64);
///
/// // `bytes` contains no data, even though there is capacity
/// assert_eq!(bytes.len(), 0);
///
/// bytes.put(&b"hello world"[..]);
///
/// assert_eq!(&bytes[..], b"hello world");
/// ```
#[inline]
pub fn with_capacity(capacity: usize) -> BytesMut {
BytesMut::from_vec(Vec::with_capacity(capacity))
}
/// Creates a new `BytesMut` with default capacity.
///
/// Resulting object has length 0 and unspecified capacity.
/// This function does not allocate.
///
/// # Examples
///
/// ```
/// use bytes::{BytesMut, BufMut};
///
/// let mut bytes = BytesMut::new();
///
/// assert_eq!(0, bytes.len());
///
/// bytes.reserve(2);
/// bytes.put_slice(b"xy");
///
/// assert_eq!(&b"xy"[..], &bytes[..]);
/// ```
#[inline]
pub fn new() -> BytesMut {
BytesMut::with_capacity(0)
}
/// Returns the number of bytes contained in this `BytesMut`.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let b = BytesMut::from(&b"hello"[..]);
/// assert_eq!(b.len(), 5);
/// ```
#[inline]
pub fn len(&self) -> usize {
self.len
}
/// Returns true if the `BytesMut` has a length of 0.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let b = BytesMut::with_capacity(64);
/// assert!(b.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Returns the number of bytes the `BytesMut` can hold without reallocating.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let b = BytesMut::with_capacity(64);
/// assert_eq!(b.capacity(), 64);
/// ```
#[inline]
pub fn capacity(&self) -> usize {
self.cap
}
/// Converts `self` into an immutable `Bytes`.
///
/// The conversion is zero cost and is used to indicate that the slice
/// referenced by the handle will no longer be mutated. Once the conversion
/// is done, the handle can be cloned and shared across threads.
///
/// # Examples
///
/// ```
/// use bytes::{BytesMut, BufMut};
/// use std::thread;
///
/// let mut b = BytesMut::with_capacity(64);
/// b.put(&b"hello world"[..]);
/// let b1 = b.freeze();
/// let b2 = b1.clone();
///
/// let th = thread::spawn(move || {
/// assert_eq!(&b1[..], b"hello world");
/// });
///
/// assert_eq!(&b2[..], b"hello world");
/// th.join().unwrap();
/// ```
#[inline]
pub fn freeze(mut self) -> Bytes {
if self.kind() == KIND_VEC {
// Just re-use `Bytes` internal Vec vtable
unsafe {
let (off, _) = self.get_vec_pos();
let vec = rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off);
mem::forget(self);
vec.into()
}
} else {
debug_assert_eq!(self.kind(), KIND_ARC);
let ptr = self.ptr.as_ptr();
let len = self.len;
let data = AtomicPtr::new(self.data as _);
mem::forget(self);
unsafe {
Bytes::with_vtable(ptr, len, data, &SHARED_VTABLE)
}
}
}
/// Splits the bytes into two at the given index.
///
/// Afterwards `self` contains elements `[0, at)`, and the returned
/// `BytesMut` contains elements `[at, capacity)`.
///
/// This is an `O(1)` operation that just increases the reference count
/// and sets a few indices.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let mut a = BytesMut::from(&b"hello world"[..]);
/// let mut b = a.split_off(5);
///
/// a[0] = b'j';
/// b[0] = b'!';
///
/// assert_eq!(&a[..], b"jello");
/// assert_eq!(&b[..], b"!world");
/// ```
///
/// # Panics
///
/// Panics if `at > capacity`.
pub fn split_off(&mut self, at: usize) -> BytesMut {
assert!(at <= self.capacity());
unsafe {
let mut other = self.shallow_clone();
other.set_start(at);
self.set_end(at);
other
}
}
/// Removes the bytes from the current view, returning them in a new
/// `BytesMut` handle.
///
/// Afterwards, `self` will be empty, but will retain any additional
/// capacity that it had before the operation. This is identical to
/// `self.split_to(self.len())`.
///
/// This is an `O(1)` operation that just increases the reference count and
/// sets a few indices.
///
/// # Examples
///
/// ```
/// use bytes::{BytesMut, BufMut};
///
/// let mut buf = BytesMut::with_capacity(1024);
/// buf.put(&b"hello world"[..]);
///
/// let other = buf.split();
///
/// assert!(buf.is_empty());
/// assert_eq!(1013, buf.capacity());
///
/// assert_eq!(other, b"hello world"[..]);
/// ```
pub fn split(&mut self) -> BytesMut {
let len = self.len();
self.split_to(len)
}
/// Splits the buffer into two at the given index.
///
/// Afterwards `self` contains elements `[at, len)`, and the returned `BytesMut`
/// contains elements `[0, at)`.
///
/// This is an `O(1)` operation that just increases the reference count and
/// sets a few indices.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let mut a = BytesMut::from(&b"hello world"[..]);
/// let mut b = a.split_to(5);
///
/// a[0] = b'!';
/// b[0] = b'j';
///
/// assert_eq!(&a[..], b"!world");
/// assert_eq!(&b[..], b"jello");
/// ```
///
/// # Panics
///
/// Panics if `at > len`.
pub fn split_to(&mut self, at: usize) -> BytesMut {
assert!(at <= self.len());
unsafe {
let mut other = self.shallow_clone();
other.set_end(at);
self.set_start(at);
other
}
}
/// Shortens the buffer, keeping the first `len` bytes and dropping the
/// rest.
///
/// If `len` is greater than the buffer's current length, this has no
/// effect.
///
/// The [`split_off`] method can emulate `truncate`, but this causes the
/// excess bytes to be returned instead of dropped.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let mut buf = BytesMut::from(&b"hello world"[..]);
/// buf.truncate(5);
/// assert_eq!(buf, b"hello"[..]);
/// ```
///
/// [`split_off`]: #method.split_off
pub fn truncate(&mut self, len: usize) {
if len <= self.len() {
unsafe { self.set_len(len); }
}
}
/// Clears the buffer, removing all data.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let mut buf = BytesMut::from(&b"hello world"[..]);
/// buf.clear();
/// assert!(buf.is_empty());
/// ```
pub fn clear(&mut self) {
self.truncate(0);
}
/// Resizes the buffer so that `len` is equal to `new_len`.
///
/// If `new_len` is greater than `len`, the buffer is extended by the
/// difference with each additional byte set to `value`. If `new_len` is
/// less than `len`, the buffer is simply truncated.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let mut buf = BytesMut::new();
///
/// buf.resize(3, 0x1);
/// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);
///
/// buf.resize(2, 0x2);
/// assert_eq!(&buf[..], &[0x1, 0x1]);
///
/// buf.resize(4, 0x3);
/// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
/// ```
pub fn resize(&mut self, new_len: usize, value: u8) {
let len = self.len();
if new_len > len {
let additional = new_len - len;
self.reserve(additional);
unsafe {
let dst = self.bytes_mut().as_mut_ptr();
ptr::write_bytes(dst, value, additional);
self.set_len(new_len);
}
} else {
self.truncate(new_len);
}
}
/// Sets the length of the buffer.
///
/// This will explicitly set the size of the buffer without actually
/// modifying the data, so it is up to the caller to ensure that the data
/// has been initialized.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let mut b = BytesMut::from(&b"hello world"[..]);
///
/// unsafe {
/// b.set_len(5);
/// }
///
/// assert_eq!(&b[..], b"hello");
///
/// unsafe {
/// b.set_len(11);
/// }
///
/// assert_eq!(&b[..], b"hello world");
/// ```
pub unsafe fn set_len(&mut self, len: usize) {
debug_assert!(len <= self.cap);
self.len = len;
}
/// Reserves capacity for at least `additional` more bytes to be inserted
/// into the given `BytesMut`.
///
/// More than `additional` bytes may be reserved in order to avoid frequent
/// reallocations. A call to `reserve` may result in an allocation.
///
/// Before allocating new buffer space, the function will attempt to reclaim
/// space in the existing buffer. If the current handle references a small
/// view in the original buffer and all other handles have been dropped,
/// and the requested capacity is less than or equal to the existing
/// buffer's capacity, then the current view will be copied to the front of
/// the buffer and the handle will take ownership of the full buffer.
///
/// # Examples
///
/// In the following example, a new buffer is allocated.
///
/// ```
/// use bytes::BytesMut;
///
/// let mut buf = BytesMut::from(&b"hello"[..]);
/// buf.reserve(64);
/// assert!(buf.capacity() >= 69);
/// ```
///
/// In the following example, the existing buffer is reclaimed.
///
/// ```
/// use bytes::{BytesMut, BufMut};
///
/// let mut buf = BytesMut::with_capacity(128);
/// buf.put(&[0; 64][..]);
///
/// let ptr = buf.as_ptr();
/// let other = buf.split();
///
/// assert!(buf.is_empty());
/// assert_eq!(buf.capacity(), 64);
///
/// drop(other);
/// buf.reserve(128);
///
/// assert_eq!(buf.capacity(), 128);
/// assert_eq!(buf.as_ptr(), ptr);
/// ```
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
#[inline]
pub fn reserve(&mut self, additional: usize) {
let len = self.len();
let rem = self.capacity() - len;
if additional <= rem {
// The handle can already store at least `additional` more bytes, so
// there is no further work needed to be done.
return;
}
self.reserve_inner(additional);
}
// In separate function to allow the short-circuits in `reserve` to
// be inline-able. Significant helps performance.
fn reserve_inner(&mut self, additional: usize) {
let len = self.len();
let kind = self.kind();
if kind == KIND_VEC {
// If there's enough free space before the start of the buffer, then
// just copy the data backwards and reuse the already-allocated
// space.
//
// Otherwise, since backed by a vector, use `Vec::reserve`
unsafe {
let (off, prev) = self.get_vec_pos();
// Only reuse space if we stand to gain at least capacity/2
// bytes of space back
if off >= additional && off >= (self.cap / 2) {
// There's space - reuse it
//
// Just move the pointer back to the start after copying
// data back.
let base_ptr = self.ptr.as_ptr().offset(-(off as isize));
ptr::copy(self.ptr.as_ptr(), base_ptr, self.len);
self.ptr = vptr(base_ptr);
self.set_vec_pos(0, prev);
// Length stays constant, but since we moved backwards we
// can gain capacity back.
self.cap += off;
} else {
// No space - allocate more
let mut v = rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off);
v.reserve(additional);
// Update the info
self.ptr = vptr(v.as_mut_ptr().offset(off as isize));
self.len = v.len() - off;
self.cap = v.capacity() - off;
// Drop the vec reference
mem::forget(v);
}
return;
}
}
debug_assert_eq!(kind, KIND_ARC);
let shared: *mut Shared = self.data as _;
// Reserving involves abandoning the currently shared buffer and
// allocating a new vector with the requested capacity.
//
// Compute the new capacity
let mut new_cap = len + additional;
let original_capacity;
let original_capacity_repr;
unsafe {
original_capacity_repr = (*shared).original_capacity_repr;
original_capacity = original_capacity_from_repr(original_capacity_repr);
// First, try to reclaim the buffer. This is possible if the current
// handle is the only outstanding handle pointing to the buffer.
if (*shared).is_unique() {
// This is the only handle to the buffer. It can be reclaimed.
// However, before doing the work of copying data, check to make
// sure that the vector has enough capacity.
let v = &mut (*shared).vec;
if v.capacity() >= new_cap {
// The capacity is sufficient, reclaim the buffer
let ptr = v.as_mut_ptr();
ptr::copy(self.ptr.as_ptr(), ptr, len);
self.ptr = vptr(ptr);
self.cap = v.capacity();
return;
}
// The vector capacity is not sufficient. The reserve request is
// asking for more than the initial buffer capacity. Allocate more
// than requested if `new_cap` is not much bigger than the current
// capacity.
//
// There are some situations, using `reserve_exact` that the
// buffer capacity could be below `original_capacity`, so do a
// check.
new_cap = cmp::max(
cmp::max(v.capacity() << 1, new_cap),
original_capacity);
} else {
new_cap = cmp::max(new_cap, original_capacity);
}
}
// Create a new vector to store the data
let mut v = Vec::with_capacity(new_cap);
// Copy the bytes
v.extend_from_slice(self.as_ref());
// Release the shared handle. This must be done *after* the bytes are
// copied.
unsafe { release_shared(shared) };
// Update self
let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;
self.data = data as _;
self.ptr = vptr(v.as_mut_ptr());
self.len = v.len();
self.cap = v.capacity();
// Forget the vector handle
mem::forget(v);
}
/// Appends given bytes to this object.
///
/// If this `BytesMut` object has not enough capacity, it is resized first.
/// So unlike `put_slice` operation, `extend_from_slice` does not panic.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let mut buf = BytesMut::with_capacity(0);
/// buf.extend_from_slice(b"aaabbb");
/// buf.extend_from_slice(b"cccddd");
///
/// assert_eq!(b"aaabbbcccddd", &buf[..]);
/// ```
pub fn extend_from_slice(&mut self, extend: &[u8]) {
self.reserve(extend.len());
self.put_slice(extend);
}
/// Combine splitted BytesMut objects back as contiguous.
///
/// If `BytesMut` objects were not contiguous originally, they will be extended.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let mut buf = BytesMut::with_capacity(64);
/// buf.extend_from_slice(b"aaabbbcccddd");
///
/// let splitted = buf.split_off(6);
/// assert_eq!(b"aaabbb", &buf[..]);
/// assert_eq!(b"cccddd", &splitted[..]);
///
/// buf.unsplit(splitted);
/// assert_eq!(b"aaabbbcccddd", &buf[..]);
/// ```
pub fn unsplit(&mut self, other: BytesMut) {
if self.is_empty() {
*self = other;
return;
}
if let Err(other) = self.try_unsplit(other) {
self.extend_from_slice(other.as_ref());
}
}
// private
// For now, use a `Vec` to manage the memory for us, but we may want to
// change that in the future to some alternate allocator strategy.
//
// Thus, we don't expose an easy way to construct from a `Vec` since an
// internal change could make a simple pattern (`BytesMut::from(vec)`)
// suddenly a lot more expensive.
#[inline]
pub(crate) fn from_vec(mut vec: Vec<u8>) -> BytesMut {
let ptr = vptr(vec.as_mut_ptr());
let len = vec.len();
let cap = vec.capacity();
mem::forget(vec);
let original_capacity_repr = original_capacity_to_repr(cap);
let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;
BytesMut {
ptr,
len,
cap,
data: data as *mut _,
}
}
#[inline]
fn as_slice(&self) -> &[u8] {
unsafe {
slice::from_raw_parts(self.ptr.as_ptr(), self.len)
}
}
#[inline]
fn as_slice_mut(&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len)
}
}
unsafe fn set_start(&mut self, start: usize) {
// Setting the start to 0 is a no-op, so return early if this is the
// case.
if start == 0 {
return;
}
debug_assert!(start <= self.cap);
let kind = self.kind();
if kind == KIND_VEC {
// Setting the start when in vec representation is a little more
// complicated. First, we have to track how far ahead the
// "start" of the byte buffer from the beginning of the vec. We
// also have to ensure that we don't exceed the maximum shift.
let (mut pos, prev) = self.get_vec_pos();
pos += start;
if pos <= MAX_VEC_POS {
self.set_vec_pos(pos, prev);
} else {
// The repr must be upgraded to ARC. This will never happen
// on 64 bit systems and will only happen on 32 bit systems
// when shifting past 134,217,727 bytes. As such, we don't
// worry too much about performance here.
self.promote_to_shared(/*ref_count = */1);
}
}
// Updating the start of the view is setting `ptr` to point to the
// new start and updating the `len` field to reflect the new length
// of the view.
self.ptr = vptr(self.ptr.as_ptr().offset(start as isize));
if self.len >= start {
self.len -= start;
} else {
self.len = 0;
}
self.cap -= start;
}
unsafe fn set_end(&mut self, end: usize) {
debug_assert_eq!(self.kind(), KIND_ARC);
assert!(end <= self.cap);
self.cap = end;
self.len = cmp::min(self.len, end);
}
fn try_unsplit(&mut self, other: BytesMut) -> Result<(), BytesMut> {
if other.is_empty() {
return Ok(());
}
let ptr = unsafe { self.ptr.as_ptr().offset(self.len as isize) };
if ptr == other.ptr.as_ptr() &&
self.kind() == KIND_ARC &&
other.kind() == KIND_ARC &&
self.data == other.data
{
// Contiguous blocks, just combine directly
self.len += other.len;
self.cap += other.cap;
Ok(())
} else {
Err(other)
}
}
#[inline]
fn kind(&self) -> usize {
self.data as usize & KIND_MASK
}
unsafe fn promote_to_shared(&mut self, ref_cnt: usize) {
debug_assert_eq!(self.kind(), KIND_VEC);
debug_assert!(ref_cnt == 1 || ref_cnt == 2);
let original_capacity_repr =
(self.data as usize & ORIGINAL_CAPACITY_MASK) >> ORIGINAL_CAPACITY_OFFSET;
// The vec offset cannot be concurrently mutated, so there
// should be no danger reading it.
let off = (self.data as usize) >> VEC_POS_OFFSET;
// First, allocate a new `Shared` instance containing the
// `Vec` fields. It's important to note that `ptr`, `len`,
// and `cap` cannot be mutated without having `&mut self`.
// This means that these fields will not be concurrently
// updated and since the buffer hasn't been promoted to an
// `Arc`, those three fields still are the components of the
// vector.
let shared = Box::new(Shared {
vec: rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off),
original_capacity_repr,
ref_count: AtomicUsize::new(ref_cnt),
});
let shared = Box::into_raw(shared);
// The pointer should be aligned, so this assert should
// always succeed.
debug_assert_eq!(shared as usize & KIND_MASK, KIND_ARC);
self.data = shared as _;
}
/// Makes an exact shallow clone of `self`.
///
/// The kind of `self` doesn't matter, but this is unsafe
/// because the clone will have the same offsets. You must
/// be sure the returned value to the user doesn't allow
/// two views into the same range.
#[inline]
unsafe fn shallow_clone(&mut self) -> BytesMut {
if self.kind() == KIND_ARC {
increment_shared(self.data);
ptr::read(self)
} else {
self.promote_to_shared(/*ref_count = */2);
ptr::read(self)
}
}
#[inline]
unsafe fn get_vec_pos(&mut self) -> (usize, usize) {
debug_assert_eq!(self.kind(), KIND_VEC);
let prev = self.data as usize;
(prev >> VEC_POS_OFFSET, prev)
}
#[inline]
unsafe fn set_vec_pos(&mut self, pos: usize, prev: usize) {
debug_assert_eq!(self.kind(), KIND_VEC);
debug_assert!(pos <= MAX_VEC_POS);
self.data = ((pos << VEC_POS_OFFSET) | (prev & NOT_VEC_POS_MASK)) as *mut _;
}
}
impl Drop for BytesMut {
fn drop(&mut self) {
let kind = self.kind();
if kind == KIND_VEC {
unsafe {
let (off, _) = self.get_vec_pos();
// Vector storage, free the vector
let _ = rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off);
}
} else if kind == KIND_ARC {
unsafe { release_shared(self.data as _) };
}
}
}
impl Buf for BytesMut {
#[inline]
fn remaining(&self) -> usize {
self.len()
}
#[inline]
fn bytes(&self) -> &[u8] {
self.as_slice()
}
#[inline]
fn advance(&mut self, cnt: usize) {
assert!(cnt <= self.remaining(), "cannot advance past `remaining`");
unsafe { self.set_start(cnt); }
}
fn to_bytes(&mut self) -> crate::Bytes {
self.split().freeze()
}
}
impl BufMut for BytesMut {
#[inline]
fn remaining_mut(&self) -> usize {
usize::MAX - self.len()
}
#[inline]
unsafe fn advance_mut(&mut self, cnt: usize) {
let new_len = self.len() + cnt;
assert!(new_len <= self.cap, "new_len = {}; capacity = {}", new_len, self.cap);
self.len = new_len;
}
#[inline]
fn bytes_mut(&mut self) -> &mut [mem::MaybeUninit<u8>] {
if self.capacity() == self.len() {
self.reserve(64);
}
unsafe {
slice::from_raw_parts_mut(self.ptr.as_ptr().offset(self.len as isize) as *mut mem::MaybeUninit<u8>, self.cap - self.len)
}
}
}
impl AsRef<[u8]> for BytesMut {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_slice()
}
}
impl Deref for BytesMut {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
self.as_ref()
}
}
impl AsMut<[u8]> for BytesMut {
fn as_mut(&mut self) -> &mut [u8] {
self.as_slice_mut()
}
}
impl DerefMut for BytesMut {
#[inline]
fn deref_mut(&mut self) -> &mut [u8] {
self.as_mut()
}
}
impl<'a> From<&'a [u8]> for BytesMut {
fn from(src: &'a [u8]) -> BytesMut {
BytesMut::from_vec(src.to_vec())
}
}
impl<'a> From<&'a str> for BytesMut {
fn from(src: &'a str) -> BytesMut {
BytesMut::from(src.as_bytes())
}
}
impl PartialEq for BytesMut {
fn eq(&self, other: &BytesMut) -> bool {
self.as_slice() == other.as_slice()
}
}
impl PartialOrd for BytesMut {
fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
self.as_slice().partial_cmp(other.as_slice())
}
}