hashASCIIStrToField function

BigInt hashASCIIStrToField(
  1. String str,
  2. int maxSize
)

Hashes an ASCII str to a single field element, padding with zero bytes up to maxSize. Throws an ArgumentError if str is longer than maxSize.

Implementation

BigInt hashASCIIStrToField(String str, int maxSize) {
  if (str.length > maxSize) {
    throw ArgumentError('String $str is longer than $maxSize chars');
  }

  // Padding with zeroes is safe because we are only using this function to map
  // a human-readable sequence of bytes. The ASCII values of those characters
  // will never be zero (the null character).
  final strPadded = str.padRight(maxSize, String.fromCharCode(0)).codeUnits;

  const chunkSize = PACK_WIDTH ~/ 8;
  final packed = chunkArray(strPadded, chunkSize).map(bytesBEToBigInt).toList();
  return poseidonHash(packed);
}