Skip to main content

truncate

Function truncate 

Source
pub fn truncate(s: &str, max_len: usize) -> String
Expand description

Truncates a string to a maximum length, respecting UTF-8 character boundaries.

This function safely handles multi-byte UTF-8 characters (e.g., degree symbol, emoji, CJK characters) by finding the nearest valid character boundary.

§Arguments

  • s - The string to truncate.
  • max_len - Maximum byte length for the result (including “…” suffix).

§Returns

The original string if it fits, otherwise a truncated version with “…” appended.

§Examples

// ASCII text
assert_eq!(truncate("Hello, world!", 10), "Hello, ...");

// Multi-byte UTF-8 characters (degree symbol is 2 bytes)
assert_eq!(truncate("32 °C temperature", 10), "32 °C ...");

// String shorter than max_len
assert_eq!(truncate("short", 100), "short");