use std::borrow::Cow;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicBool, Ordering};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
static IS_CJK: LazyLock<AtomicBool> = LazyLock::new(|| {
let is_cjk = match std::env::var("UNICODE_WIDTH") {
Ok(value) => value.eq_ignore_ascii_case("cjk"),
_ => false,
};
AtomicBool::new(is_cjk)
});
#[derive(Clone, Debug)]
pub struct UnicodeWidth {
is_cjk: bool,
should_expand_tab: bool,
tab_size: u8,
}
impl Default for UnicodeWidth {
fn default() -> Self {
Self {
is_cjk: IS_CJK.load(Ordering::Relaxed),
should_expand_tab: false,
tab_size: 0,
}
}
}
impl UnicodeWidth {
pub fn new() -> Self {
Self::default()
}
pub fn with_cjk(is_cjk: bool) -> Self {
Self {
is_cjk,
..Default::default()
}
}
pub fn set_default_cjk(is_cjk: bool) {
IS_CJK.store(is_cjk, Ordering::Relaxed);
}
#[deprecated(note = "Please use `char_opt` instead.")]
pub fn char(&self, ch: char) -> Option<usize> {
self.char_opt(ch)
}
pub fn char_opt(&self, ch: char) -> Option<usize> {
match self.is_cjk {
false => UnicodeWidthChar::width(ch),
true => UnicodeWidthChar::width_cjk(ch),
}
}
pub fn str(&self, str: &str) -> usize {
match self.is_cjk {
false => UnicodeWidthStr::width(str),
true => UnicodeWidthStr::width_cjk(str),
}
}
pub fn set_tab_size(&mut self, tab_size: u8) {
self.tab_size = tab_size;
}
pub fn set_expand_tab(&mut self, should_expand_tab: bool) {
self.should_expand_tab = should_expand_tab;
}
pub fn truncate<'a>(&self, input: &'a str, max_width: usize) -> Cow<'a, str> {
let mut width = 0;
let mut buffer: Option<String> = None;
let tab_size = self.tab_size as usize;
for (index, ch) in input.char_indices() {
let ch_width = if let Some(ch_width) = self.char_opt(ch) {
ch_width
} else if ch == '\t' && tab_size > 0 {
if buffer.is_none() && self.should_expand_tab {
let mut output = String::with_capacity(input.len() + tab_size * 4);
output.push_str(&input[..index]);
buffer = Some(output);
}
tab_size - (width % tab_size)
} else {
0
};
width += ch_width;
if width > max_width {
return match buffer {
None => Cow::Borrowed(&input[..index]),
Some(output) => Cow::Owned(output),
};
}
if let Some(ref mut output) = buffer {
if ch == '\t' {
for _ in 0..ch_width {
output.push(' ');
}
} else {
output.push(ch);
}
}
}
match buffer {
None => Cow::Borrowed(input),
Some(output) => Cow::Owned(output),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn char() {
let uw = UnicodeWidth::with_cjk(false);
let cjk = UnicodeWidth::with_cjk(true);
assert_eq!(uw.char_opt('A'), Some(1));
assert_eq!(cjk.char_opt('A'), Some(1));
assert_eq!(uw.char_opt('\u{2588}'), Some(1));
assert_eq!(cjk.char_opt('\u{2588}'), Some(2));
assert_eq!(uw.char_opt('\u{3042}'), Some(2));
assert_eq!(cjk.char_opt('\u{3042}'), Some(2));
}
#[test]
fn str() {
let uw = UnicodeWidth::with_cjk(false);
let cjk = UnicodeWidth::with_cjk(true);
assert_eq!(uw.str("A"), 1);
assert_eq!(cjk.str("A"), 1);
assert_eq!(uw.str("\u{2588}"), 1);
assert_eq!(cjk.str("\u{2588}"), 2);
assert_eq!(uw.str("\u{3042}"), 2);
assert_eq!(cjk.str("\u{3042}"), 2);
}
#[test]
fn truncate() {
let uw = UnicodeWidth::with_cjk(false);
let cjk = UnicodeWidth::with_cjk(true);
assert_eq!(uw.truncate("hello", 0), "");
assert_eq!(uw.truncate("hello", 4), "hell");
assert_eq!(uw.truncate("hello", 5), "hello");
assert_eq!(uw.truncate("hello", 6), "hello");
assert_eq!(uw.truncate("hello", 10), "hello");
assert_eq!(uw.truncate("A\u{2588}B", 2), "A\u{2588}");
assert_eq!(cjk.truncate("A\u{2588}B", 2), "A");
assert_eq!(uw.truncate("\u{3042}", 1), "");
assert_eq!(uw.truncate("\u{3042}", 2), "\u{3042}");
assert_eq!(uw.truncate("\u{3042}", 3), "\u{3042}");
assert_eq!(uw.truncate("A\nB", 1), "A\n");
assert_eq!(uw.truncate("A\nB", 2), "A\nB");
assert_eq!(uw.truncate("\nA", 0), "\n");
}
#[test]
fn default_cjk() {
let original = IS_CJK.load(Ordering::Relaxed);
UnicodeWidth::set_default_cjk(false);
assert_eq!(UnicodeWidth::default().char_opt('\u{2588}'), Some(1));
assert_eq!(UnicodeWidth::new().char_opt('\u{2588}'), Some(1));
UnicodeWidth::set_default_cjk(true);
assert_eq!(UnicodeWidth::default().char_opt('\u{2588}'), Some(2));
assert_eq!(UnicodeWidth::new().char_opt('\u{2588}'), Some(2));
UnicodeWidth::set_default_cjk(original);
}
#[test]
fn truncate_tabs_zero() {
let mut uw = UnicodeWidth::new();
for _ in 0..2 {
assert_eq!(uw.truncate("A\tB", 1), Cow::Borrowed("A\t"));
assert_eq!(uw.truncate("A\tB", 2), Cow::Borrowed("A\tB"));
uw.set_expand_tab(true);
}
}
#[test]
fn truncate_tabs_expand_multi() {
let mut uw = UnicodeWidth::new();
uw.set_tab_size(4);
uw.set_expand_tab(true);
assert_eq!(uw.truncate("\t\t", 7), Cow::Owned::<str>(" ".into()));
assert_eq!(uw.truncate("\t\t", 8), Cow::Owned::<str>(" ".into()));
}
}