Last active
October 19, 2024 06:41
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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