Skip to content

Commit

Permalink
Additional checking for counters.
Browse files Browse the repository at this point in the history
This patch adds some additional checking for counters:

* Wrap counters around at 2^32.  Most graphing software (RRDtool etc.)
  can deal with this properly.  Unfortunately wrapping at 2^64 isn't
  possible because JS has a maximum integer resolution of 2^53.

* Don't allow counters to be decremented below 0.
  • Loading branch information
Michael S. Fischer committed Jul 6, 2011
1 parent f3b52cd commit 7af921b
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions metrics/counter.js
@@ -1,19 +1,31 @@
/*
* A simple counter object
*/

/* JavaScript uses double-precision FP for all numeric types.
* Perhaps someday we'll have native 64-bit integers that can safely be
* transported via JSON without additional code, but not today. */
var MAX_COUNTER_VALUE = Math.pow(2, 32); // 4294967296

var Counter = module.exports = function Counter() {
this.count = 0;
this.type = 'counter';
}

Counter.prototype.inc = function(val) {
if (!val) { val = 1; }
this.count += val;
if (this.count === MAX_COUNTER_VALUE) {
this.count = 0;
} else {
this.count += val;
}
}

Counter.prototype.dec = function(val) {
if (!val) { val = 1; }
this.count -= val;
if (this.count > 0) {
this.count -= val;
}
}

Counter.prototype.clear = function() {
Expand Down

0 comments on commit 7af921b

Please sign in to comment.