Skip to content

Instantly share code, notes, and snippets.

@frangio
Last active March 17, 2023 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frangio/6247dcd678389cd6ab3da45ef3e98d19 to your computer and use it in GitHub Desktop.
Save frangio/6247dcd678389cd6ab3da45ef3e98d19 to your computer and use it in GitHub Desktop.
Solidity function to check if a string contains only printable ASCII characters and is at most 32 characters long. Branch-free "vectorized" implementation.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
function isAsciiPrintableShortString(string memory str) pure returns (bool) {
unchecked {
uint256 b = uint256(bytes32(hex"0101010101010101010101010101010101010101010101010101010101010101"));
bytes32 chars = bytes32(bytes(str));
uint256 len = bytes(str).length;
bytes32 nonprintable = chars & bytes32(b * 0xe0);
nonprintable |= nonprintable >> 1;
nonprintable &= bytes32(b * 0xa0);
nonprintable ^= bytes32(b * 0x20);
nonprintable >>= 8 * (32 - len);
bytes32 del = chars;
del &= del >> 1;
del &= del >> 1;
del &= del >> 2;
del &= del >> 2;
return (nonprintable | del) == 0 && len <= 32;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment