-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
125 lines (106 loc) · 2.35 KB
/
index.js
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
const TOS = require('time-ordered-set')
class Entry {
constructor (pool, key, val) {
this.pool = pool
this.prev = null
this.next = null
this.key = key
this.value = val
this.refs = 0
}
bump () {
if (this.refs > 0) return
this.pool.gcable.add(this)
this.pool._gcMaybe()
}
delete () {
this.pool.gcable.remove(this)
this.pool.entries.delete(this.key)
if (this.pool.close) this.pool.close(this.value)
}
increment () {
this.refs++
if (this.refs === 1) {
this.pool.gcable.remove(this)
}
this.pool._gcMaybe()
}
decrement () {
this.refs--
if (this.refs === 0) {
this.pool.gcable.add(this)
this.pool._gcMaybe()
}
this.pool._gcMaybe()
}
}
module.exports = class Pool {
constructor ({ maxSize = Infinity, close } = {}) {
this.maxSize = maxSize
this.close = close
this.gcable = new TOS()
this.entries = new Map()
}
get size () {
return this.entries.size
}
isFull () {
return this.entries.size < this.maxSize
}
entry (key) {
return this.entries.get(key)
}
get (key, bump = true) {
const entry = this.entry(key)
if (!entry) return
if (bump) entry.bump()
return entry.value
}
delete (key) {
const e = this.entry(key)
if (e) e.delete()
}
add (val, forceGC = false) {
return this.set(val, val, forceGC)
}
has (key) {
return this.entries.has(key)
}
set (key, val, forceGC = false) {
const existing = this.entries.get(key)
if (existing) {
existing.bump()
existing.value = val
return existing
}
const entry = new Entry(this, key, val)
this.gcable.add(entry)
this.entries.set(key, entry)
// allow gc list to grow by one if otherwise we could destroy ourself unless forceGC is set
this._gcMaybe(!forceGC)
return entry
}
gc () {
const oldest = this.gcable.oldest
if (!oldest) return null
oldest.delete()
return oldest.value
}
_gcMaybe (allowOne = false) {
if (this.gcable.length === 1 && allowOne) return
if (this.entries.size <= this.maxSize && this.close) return
this.gc()
}
increment (key) {
const e = this.entry(key)
if (e) e.increment()
}
decrement (key) {
const e = this.entry(key)
if (e) e.decrement()
}
bump (key) {
const e = this.entry(key)
if (e) e.bump()
}
}