Function truncate_by_width

Source
pub fn truncate_by_width(s: &str, max_width: usize) -> &str
Expand description

Truncates a string by display width while preserving grapheme cluster boundaries.

This function ensures that wide characters such as emoji or CJK ideographs are never split in the middle. It safely cuts off the string so that its total display width does not exceed the given max_width, making it ideal for terminal or TUI rendering.

§Arguments

  • s - The input string to truncate
  • max_width - Maximum allowed display width in terminal columns

§Returns

A string slice that fits within the specified display width without cutting graphemes.

§Example

use runefix_core::truncate_by_width;

let s = "Hi 👋,世界";
let short = truncate_by_width(s, 6);
assert_eq!(short, "Hi 👋");