-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathbuffer.rs
More file actions
1334 lines (1178 loc) · 45.5 KB
/
buffer.rs
File metadata and controls
1334 lines (1178 loc) · 45.5 KB
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
//! Backing storage for [`IoBuf`] and [`super::IoBufMut`].
//!
//! This module contains the low-level allocation handles and the immutable and
//! mutable view types built on top of them:
//! - [`AlignedBuffer`] is self-contained: it carries its own [`Layout`] and
//! deallocates directly on drop.
//! - [`PooledBuffer`] is the raw pooled allocation handle: it carries only a
//! pointer and does not know its allocation layout.
//! - [`PooledBacking`] is the pooled ownership bundle outside the global
//! freelist: it pairs that handle with a [`SizeClassLease`] and slot id so the
//! buffer can return to its originating [`SizeClass`](super::pool::SizeClass).
//!
//! The allocator-facing pool logic lives in `pool.rs`. This module only deals
//! with backing ownership and view semantics.
use super::IoBuf;
use crate::iobuf::pool::{BufferPoolThreadCache, SizeClassLease};
use bytes::Bytes;
use std::{
alloc::{alloc, alloc_zeroed, dealloc, handle_alloc_error, Layout},
mem::ManuallyDrop,
ops::{Bound, RangeBounds},
ptr::NonNull,
sync::Arc,
};
/// A heap allocation with explicit alignment.
///
/// Owns an aligned region of memory allocated via the global allocator. This
/// handle is self-contained: it stores the [`Layout`] needed to deallocate the
/// region and releases the memory directly on drop.
///
/// This is the raw storage primitive used by untracked aligned buffers.
pub struct AlignedBuffer {
ptr: NonNull<u8>,
layout: Layout,
}
// SAFETY: `AlignedBuffer` represents a uniquely-owned heap allocation with no
// aliasing safe references. Sharing only exposes raw pointers or immutable
// slices through higher-level view types.
unsafe impl Send for AlignedBuffer {}
// SAFETY: see above.
unsafe impl Sync for AlignedBuffer {}
impl std::fmt::Debug for AlignedBuffer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AlignedBuffer")
.field("ptr", &self.ptr)
.field("capacity", &self.capacity())
.field("alignment", &self.layout.align())
.finish()
}
}
impl AlignedBuffer {
/// Creates a new uninitialized aligned buffer.
///
/// # Panics
///
/// Panics if:
/// - `capacity == 0`
/// - `alignment` is not a power of two
#[inline]
pub fn new(capacity: usize, alignment: usize) -> Self {
assert!(capacity > 0, "capacity must be greater than zero");
let layout =
Layout::from_size_align(capacity, alignment).expect("alignment is a power of two");
// SAFETY: layout is valid and non-zero sized.
let ptr = unsafe { alloc(layout) };
let ptr = NonNull::new(ptr).unwrap_or_else(|| handle_alloc_error(layout));
Self { ptr, layout }
}
/// Creates a new zero-initialized aligned buffer.
///
/// # Panics
///
/// Panics if:
/// - `capacity == 0`
/// - `alignment` is not a power of two
#[inline]
pub(crate) fn new_zeroed(capacity: usize, alignment: usize) -> Self {
assert!(capacity > 0, "capacity must be greater than zero");
let layout =
Layout::from_size_align(capacity, alignment).expect("alignment is a power of two");
// SAFETY: layout is valid and non-zero sized.
let ptr = unsafe { alloc_zeroed(layout) };
let ptr = NonNull::new(ptr).unwrap_or_else(|| handle_alloc_error(layout));
Self { ptr, layout }
}
#[inline(always)]
pub const fn capacity(&self) -> usize {
self.layout.size()
}
#[inline(always)]
pub const fn as_ptr(&self) -> *mut u8 {
self.ptr.as_ptr()
}
}
impl Drop for AlignedBuffer {
#[inline(always)]
fn drop(&mut self) {
// SAFETY: ptr/layout came from the global allocator and are unchanged.
unsafe { dealloc(self.ptr.as_ptr(), self.layout) };
}
}
/// A raw pooled allocation handle whose layout is stored by its size class.
///
/// Unlike [`AlignedBuffer`], this handle intentionally carries only the
/// allocation pointer. The size-class freelist stores the allocation layout, so
/// moving pooled buffers through pooled backing values and thread-local caches
/// does not need to move a per-buffer [`Layout`].
///
/// `PooledBuffer` does not implement [`Drop`] and does not retain its
/// originating [`SizeClass`](super::pool::SizeClass). In normal pool use,
/// [`PooledBacking`] owns it while it is outside the global freelist, and the
/// size-class [`super::freelist::Freelist`] owns it while it is globally free.
/// Only the freelist knows the layout needed to deallocate it.
///
/// Callers that take a `PooledBuffer` out of pool state must either return it to
/// the same originating size class or explicitly deallocate it with the exact
/// layout used to create it.
pub struct PooledBuffer {
ptr: NonNull<u8>,
}
// SAFETY: `PooledBuffer` represents a uniquely-owned heap allocation with no
// aliasing safe references. Sharing only exposes raw pointers or immutable
// slices through higher-level view types.
unsafe impl Send for PooledBuffer {}
// SAFETY: see above.
unsafe impl Sync for PooledBuffer {}
impl std::fmt::Debug for PooledBuffer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PooledBuffer")
.field("ptr", &self.ptr)
.finish()
}
}
impl PooledBuffer {
/// Creates a new uninitialized pooled buffer for `layout`.
///
/// # Panics
///
/// Panics if `layout` has zero size.
#[inline]
pub fn new(layout: Layout) -> Self {
assert!(layout.size() > 0, "layout size must be non-zero");
// SAFETY: layout is valid and non-zero sized.
let ptr = unsafe { alloc(layout) };
let ptr = NonNull::new(ptr).unwrap_or_else(|| handle_alloc_error(layout));
Self { ptr }
}
/// Creates a new zero-initialized pooled buffer for `layout`.
///
/// # Panics
///
/// Panics if `layout` has zero size.
#[inline]
pub fn new_zeroed(layout: Layout) -> Self {
assert!(layout.size() > 0, "layout size must be non-zero");
// SAFETY: layout is valid and non-zero sized.
let ptr = unsafe { alloc_zeroed(layout) };
let ptr = NonNull::new(ptr).unwrap_or_else(|| handle_alloc_error(layout));
Self { ptr }
}
/// Returns the allocation pointer.
#[inline(always)]
pub const fn as_ptr(&self) -> *mut u8 {
self.ptr.as_ptr()
}
/// Deallocates this pooled buffer.
///
/// # Safety
///
/// `layout` must exactly match the layout used to allocate this buffer.
#[inline(always)]
pub unsafe fn deallocate(self, layout: Layout) {
// SAFETY: guaranteed by the caller.
unsafe { dealloc(self.ptr.as_ptr(), layout) };
}
}
/// Owning allocation handle used by buffer views.
///
/// [`Buf`] and [`BufMut`] are generic over this trait so their view logic can
/// stay shared while each backing decides how the allocation is described and
/// released. Implementations must own exactly one allocation, report its full
/// capacity, expose its base pointer, and consume themselves in
/// [`Self::release`].
///
/// [`AlignedBuffer`] is self-contained and releases directly. [`PooledBacking`]
/// owns the layoutless [`PooledBuffer`] together with the [`SizeClassLease`] and
/// slot id needed to return that allocation to its size class.
pub(crate) trait BufferBacking: Send + Sync + 'static {
/// Returns the full allocation capacity, ignoring any view cursor/offset.
fn capacity(&self) -> usize;
/// Returns the base allocation pointer.
fn as_ptr(&self) -> *mut u8;
/// Consumes the backing and releases the allocation.
fn release(self);
}
impl BufferBacking for AlignedBuffer {
#[inline(always)]
fn capacity(&self) -> usize {
self.capacity()
}
#[inline(always)]
fn as_ptr(&self) -> *mut u8 {
self.as_ptr()
}
#[inline(always)]
fn release(self) {
drop(self);
}
}
/// Pooled backing storage outside the global freelist.
///
/// This is the ownership bundle for a pooled allocation outside the global
/// freelist. The [`PooledBuffer`] is the raw allocation pointer, `slot`
/// identifies that allocation within the originating size class, and
/// [`SizeClassLease`] owns the strong size-class reference needed to keep the
/// freelist and allocation layout alive.
///
/// Releasing this backing transfers the whole bundle to
/// [`BufferPoolThreadCache`]. The thread cache may keep the buffer locally, or
/// return it to the class-global freelist and release the lease.
pub(crate) struct PooledBacking {
buffer: PooledBuffer,
lease: SizeClassLease,
slot: u32,
}
impl BufferBacking for PooledBacking {
#[inline(always)]
fn capacity(&self) -> usize {
self.lease.size()
}
#[inline(always)]
fn as_ptr(&self) -> *mut u8 {
self.buffer.as_ptr()
}
#[inline(always)]
fn release(self) {
BufferPoolThreadCache::push(self.lease, self.slot, self.buffer);
}
}
/// Shared allocation with backing-specific release behavior.
///
/// This is the single ownership point for the underlying backing allocation.
/// Immutable views hold it behind an [`Arc`], while mutable views own it
/// directly and may later freeze it into an immutable shared view.
struct BufInner<B: BufferBacking> {
buffer: ManuallyDrop<B>,
}
impl<B: BufferBacking> BufInner<B> {
#[inline]
const fn new(buffer: B) -> Self {
Self {
buffer: ManuallyDrop::new(buffer),
}
}
#[inline]
fn capacity(&self) -> usize {
self.buffer.capacity()
}
}
impl<B: BufferBacking> Drop for BufInner<B> {
#[inline(always)]
fn drop(&mut self) {
// SAFETY: Drop is called at most once for this value.
let buffer = unsafe { ManuallyDrop::take(&mut self.buffer) };
buffer.release();
}
}
/// Immutable, reference-counted view over fixed-capacity backing storage.
///
/// Cloning is cheap and shares the same underlying aligned allocation.
///
/// The backing type decides what happens when the final reference is dropped:
/// untracked aligned buffers deallocate directly, while pooled buffers return
/// the allocation to their originating size class.
///
/// # View Layout
///
/// ```text
/// [0................offset...........offset+len...........capacity]
/// ^ ^ ^ ^
/// | | | |
/// allocation start first readable end of readable allocation end
/// byte of this view region for this view
/// ```
///
/// Regions:
/// - `[0..offset)`: not readable from this view
/// - `[offset..offset+len)`: readable bytes for this view
/// - `[offset+len..capacity)`: not readable from this view
///
/// # Invariants
///
/// - `offset <= capacity`
/// - `offset + len <= capacity`
///
/// This representation allows sliced views to preserve their current readable
/// window while still supporting `try_into_mut` when uniquely owned.
pub(crate) struct Buf<B: BufferBacking> {
inner: Arc<BufInner<B>>,
offset: usize,
len: usize,
}
impl<B: BufferBacking> Buf<B> {
/// Returns a pointer to the first readable byte.
#[inline]
pub(crate) fn as_ptr(&self) -> *const u8 {
// SAFETY: offset is always within the underlying allocation.
unsafe { self.inner.buffer.as_ptr().add(self.offset) }
}
/// Returns a slice of this view (zero-copy).
///
/// The range is resolved relative to this view's readable window
/// (`0..self.len`), not relative to the allocation start.
///
/// Returns `None` for empty ranges, allowing callers to detach from the
/// underlying allocation.
pub(crate) fn slice(&self, range: impl RangeBounds<usize>) -> Option<Self> {
let start = match range.start_bound() {
Bound::Included(&n) => n,
Bound::Excluded(&n) => n.checked_add(1).expect("range start overflow"),
Bound::Unbounded => 0,
};
let end = match range.end_bound() {
Bound::Included(&n) => n.checked_add(1).expect("range end overflow"),
Bound::Excluded(&n) => n,
Bound::Unbounded => self.len,
};
assert!(start <= end, "slice start must be <= end");
assert!(end <= self.len, "slice out of bounds");
if start == end {
return None;
}
Some(Self {
inner: Arc::clone(&self.inner),
offset: self.offset + start,
len: end - start,
})
}
/// Splits the buffer into two at the given index.
///
/// Afterwards `self` contains bytes `[at, len)`, and the returned buffer
/// contains bytes `[0, at)`.
///
/// This is an `O(1)` zero-copy operation.
///
/// # Panics
///
/// Panics if `at > len`.
#[inline]
pub(crate) fn split_to(&mut self, at: usize) -> Self {
assert!(
at <= self.len,
"split_to out of bounds: {:?} <= {:?}",
at,
self.len,
);
let prefix = Self {
inner: Arc::clone(&self.inner),
offset: self.offset,
len: at,
};
self.offset += at;
self.len -= at;
prefix
}
/// Try to recover mutable ownership without copying.
///
/// This succeeds only when this is the sole remaining reference to the
/// underlying allocation (`Arc` strong count is 1).
///
/// On success, the returned mutable buffer preserves the readable bytes and
/// mutable capacity from this view's current offset to the end of the
/// allocation. This means uniquely-owned sliced views can also be recovered
/// as mutable buffers while keeping the same readable window.
///
/// On failure, returns `self` unchanged.
pub(crate) fn try_into_mut(self) -> Result<BufMut<B>, Self> {
let Self { inner, offset, len } = self;
match Arc::try_unwrap(inner) {
Ok(inner) => Ok(BufMut {
inner: ManuallyDrop::new(inner),
cursor: offset,
len: offset.checked_add(len).expect("slice end overflow"),
}),
Err(inner) => Err(Self { inner, offset, len }),
}
}
/// Converts this view into [`Bytes`] without copying.
///
/// Empty views return detached [`Bytes::new`] so the underlying allocation
/// is not retained by an empty owner.
pub(crate) fn into_bytes(self) -> Bytes {
if self.len == 0 {
return Bytes::new();
}
Bytes::from_owner(self)
}
}
impl<B: BufferBacking> AsRef<[u8]> for Buf<B> {
#[inline]
fn as_ref(&self) -> &[u8] {
// SAFETY: offset/len are always bounded within the underlying allocation.
unsafe { std::slice::from_raw_parts(self.inner.buffer.as_ptr().add(self.offset), self.len) }
}
}
impl<B: BufferBacking> Clone for Buf<B> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
offset: self.offset,
len: self.len,
}
}
}
impl<B: BufferBacking> bytes::Buf for Buf<B> {
#[inline]
fn remaining(&self) -> usize {
self.len
}
#[inline]
fn chunk(&self) -> &[u8] {
self.as_ref()
}
#[inline]
fn advance(&mut self, cnt: usize) {
assert!(cnt <= self.len, "cannot advance past end of buffer");
self.offset += cnt;
self.len -= cnt;
}
#[inline]
fn copy_to_bytes(&mut self, len: usize) -> Bytes {
assert!(len <= self.len, "copy_to_bytes out of bounds");
if len == 0 {
return Bytes::new();
}
let slice = Self {
inner: Arc::clone(&self.inner),
offset: self.offset,
len,
};
self.advance(len);
slice.into_bytes()
}
}
/// Mutable fixed-capacity buffer view.
///
/// When dropped, the underlying buffer is released according to `B`: untracked
/// aligned buffers deallocate directly, while pooled buffers return to the
/// pool.
///
/// # Buffer Layout
///
/// ```text
/// [0................cursor..............len.............raw_capacity]
/// ^ ^ ^ ^
/// | | | |
/// allocation start read position write position allocation end
/// (consumed prefix) (initialized)
///
/// Regions:
/// - [0..cursor]: consumed (via [`bytes::Buf::advance`]), no longer accessible
/// - [cursor..len]: readable bytes (as_ref returns this slice)
/// - [len..raw_capacity): uninitialized, writable via [`bytes::BufMut`]
/// ```
///
/// # Invariants
///
/// - `cursor <= len <= raw_capacity`
/// - Bytes in `0..len` have been initialized (safe to read)
/// - Bytes in `len..raw_capacity` are uninitialized (write-only via [`bytes::BufMut`])
///
/// # Computed Values
///
/// - `len()` = readable bytes = `self.len - cursor`
/// - `capacity()` = view capacity = `raw_capacity - cursor` (shrinks after advance)
/// - `remaining_mut()` = writable bytes = `raw_capacity - self.len`
///
/// This matches [`bytes::BytesMut`] semantics.
///
/// # Fixed Capacity
///
/// Unlike [`bytes::BytesMut`], aligned buffers have fixed capacity and do not
/// grow automatically. Calling [`bytes::BufMut::put_slice`] or other
/// [`bytes::BufMut`] methods that would exceed capacity will panic (per the
/// [`bytes::BufMut`] trait contract).
pub(crate) struct BufMut<B: BufferBacking> {
inner: ManuallyDrop<BufInner<B>>,
/// Read cursor position (for `Buf` trait).
cursor: usize,
/// Number of bytes written (initialized).
len: usize,
}
impl<B: BufferBacking> BufMut<B> {
/// Capacity of the underlying allocation (ignoring cursor).
#[inline]
fn raw_capacity(&self) -> usize {
self.inner.capacity()
}
/// Converts this mutable buffer into a shared immutable view.
///
/// Wraps `self` in [`ManuallyDrop`] to suppress its `Drop` impl, then
/// moves the inner state into an `Arc`-backed [`Buf`]. The resulting
/// view covers only the current readable window (`cursor..len`).
fn into_shared(self) -> Buf<B> {
let mut me = ManuallyDrop::new(self);
// SAFETY: `me` is wrapped in `ManuallyDrop`, so its `Drop` impl will not run.
let inner = unsafe { ManuallyDrop::take(&mut me.inner) };
Buf {
inner: Arc::new(inner),
offset: me.cursor,
len: me.len - me.cursor,
}
}
/// Returns the number of readable bytes remaining in the buffer.
///
/// This is `len - cursor`, matching [`bytes::BytesMut`] semantics.
#[inline]
pub const fn len(&self) -> usize {
self.len - self.cursor
}
/// Returns true if no readable bytes remain.
#[inline]
pub const fn is_empty(&self) -> bool {
self.cursor == self.len
}
/// Returns the number of bytes the buffer can hold without reallocating.
#[inline]
pub fn capacity(&self) -> usize {
self.inner.capacity() - self.cursor
}
/// Returns an unsafe mutable pointer to the buffer's data.
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut u8 {
// SAFETY: cursor is always <= raw capacity.
unsafe { self.inner.buffer.as_ptr().add(self.cursor) }
}
/// Sets the length of the buffer (view-relative).
///
/// 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.
///
/// The `len` parameter is relative to the current view (after any `advance`
/// calls), matching [`bytes::BytesMut::set_len`] semantics.
///
/// # Safety
///
/// Caller must ensure:
/// - All bytes in the range `[cursor, cursor + len)` are initialized
/// - `len <= capacity()` (where capacity is view-relative)
#[inline]
pub const unsafe fn set_len(&mut self, len: usize) {
self.len = self.cursor + len;
}
/// Clears the buffer, removing all data. Existing capacity is preserved.
#[inline]
pub const fn clear(&mut self) {
self.len = self.cursor;
}
/// Truncates the buffer to at most `len` readable bytes.
///
/// If `len` is greater than the current readable length, this has no effect.
/// This operates on readable bytes (after cursor), matching
/// [`bytes::BytesMut::truncate`] semantics for buffers that have been advanced.
#[inline]
pub const fn truncate(&mut self, len: usize) {
if len < self.len() {
self.len = self.cursor + len;
}
}
/// Converts the current readable window into [`Bytes`] without copying.
///
/// Empty buffers return detached [`Bytes::new`] so aligned memory is not
/// retained by an empty owner.
pub fn into_bytes(self) -> Bytes {
if self.is_empty() {
return Bytes::new();
}
Bytes::from_owner(self.into_shared())
}
}
impl<B: BufferBacking> AsRef<[u8]> for BufMut<B> {
#[inline]
fn as_ref(&self) -> &[u8] {
// SAFETY: bytes from cursor..len have been initialized.
unsafe {
std::slice::from_raw_parts(self.inner.buffer.as_ptr().add(self.cursor), self.len())
}
}
}
impl<B: BufferBacking> AsMut<[u8]> for BufMut<B> {
#[inline]
fn as_mut(&mut self) -> &mut [u8] {
let len = self.len();
// SAFETY: bytes from cursor..len have been initialized.
unsafe { std::slice::from_raw_parts_mut(self.inner.buffer.as_ptr().add(self.cursor), len) }
}
}
impl<B: BufferBacking> Drop for BufMut<B> {
#[inline(always)]
fn drop(&mut self) {
// SAFETY: Drop is only called once. freeze() wraps self in ManuallyDrop
// to prevent this Drop impl from running after ownership is transferred.
unsafe { ManuallyDrop::drop(&mut self.inner) };
}
}
impl<B: BufferBacking> bytes::Buf for BufMut<B> {
#[inline]
fn remaining(&self) -> usize {
self.len - self.cursor
}
#[inline]
fn chunk(&self) -> &[u8] {
self.as_ref()
}
#[inline]
fn advance(&mut self, cnt: usize) {
let remaining = self.len - self.cursor;
assert!(cnt <= remaining, "cannot advance past end of buffer");
self.cursor += cnt;
}
}
// SAFETY: `BufMut` exposes the uninitialized tail `[len..raw_capacity)` and
// only advances within the underlying allocation bounds.
unsafe impl<B: BufferBacking> bytes::BufMut for BufMut<B> {
#[inline]
fn remaining_mut(&self) -> usize {
self.raw_capacity() - self.len
}
#[inline]
unsafe fn advance_mut(&mut self, cnt: usize) {
assert!(
cnt <= self.remaining_mut(),
"cannot advance past end of buffer"
);
self.len += cnt;
}
#[inline]
fn chunk_mut(&mut self) -> &mut bytes::buf::UninitSlice {
let raw_cap = self.raw_capacity();
let len = self.len;
// SAFETY: We have exclusive access and the slice is within raw capacity.
unsafe {
let ptr = self.inner.buffer.as_ptr().add(len);
bytes::buf::UninitSlice::from_raw_parts_mut(ptr, raw_cap - len)
}
}
}
/// Immutable, reference-counted view over an untracked aligned allocation.
///
/// The final reference deallocates the underlying aligned buffer directly.
pub(crate) type AlignedBuf = Buf<AlignedBuffer>;
/// Immutable, reference-counted view over a pooled allocation.
///
/// The final reference releases its [`PooledBacking`], returning the allocation
/// to its originating [`SizeClass`](super::pool::SizeClass). See [`Buf`] for
/// the shared immutable view layout and invariants.
pub(crate) type PooledBuf = Buf<PooledBacking>;
/// Mutable view over an untracked aligned allocation.
///
/// When dropped, the underlying aligned allocation is deallocated directly.
/// See [`BufMut`] for the shared mutable layout and invariants.
pub(crate) type AlignedBufMut = BufMut<AlignedBuffer>;
/// Mutable view over a pooled allocation.
///
/// When dropped, this releases its [`PooledBacking`], returning the allocation
/// to its originating [`SizeClass`](super::pool::SizeClass). See [`BufMut`] for
/// the shared mutable layout and invariants.
pub(crate) type PooledBufMut = BufMut<PooledBacking>;
impl std::fmt::Debug for Buf<AlignedBuffer> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AlignedBuf")
.field("offset", &self.offset)
.field("len", &self.len)
.field("capacity", &self.inner.capacity())
.finish()
}
}
impl std::fmt::Debug for Buf<PooledBacking> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PooledBuf")
.field("offset", &self.offset)
.field("len", &self.len)
.field("capacity", &self.inner.capacity())
.finish()
}
}
impl std::fmt::Debug for BufMut<AlignedBuffer> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AlignedBufMut")
.field("cursor", &self.cursor)
.field("len", &self.len)
.field("capacity", &self.capacity())
.finish()
}
}
impl BufMut<AlignedBuffer> {
#[inline]
pub(crate) const fn new(buffer: AlignedBuffer) -> Self {
Self {
inner: ManuallyDrop::new(BufInner::new(buffer)),
cursor: 0,
len: 0,
}
}
pub(crate) fn into_aligned(self) -> AlignedBuf {
self.into_shared()
}
pub fn freeze(self) -> IoBuf {
IoBuf::from_aligned(self.into_aligned())
}
}
impl std::fmt::Debug for BufMut<PooledBacking> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PooledBufMut")
.field("cursor", &self.cursor)
.field("len", &self.len)
.field("capacity", &self.capacity())
.finish()
}
}
impl BufMut<PooledBacking> {
#[inline]
pub(crate) const fn new(buffer: PooledBuffer, lease: SizeClassLease, slot: u32) -> Self {
Self {
inner: ManuallyDrop::new(BufInner::new(PooledBacking {
buffer,
lease,
slot,
})),
cursor: 0,
len: 0,
}
}
/// Convert into an immutable pooled view over the current readable window.
pub(crate) fn into_pooled(self) -> PooledBuf {
self.into_shared()
}
/// Freezes the buffer into an immutable [`IoBuf`].
///
/// Only the readable portion (`cursor..len`) is included in the result.
/// The underlying buffer will be returned to the pool when all references
/// to the [`IoBuf`] (including slices) are dropped.
pub fn freeze(self) -> IoBuf {
IoBuf::from_pooled(self.into_pooled())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
iobuf::{
cache_line_size, page_size, pool::BufferPoolThreadCacheConfig, BufferPool,
BufferPoolConfig,
},
telemetry::metrics::Registry,
};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use commonware_utils::{NZUsize, NZU32};
use std::ops::Bound;
fn test_pool(config: BufferPoolConfig) -> BufferPool {
let mut registry = Registry::default();
BufferPool::new(config, &mut registry)
}
fn test_config(min_size: usize, max_size: usize, max_per_class: u32) -> BufferPoolConfig {
BufferPoolConfig {
pool_min_size: 0,
min_size: NZUsize!(min_size),
max_size: NZUsize!(max_size),
max_per_class: NZU32!(max_per_class),
parallelism: NZUsize!(1),
thread_cache_config: BufferPoolThreadCacheConfig::Enabled(None),
prefill: false,
alignment: NZUsize!(page_size()),
}
}
#[test]
fn test_aligned_buffer() {
// Page-aligned allocation should report correct capacity and alignment.
let page = page_size();
let buf = AlignedBuffer::new(4096, page);
assert_eq!(buf.capacity(), 4096);
assert!((buf.as_ptr() as usize).is_multiple_of(page));
// Cache-line-aligned allocation should also satisfy its alignment.
let cache_line = cache_line_size();
let buf2 = AlignedBuffer::new(4096, cache_line);
assert_eq!(buf2.capacity(), 4096);
assert!((buf2.as_ptr() as usize).is_multiple_of(cache_line));
}
#[test]
#[should_panic(expected = "capacity must be greater than zero")]
fn test_aligned_buffer_zero_capacity_panics() {
let _ = AlignedBuffer::new(0, page_size());
}
#[test]
#[should_panic(expected = "capacity must be greater than zero")]
fn test_aligned_buffer_zeroed_zero_capacity_panics() {
let _ = AlignedBuffer::new_zeroed(0, page_size());
}
#[test]
fn test_untracked_aligned_debug_and_view_paths() {
let page = page_size();
// Cover debug formatting for the raw aligned owner.
let buffer = AlignedBuffer::new(16, page);
let buffer_debug = format!("{buffer:?}");
assert!(buffer_debug.contains("AlignedBuffer"));
assert!(buffer_debug.contains("capacity"));
// Exercise the mutable aligned wrapper through Buf/BufMut-style access.
let mut aligned_mut = AlignedBufMut::new(buffer);
let aligned_mut_debug = format!("{aligned_mut:?}");
assert!(aligned_mut_debug.contains("AlignedBufMut"));
assert!(aligned_mut.is_empty());
aligned_mut.put_slice(b"abcdefgh");
assert_eq!(aligned_mut.as_mut(), b"abcdefgh");
assert_eq!(Buf::remaining(&aligned_mut), 8);
assert_eq!(Buf::chunk(&aligned_mut), b"abcdefgh");
Buf::advance(&mut aligned_mut, 2);
assert_eq!(aligned_mut.as_mut_ptr() as usize % page, 2);
assert_eq!(Buf::chunk(&aligned_mut), b"cdefgh");
let prefix = Buf::copy_to_bytes(&mut aligned_mut, 2);
assert_eq!(prefix.as_ref(), b"cd");
assert_eq!(Buf::chunk(&aligned_mut), b"efgh");
aligned_mut.clear();
assert!(aligned_mut.is_empty());
aligned_mut.put_slice(b"wxyz");
// Empty aligned owners should detach into empty Bytes cleanly.
let empty_bytes = AlignedBufMut::new(AlignedBuffer::new(8, page)).into_bytes();
assert!(empty_bytes.is_empty());
let empty_bytes = AlignedBufMut::new(AlignedBuffer::new(8, page))
.into_aligned()
.into_bytes();
assert!(empty_bytes.is_empty());
// Non-empty mutable owners should hand their readable window to Bytes
// without copying.
let mut bytes_mut_source = AlignedBufMut::new(AlignedBuffer::new(8, page));
bytes_mut_source.put_slice(b"data");
let owned_bytes = bytes_mut_source.into_bytes();
assert_eq!(owned_bytes.as_ref(), b"data");
// Cover immutable debug/view/slice paths on the aligned wrapper.
let mut aligned = aligned_mut.into_aligned();
let aligned_debug = format!("{aligned:?}");
assert!(aligned_debug.contains("AlignedBuf"));
assert_eq!(aligned.as_ptr(), aligned.as_ref().as_ptr());
assert_eq!(aligned.as_ref(), b"wxyz");
assert_eq!(aligned.slice(..2).unwrap().as_ref(), b"wx");
assert_eq!(aligned.slice(..=2).unwrap().as_ref(), b"wxy");
assert_eq!(aligned.slice(1..).unwrap().as_ref(), b"xyz");
assert_eq!(aligned.slice(1..=2).unwrap().as_ref(), b"xy");
assert_eq!(
aligned
.slice((Bound::Included(1), Bound::Excluded(3)))
.unwrap()
.as_ref(),
b"xy"
);
let mut split = aligned.clone();
let split_prefix = split.split_to(2);
assert_eq!(split_prefix.as_ref(), b"wx");
assert_eq!(split.as_ref(), b"yz");
let head = Buf::copy_to_bytes(&mut aligned, 1);
assert_eq!(head.as_ref(), b"w");
let tail = Buf::copy_to_bytes(&mut aligned, 3);
assert_eq!(tail.as_ref(), b"xyz");
assert_eq!(Buf::remaining(&aligned), 0);
// Unique aligned owners can recover mutability without copying.
let mut unique_source = AlignedBufMut::new(AlignedBuffer::new(8, page));
unique_source.put_slice(b"qrst");
let unique = unique_source.into_aligned();
let recovered = unique
.try_into_mut()
.expect("unique aligned buffer should recover mutability");
assert_eq!(recovered.as_ref(), b"qrst");
// Shared aligned owners must refuse the mutable conversion.
let mut shared_source = AlignedBufMut::new(AlignedBuffer::new(8, page));
shared_source.put_slice(b"uvwx");
let shared = shared_source.into_aligned();
let _clone = shared.clone();
assert!(shared.try_into_mut().is_err());
// Fully draining a unique aligned owner should hand back owned Bytes.
let mut bytes_source = AlignedBufMut::new(AlignedBuffer::new(8, page));
bytes_source.put_slice(b"lmno");
let owned_bytes = bytes_source.into_aligned().into_bytes();
assert_eq!(owned_bytes.as_ref(), b"lmno");
}
#[test]
fn test_pooled_buf_mut_freeze() {
// Freeze a pooled mutable buffer and verify content is preserved in the
// resulting immutable view, including slices.
let page = page_size();
let pool = test_pool(test_config(page, page, 2));
// Write data into a pooled buffer.
let mut buf = pool.try_alloc(11).unwrap();
buf.put_slice(&[0u8; 11]);
assert_eq!(buf.len(), 11);
buf.as_mut()[..5].copy_from_slice(&[1, 2, 3, 4, 5]);