bytes32.ts 1.2 KB

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