Skip to main content

truncate_bytes_safe

Function truncate_bytes_safe 

Source
pub fn truncate_bytes_safe(s: &str, max_bytes: usize) -> &str
Expand description

Truncates s to at most max_bytes bytes while respecting UTF-8 char boundaries.

If s is shorter than or equal to max_bytes bytes it is returned unchanged. Otherwise the longest prefix that fits within max_bytes bytes and ends on a valid UTF-8 boundary is returned, so the result is always a valid &str.

This is safe to use for building diagnostic messages from arbitrary API response bodies, which may contain multi-byte characters like em-dashes.