bytes32.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. /**
  3. * About bytes32 strings...
  4. *
  5. * @_docloc: api/utils:Bytes32 Strings
  6. */
  7. Object.defineProperty(exports, "__esModule", { value: true });
  8. exports.decodeBytes32String = exports.encodeBytes32String = void 0;
  9. const index_js_1 = require("../utils/index.js");
  10. /**
  11. * Encodes %%text%% as a Bytes32 string.
  12. */
  13. function encodeBytes32String(text) {
  14. // Get the bytes
  15. const bytes = (0, index_js_1.toUtf8Bytes)(text);
  16. // Check we have room for null-termination
  17. if (bytes.length > 31) {
  18. throw new Error("bytes32 string must be less than 32 bytes");
  19. }
  20. // Zero-pad (implicitly null-terminates)
  21. return (0, index_js_1.zeroPadBytes)(bytes, 32);
  22. }
  23. exports.encodeBytes32String = encodeBytes32String;
  24. /**
  25. * Encodes the Bytes32-encoded %%bytes%% into a string.
  26. */
  27. function decodeBytes32String(_bytes) {
  28. const data = (0, index_js_1.getBytes)(_bytes, "bytes");
  29. // Must be 32 bytes with a null-termination
  30. if (data.length !== 32) {
  31. throw new Error("invalid bytes32 - not 32 bytes long");
  32. }
  33. if (data[31] !== 0) {
  34. throw new Error("invalid bytes32 string - no null terminator");
  35. }
  36. // Find the null termination
  37. let length = 31;
  38. while (data[length - 1] === 0) {
  39. length--;
  40. }
  41. // Determine the string value
  42. return (0, index_js_1.toUtf8String)(data.slice(0, length));
  43. }
  44. exports.decodeBytes32String = decodeBytes32String;
  45. //# sourceMappingURL=bytes32.js.map