// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; library StringUtils { /// @dev Returns the length of a given string /// @param s The string to measure the length of /// @return The length of the input string function strlen(string memory s) internal pure returns (uint256) { uint256 len; uint256 i = 0; uint256 bytelength = bytes(s).length; for (len = 0; i < bytelength; len++) { bytes1 b = bytes(s)[i]; if (b < 0x80) { i += 1; } else if (b < 0xE0) { i += 2; } else if (b < 0xF0) { i += 3; } else if (b < 0xF8) { i += 4; } else if (b < 0xFC) { i += 5; } else { i += 6; } } return len; } /// @dev Escapes special characters in a given string /// @param str The string to escape /// @return The escaped string function escape(string memory str) internal pure returns (string memory) { bytes memory strBytes = bytes(str); uint extraChars = 0; // count extra space needed for escaping for (uint i = 0; i < strBytes.length; i++) { if (_needsEscaping(strBytes[i])) { extraChars++; } } // allocate buffer with the exact size needed bytes memory buffer = new bytes(strBytes.length + extraChars); uint index = 0; // escape characters for (uint i = 0; i < strBytes.length; i++) { if (_needsEscaping(strBytes[i])) { buffer[index++] = "\\"; buffer[index++] = _getEscapedChar(strBytes[i]); } else { buffer[index++] = strBytes[i]; } } return string(buffer); } // determine if a character needs escaping function _needsEscaping(bytes1 char) private pure returns (bool) { return char == '"' || char == "/" || char == "\\" || char == "\n" || char == "\r" || char == "\t"; } // get the escaped character function _getEscapedChar(bytes1 char) private pure returns (bytes1) { if (char == "\n") return "n"; if (char == "\r") return "r"; if (char == "\t") return "t"; return char; } }