StringXor.js 1.1 KB

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