@@ -34,9 +34,13 @@ use std::sync::Mutex;
34
34
/// A pool of byte slices, that reuses memory.
35
35
#[ derive( Debug ) ]
36
36
pub struct BytePool {
37
- list : Mutex < Vec < Vec < u8 > > > ,
37
+ list_large : Mutex < Vec < Vec < u8 > > > ,
38
+ list_small : Mutex < Vec < Vec < u8 > > > ,
38
39
}
39
40
41
+ /// The size at which point values are allocated in the small list, rather than the big.
42
+ const SPLIT_SIZE : usize = 4 * 1024 ;
43
+
40
44
/// The value returned by an allocation of the pool.
41
45
/// When it is dropped the memory gets returned into the pool, and is not zeroed.
42
46
/// If that is a concern, you must clear the data yourself.
@@ -54,7 +58,8 @@ impl fmt::Debug for Block<'_> {
54
58
impl Default for BytePool {
55
59
fn default ( ) -> Self {
56
60
BytePool {
57
- list : Mutex :: new ( Vec :: new ( ) ) ,
61
+ list_large : Mutex :: new ( Vec :: new ( ) ) ,
62
+ list_small : Mutex :: new ( Vec :: new ( ) ) ,
58
63
}
59
64
}
60
65
}
@@ -73,7 +78,11 @@ impl BytePool {
73
78
assert ! ( size > 0 , "Can not allocate empty blocks" ) ;
74
79
75
80
// check the last 4 blocks
76
- let mut lock = self . list . lock ( ) . unwrap ( ) ;
81
+ let mut lock = if size < SPLIT_SIZE {
82
+ self . list_small . lock ( ) . unwrap ( )
83
+ } else {
84
+ self . list_large . lock ( ) . unwrap ( )
85
+ } ;
77
86
let end = lock. len ( ) ;
78
87
let start = if end > 4 { end - 4 } else { 0 } ;
79
88
@@ -92,7 +101,11 @@ impl BytePool {
92
101
}
93
102
94
103
fn push_raw_block ( & self , block : Vec < u8 > ) {
95
- self . list . lock ( ) . unwrap ( ) . push ( block) ;
104
+ if block. capacity ( ) < SPLIT_SIZE {
105
+ self . list_small . lock ( ) . unwrap ( ) . push ( block) ;
106
+ } else {
107
+ self . list_large . lock ( ) . unwrap ( ) . push ( block) ;
108
+ }
96
109
}
97
110
}
98
111
@@ -228,6 +241,6 @@ mod tests {
228
241
h2. join ( ) . unwrap ( ) ;
229
242
230
243
// two threads allocating in parallel will need 2 buffers
231
- assert_eq ! ( pool. list . lock( ) . unwrap( ) . len( ) , 2 ) ;
244
+ assert_eq ! ( pool. list_small . lock( ) . unwrap( ) . len( ) , 2 ) ;
232
245
}
233
246
}
0 commit comments