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