/
IDProvider.js
67 lines (63 loc) · 1.65 KB
/
IDProvider.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
function IDProvider() {
this._free=[{from: 0, to: NaN}];
}
/**
* Allocates a new ID number to use.
* @author fw@hardijzer.nl
* @return The lowest un-used ID number
*/
IDProvider.prototype.alloc=function() {
var first=this._free[0];
if (first.from==first.to) {
//Discard range
this._free.shift();
return first.from;
}
return first.from++;
}
/**
* Free an allocated ID for re-use.
* @author fw@hardijzer.nl
* @param {id} ID number to free.
*/
IDProvider.prototype.free=function(id) {
//Binary search
var left=0;
var right=this._free.length;
while (right>left) {
var mid=Math.floor((left+right)/2);
var current=this._free[mid];
if (current.from>id) right=mid;
else if (current.to<id) left=mid+1;
else
throw new Error("ID was already de-allocated");
}
//both left and right now contain the range just past our id.
//Set left to point to the one before, keep right just past
left--;
var mergeleft=(left>=0 && this._free[left].to==id-1);
var mergeright=(right<this._free.length && this._free[right].from==id+1);
if (mergeleft && mergeright) {
//Merge two ranges into one new range
this._free[left].to=this._free[right].to;
this._free.splice(right,1);
} else if (mergeleft) {
this._free[left].to=id;
} else if (mergeright) {
this._free[right].from=id;
} else {
//Create new range inbetween
this._free.splice(right,0,{from:id,to:id});
}
}
IDProvider.prototype.used=function() {
var total=0;
var last=0;
for (var i=0; i<this._free.length; i++) {
var cur=this._free[i];
total+=cur.from - last;
last=cur.to+1;
}
return total;
}
exports.IDProvider=IDProvider;