Created
October 1, 2019 22:52
-
-
Save csauve/bfbdd66664131676a111fd6c890060c5 to your computer and use it in GitHub Desktop.
Safely trims a String to a max length of bytes in a desired encoding without cutting multi-byte characters in half.
This file contains 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
static String trimBytes(String input, int lengthBytes, Charset charset) { | |
if (input == null) return null | |
if (input.getBytes(charset).length <= lengthBytes) return input | |
def bytes = charset.encode(input) | |
bytes.limit(Math.min(lengthBytes, bytes.limit())) | |
def chars = charset.newDecoder() | |
.onMalformedInput(CodingErrorAction.IGNORE) | |
.onUnmappableCharacter(CodingErrorAction.IGNORE) | |
.decode(bytes) | |
return new StringBuffer(chars).toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment