Created
September 29, 2015 04:10
-
-
Save dginev/f6da5e94335d545e0a7b to your computer and use it in GitHub Desktop.
UTF8 safe truncate for Rust strings
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
fn utf8_truncate(input : &mut String, maxsize: usize) { | |
let mut utf8_maxsize = input.len(); | |
if utf8_maxsize >= maxsize { | |
{ let mut char_iter = input.char_indices(); | |
while utf8_maxsize >= maxsize { | |
utf8_maxsize = match char_iter.next_back() { | |
Some((index, _)) => index, | |
_ => 0 | |
}; | |
} } // Extra {} wrap to limit the immutable borrow of char_indices() | |
input.truncate(utf8_maxsize); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to
aatch
from IRC, for the minimal UTF8 smiley mutlilation example demonstrating why this is needed:While
.truncate()
and.len()
work on raw bytes, UTF8-encoded characters often use several bytes, so blind truncating would break the encoding.P.S. The irony that I couldn't use the original example's smiley char because GitHub refuses high-end Unicode: