All files / ethers.js/src.ts/abi bytes32.ts

100% Statements 44/44
50% Branches 3/6
100% Functions 2/2
100% Lines 44/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 461x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x    
/**
 *  About bytes32 strings...
 *
 *  @_docloc: api/utils:Bytes32 Strings
 */
 
import {
    getBytes, toUtf8Bytes, toUtf8String, zeroPadBytes
} from "../utils/index.js";
 
import type { BytesLike } from "../utils/index.js";
 
/**
 *  Encodes %%text%% as a Bytes32 string.
 */
export function encodeBytes32String(text: string): string {
 
    // Get the bytes
    const bytes = toUtf8Bytes(text);
 
    // Check we have room for null-termination
    if (bytes.length > 31) { throw new Error("bytes32 string must be less than 32 bytes"); }
 
    // Zero-pad (implicitly null-terminates)
    return zeroPadBytes(bytes, 32);
}
 
/**
 *  Encodes the Bytes32-encoded %%bytes%% into a string.
 */
export function decodeBytes32String(_bytes: BytesLike): string {
    const data = getBytes(_bytes, "bytes");
 
    // Must be 32 bytes with a null-termination
    if (data.length !== 32) { throw new Error("invalid bytes32 - not 32 bytes long"); }
    if (data[31] !== 0) { throw new Error("invalid bytes32 string - no null terminator"); }
 
    // Find the null termination
    let length = 31;
    while (data[length - 1] === 0) { length--; }
 
    // Determine the string value
    return toUtf8String(data.slice(0, length));
}