@@ -11,7 +11,8 @@ use std::{mem::replace, ops::Deref, sync::Arc};
11
11
12
12
#[ derive( Debug ) ]
13
13
pub struct BufferPool {
14
- buffer_cap : usize ,
14
+ buffer_size_cap : usize ,
15
+ buffer_init_cap : usize ,
15
16
pool : ArrayQueue < Vec < u8 > > ,
16
17
}
17
18
@@ -22,25 +23,29 @@ impl BufferPool {
22
23
. and_then ( |x| x. parse ( ) . ok ( ) )
23
24
. unwrap_or ( 128_usize ) ;
24
25
25
- let buffer_cap = std:: env:: var ( "MYSQL_ASYNC_BUFFER_SIZE_CAP" )
26
+ let buffer_size_cap = std:: env:: var ( "MYSQL_ASYNC_BUFFER_SIZE_CAP" )
26
27
. ok ( )
27
28
. and_then ( |x| x. parse ( ) . ok ( ) )
28
29
. unwrap_or ( 4 * 1024 * 1024 ) ;
29
30
31
+ let buffer_init_cap = std:: env:: var ( "MYSQL_ASYNC_BUFFER_INIT_CAP" )
32
+ . ok ( )
33
+ . and_then ( |x| x. parse ( ) . ok ( ) )
34
+ . unwrap_or ( 0 ) ;
35
+
30
36
Self {
31
37
pool : ArrayQueue :: new ( pool_cap) ,
32
- buffer_cap,
38
+ buffer_size_cap,
39
+ buffer_init_cap,
33
40
}
34
41
}
35
42
36
43
pub fn get ( self : & Arc < Self > ) -> PooledBuf {
37
- let mut buf = self . pool . pop ( ) . unwrap_or_default ( ) ;
38
-
39
- // SAFETY:
40
- // 1. OK – 0 is always within capacity
41
- // 2. OK - nothing to initialize
42
- unsafe { buf. set_len ( 0 ) }
43
-
44
+ let buf = self
45
+ . pool
46
+ . pop ( )
47
+ . unwrap_or_else ( || Vec :: with_capacity ( self . buffer_init_cap ) ) ;
48
+ debug_assert_eq ! ( buf. len( ) , 0 ) ;
44
49
PooledBuf ( buf, self . clone ( ) )
45
50
}
46
51
@@ -51,15 +56,12 @@ impl BufferPool {
51
56
}
52
57
53
58
fn put ( self : & Arc < Self > , mut buf : Vec < u8 > ) {
54
- if buf. len ( ) > self . buffer_cap {
55
- // TODO: until `Vec::shrink_to` stabilization
56
-
57
- // SAFETY:
58
- // 1. OK – new_len <= capacity
59
- // 2. OK - 0..new_len is initialized
60
- unsafe { buf. set_len ( self . buffer_cap ) }
61
- buf. shrink_to_fit ( ) ;
62
- }
59
+ // SAFETY:
60
+ // 1. OK – 0 is always within capacity
61
+ // 2. OK - nothing to initialize
62
+ unsafe { buf. set_len ( 0 ) }
63
+
64
+ buf. shrink_to ( self . buffer_size_cap ) ;
63
65
64
66
// ArrayQueue will make sure to drop the buffer if capacity is exceeded
65
67
let _ = self . pool . push ( buf) ;
0 commit comments