StringXor.js
1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class StringXor {
constructor() {
this._value = undefined;
}
/**
* @param {string} str string
* @returns {void}
*/
add(str) {
const len = str.length;
const value = this._value;
if (value === undefined) {
const newValue = (this._value = Buffer.allocUnsafe(len));
for (let i = 0; i < len; i++) {
newValue[i] = str.charCodeAt(i);
}
return;
}
const valueLen = value.length;
if (valueLen < len) {
const newValue = (this._value = Buffer.allocUnsafe(len));
let i;
for (i = 0; i < valueLen; i++) {
newValue[i] = value[i] ^ str.charCodeAt(i);
}
for (; i < len; i++) {
newValue[i] = str.charCodeAt(i);
}
} else {
for (let i = 0; i < len; i++) {
value[i] = value[i] ^ str.charCodeAt(i);
}
}
}
toString() {
const value = this._value;
return value === undefined ? "" : value.toString("latin1");
}
updateHash(hash) {
const value = this._value;
if (value !== undefined) hash.update(value);
}
}
module.exports = StringXor;