Permalink
Browse files

Added actual library

  • Loading branch information...
1 parent 01fb473 commit 0f60dfcf4e723a0108ebbae21526fadbc398f045 @Frans-Willem committed Jul 28, 2010
Showing with 682 additions and 0 deletions.
  1. +67 −0 IDProvider.js
  2. +615 −0 IPCNode.js
View
@@ -0,0 +1,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;
Oops, something went wrong.

0 comments on commit 0f60dfc

Please sign in to comment.