bytes32.js 1.2 KB

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