2016-02-21 00:57:38 +00:00
|
|
|
/* jslint node: true */
|
|
|
|
'use strict';
|
|
|
|
|
|
|
|
let _ = require('lodash');
|
|
|
|
|
|
|
|
// FNV-1a based on work here: https://github.com/wiedi/node-fnv
|
|
|
|
module.exports = class FNV1a {
|
|
|
|
constructor(data) {
|
|
|
|
this.hash = 0x811c9dc5;
|
2018-01-15 19:22:11 +00:00
|
|
|
|
2016-02-21 00:57:38 +00:00
|
|
|
if(!_.isUndefined(data)) {
|
|
|
|
this.update(data);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
update(data) {
|
|
|
|
if(_.isNumber(data)) {
|
|
|
|
data = data.toString();
|
|
|
|
}
|
2018-01-15 19:22:11 +00:00
|
|
|
|
2016-02-21 00:57:38 +00:00
|
|
|
if(_.isString(data)) {
|
2018-04-28 12:59:07 +00:00
|
|
|
data = Buffer.from(data);
|
2016-02-21 00:57:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if(!Buffer.isBuffer(data)) {
|
|
|
|
throw new Error('data must be String or Buffer!');
|
|
|
|
}
|
|
|
|
|
|
|
|
for(let b of data) {
|
|
|
|
this.hash = this.hash ^ b;
|
2018-01-15 19:22:11 +00:00
|
|
|
this.hash +=
|
|
|
|
(this.hash << 24) + (this.hash << 8) + (this.hash << 7) +
|
2016-02-21 00:57:38 +00:00
|
|
|
(this.hash << 4) + (this.hash << 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
digest(encoding) {
|
|
|
|
encoding = encoding || 'binary';
|
2018-04-28 12:59:07 +00:00
|
|
|
let buf = Buffer.alloc(4);
|
2016-02-21 00:57:38 +00:00
|
|
|
buf.writeInt32BE(this.hash & 0xffffffff, 0);
|
|
|
|
return buf.toString(encoding);
|
|
|
|
}
|
|
|
|
|
|
|
|
get value() {
|
|
|
|
return this.hash & 0xffffffff;
|
|
|
|
}
|
2018-01-15 19:22:11 +00:00
|
|
|
};
|
2016-02-21 00:57:38 +00:00
|
|
|
|