@@ -20,6 +20,31 @@ const RDONLY = constants.O_RDONLY
20
20
const WRONLY = constants . O_WRONLY
21
21
const CREAT = constants . O_CREAT
22
22
23
+ class Pool {
24
+ constructor ( maxSize ) {
25
+ this . maxSize = maxSize
26
+ this . active = [ ]
27
+ }
28
+
29
+ _onactive ( file ) {
30
+ // suspend a random one when the pool
31
+ if ( this . active . length >= this . maxSize ) {
32
+ const r = Math . floor ( Math . random ( ) * this . active . length )
33
+ this . active [ r ] . suspend ( )
34
+ }
35
+
36
+ file . _pi = this . active . push ( file ) - 1
37
+ }
38
+
39
+ _oninactive ( file ) {
40
+ const head = this . active . pop ( )
41
+ if ( head !== file ) {
42
+ head . _pi = file . _pi
43
+ this . active [ head . _pi ] = head
44
+ }
45
+ }
46
+ }
47
+
23
48
module . exports = class RandomAccessFile extends RandomAccessStorage {
24
49
constructor ( filename , opts = { } ) {
25
50
const size = opts . size || ( opts . truncate ? 0 : - 1 )
@@ -39,6 +64,8 @@ module.exports = class RandomAccessFile extends RandomAccessStorage {
39
64
40
65
this . mode = readable && writable ? RDWR : ( readable ? RDONLY : WRONLY )
41
66
67
+ this . _pi = 0 // pool index
68
+ this . _pool = opts . pool || null
42
69
this . _size = size
43
70
this . _rmdir = ! ! opts . rmdir
44
71
this . _lock = opts . lock === true
@@ -47,6 +74,10 @@ module.exports = class RandomAccessFile extends RandomAccessStorage {
47
74
this . _alwaysCreate = size >= 0
48
75
}
49
76
77
+ static createPool ( maxSize ) {
78
+ return new Pool ( maxSize )
79
+ }
80
+
50
81
_open ( req ) {
51
82
const create = this . _alwaysCreate || this . writing // .writing comes from RAS
52
83
const self = this
@@ -92,7 +123,7 @@ module.exports = class RandomAccessFile extends RandomAccessStorage {
92
123
93
124
function ontruncate ( err ) {
94
125
if ( err ) return onerrorafteropen ( err )
95
-
126
+ if ( self . _pool !== null ) self . _pool . _onactive ( self )
96
127
req . callback ( null )
97
128
}
98
129
@@ -180,6 +211,7 @@ module.exports = class RandomAccessFile extends RandomAccessStorage {
180
211
181
212
function onclose ( err ) {
182
213
if ( err ) return req . callback ( err )
214
+ if ( self . _pool !== null ) self . _pool . _oninactive ( self )
183
215
self . fd = 0
184
216
req . callback ( null )
185
217
}
0 commit comments