Skip to content

Instantly share code, notes, and snippets.

@csauve
Created October 1, 2019 22:52
Show Gist options
  • Save csauve/bfbdd66664131676a111fd6c890060c5 to your computer and use it in GitHub Desktop.
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.
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