@@ -14,17 +14,23 @@ pub struct BytesSlab {
1414 stash : Vec < BytesMut > , // reclaimed and reusable buffers.
1515 shift : usize , // current buffer allocation size.
1616 valid : usize , // buffer[..valid] are valid bytes.
17- new_bytes : BytesRefill , // function to allocate new buffers.
17+ new_bytes : BytesRefill , // function to allocate new buffers.
1818}
1919
20- /// A function to allocate a new buffer of at least `usize` bytes.
21- pub type BytesRefill = std:: sync:: Arc < dyn Fn ( usize ) -> Box < dyn DerefMut < Target =[ u8 ] > > +Send +Sync > ;
20+ /// Ability to acquire and policy to retain byte buffers.
21+ #[ derive( Clone ) ]
22+ pub struct BytesRefill {
23+ /// Logic to acquire a new buffer of a certain number of bytes.
24+ pub logic : std:: sync:: Arc < dyn Fn ( usize ) -> Box < dyn DerefMut < Target =[ u8 ] > > +Send +Sync > ,
25+ /// An optional limit on the number of empty buffers retained.
26+ pub limit : Option < usize > ,
27+ }
2228
2329impl BytesSlab {
2430 /// Allocates a new `BytesSlab` with an initial size determined by a shift.
2531 pub fn new ( shift : usize , new_bytes : BytesRefill ) -> Self {
2632 BytesSlab {
27- buffer : BytesMut :: from ( BoxDerefMut { boxed : new_bytes ( 1 << shift) } ) ,
33+ buffer : BytesMut :: from ( BoxDerefMut { boxed : ( new_bytes. logic ) ( 1 << shift) } ) ,
2834 in_progress : Vec :: new ( ) ,
2935 stash : Vec :: new ( ) ,
3036 shift,
@@ -88,9 +94,13 @@ impl BytesSlab {
8894 self . in_progress . retain ( |x| x. is_some ( ) ) ;
8995 }
9096
91- let new_buffer = self . stash . pop ( ) . unwrap_or_else ( || BytesMut :: from ( BoxDerefMut { boxed : ( self . new_bytes ) ( 1 << self . shift ) } ) ) ;
97+ let new_buffer = self . stash . pop ( ) . unwrap_or_else ( || BytesMut :: from ( BoxDerefMut { boxed : ( self . new_bytes . logic ) ( 1 << self . shift ) } ) ) ;
9298 let old_buffer = :: std:: mem:: replace ( & mut self . buffer , new_buffer) ;
9399
100+ if let Some ( limit) = self . new_bytes . limit {
101+ self . stash . truncate ( limit) ;
102+ }
103+
94104 self . buffer [ .. self . valid ] . copy_from_slice ( & old_buffer[ .. self . valid ] ) ;
95105 if !increased_shift {
96106 self . in_progress . push ( Some ( old_buffer) ) ;
0 commit comments