use unicode_width::UnicodeWidthStr;
use super::{Grapheme, PrintableText};
pub(crate) fn grapheme(cluster: &Grapheme) -> usize {
UnicodeWidthStr::width(cluster.as_str())
}
pub(crate) fn text(text: &PrintableText) -> usize {
let text = text.as_str();
if text.is_ascii() {
return text.len();
}
PrintableText::new(text).graphemes().map(grapheme).sum()
}
#[cfg(test)]
mod tests {
use super::*;
fn width(line: &str) -> usize {
text(PrintableText::new(line))
}
#[test]
fn ascii_is_one_cell_per_byte() {
assert_eq!(width("hello, world!"), 13);
assert_eq!(width(""), 0);
assert_eq!(
width("abc"),
PrintableText::new("abc")
.graphemes()
.map(grapheme)
.sum::<usize>()
);
}
#[test]
fn wide_and_zero_width_clusters_keep_their_cells() {
assert_eq!(width("日本語"), 6);
assert_eq!(width("aあ"), 3);
assert_eq!(width("👩💻"), 2);
assert_eq!(width("e\u{301}"), 1);
}
#[test]
fn a_ligature_spanning_clusters_is_measured_by_its_clusters() {
assert_eq!(UnicodeWidthStr::width("\u{644}\u{627}"), 1);
assert_eq!(width("\u{644}\u{627}"), 2);
}
}