add utils.truncate_encode
, to encode and truncate a string while respecting utf8 multi-byte encoding
This commit is contained in:
parent
9ecec75828
commit
f2c762a2d0
1 changed files with 10 additions and 0 deletions
|
@ -189,3 +189,13 @@ def is_ip(s: str) -> bool:
|
|||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def encode_truncate(s: str, encoding: str, byte_max: int) -> bytes:
|
||||
encoded = b""
|
||||
for character in s:
|
||||
encoded_character = character.encode(encoding)
|
||||
if len(encoded + encoded_character) > byte_max:
|
||||
break
|
||||
else:
|
||||
encoded += encoded_character
|
||||
return encoded
|
||||
|
|
Loading…
Reference in a new issue