2017-11-23 17:59:29 +08:00
|
|
|
/*
|
|
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
|
|
Author Tobias Koppers @sokra
|
|
|
|
*/
|
|
|
|
"use strict";
|
|
|
|
|
2017-11-23 18:44:56 +08:00
|
|
|
const BULK_SIZE = 1000;
|
2017-11-23 17:59:29 +08:00
|
|
|
|
|
|
|
class BulkUpdateDecorator {
|
|
|
|
constructor(hash) {
|
|
|
|
this.hash = hash;
|
|
|
|
this.buffer = "";
|
|
|
|
}
|
|
|
|
|
|
|
|
update(data, inputEncoding) {
|
|
|
|
if(inputEncoding !== undefined || typeof data !== "string" || data.length > BULK_SIZE) {
|
2017-11-23 18:44:56 +08:00
|
|
|
if(this.buffer.length > 0) {
|
|
|
|
this.hash.update(this.buffer);
|
|
|
|
this.buffer = "";
|
|
|
|
}
|
2017-11-23 17:59:29 +08:00
|
|
|
this.hash.update(data, inputEncoding);
|
|
|
|
} else {
|
|
|
|
this.buffer += data;
|
|
|
|
if(this.buffer.length > BULK_SIZE) {
|
2017-11-23 18:44:56 +08:00
|
|
|
this.hash.update(this.buffer);
|
|
|
|
this.buffer = "";
|
2017-11-23 17:59:29 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
digest(encoding) {
|
2017-11-23 18:44:56 +08:00
|
|
|
if(this.buffer.length > 0) {
|
|
|
|
this.hash.update(this.buffer);
|
|
|
|
}
|
2017-12-20 18:29:00 +08:00
|
|
|
var digestResult = this.hash.digest(encoding);
|
2017-12-20 20:30:36 +08:00
|
|
|
return typeof digestResult === "string" ? digestResult : digestResult.toString();
|
2017-11-23 17:59:29 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-21 18:12:36 +08:00
|
|
|
/* istanbul ignore next */
|
2018-01-20 00:06:59 +08:00
|
|
|
class DebugHash {
|
|
|
|
constructor() {
|
2018-01-20 18:28:45 +08:00
|
|
|
this.string = "";
|
2018-01-20 00:06:59 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
update(data, inputEncoding) {
|
|
|
|
if(typeof data !== "string") data = data.toString("utf-8");
|
|
|
|
this.string += data;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
digest(encoding) {
|
|
|
|
return this.string.replace(/[^a-z0-9]+/gi, m => Buffer.from(m).toString("hex"));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-23 17:59:29 +08:00
|
|
|
module.exports = algorithm => {
|
2017-12-17 23:52:56 +08:00
|
|
|
if(typeof algorithm === "function") {
|
|
|
|
return new BulkUpdateDecorator(new algorithm());
|
|
|
|
}
|
2017-11-23 17:59:29 +08:00
|
|
|
switch(algorithm) {
|
|
|
|
// TODO add non-cryptographic algorithm here
|
2018-01-20 00:06:59 +08:00
|
|
|
case "debug":
|
|
|
|
return new DebugHash();
|
|
|
|
default:
|
|
|
|
return new BulkUpdateDecorator(require("crypto").createHash(algorithm));
|
2017-11-23 17:59:29 +08:00
|
|
|
}
|
|
|
|
};
|