Skip to main content

UnicodeWidth

Struct UnicodeWidth 

Source
pub struct UnicodeWidth { /* private fields */ }
Expand description

A configuration helper to measure character and string widths.

It determines the width of Unicode characters and strings, optionally treating East Asian Ambiguous characters (such as certain Greek, Cyrillic, and CJK characters) as having a width of 2 (CJK mode).

The default CJK mode is initialized at startup based on the UNICODE_WIDTH environment variable, but can also be dynamically modified using set_default_cjk().

Implementations§

Source§

impl UnicodeWidth

Source

pub fn new() -> Self

Create a UnicodeWidth instance using the default CJK mode.

The default CJK mode is determined by the global setting, which defaults to the value of the UNICODE_WIDTH environment variable (value "cjk" enabling CJK mode).

See also set_default_cjk().

Source

pub fn with_cjk(is_cjk: bool) -> Self

Create a new UnicodeWidth instance with a specific CJK flag.

If is_cjk is true, East Asian Ambiguous characters will be treated as 2 columns wide. If false, they will be treated as 1 column wide.

See also set_cjk().

§Examples
use unicode_width_utils::UnicodeWidth;

let non_cjk = UnicodeWidth::with_cjk(false);
assert_eq!(non_cjk.char('█'), 1);
let cjk = UnicodeWidth::with_cjk(true);
assert_eq!(cjk.char('█'), 2);
Source

pub fn set_cjk(&mut self, is_cjk: bool)

Set to whether to perform an alternate width calculation more suited to CJK contexts or not.

When set to true, characters in the Ambiguous category according to Unicode Standard Annex #11 as 2 columns wide.

See also the “cjk” feature flag and UnicodeWidthChar::width_cjk().

§Examples
use unicode_width_utils::UnicodeWidth;

let mut uw = UnicodeWidth::with_cjk(false);
assert_eq!(uw.char('█'), 1);
uw.set_cjk(true);
assert_eq!(uw.char('█'), 2);
Source

pub fn set_default_cjk(is_cjk: bool)

Set the default CJK configuration dynamically.

Future instances created using UnicodeWidth::new() or UnicodeWidth::default() will inherit this default value unless explicitly overridden with with_cjk() or set_cjk().

§Examples
use unicode_width_utils::UnicodeWidth;

// Set default CJK mode to true.
UnicodeWidth::set_default_cjk(true);
let cjk = UnicodeWidth::new();
assert_eq!(cjk.char('█'), 2);

// Set default CJK mode to false.
UnicodeWidth::set_default_cjk(false);
let non_cjk = UnicodeWidth::new();
assert_eq!(non_cjk.char('█'), 1);
Source

pub fn set_control_size(&mut self, size: u8)

Set the size of control characters.

§Examples
use unicode_width_utils::UnicodeWidth;

let mut uw = UnicodeWidth::new();
assert_eq!(uw.char('\t'), 1);
assert_eq!(uw.str("A\tB"), 3);
uw.set_control_size(0);
assert_eq!(uw.char('\t'), 0);
assert_eq!(uw.str("A\tB"), 2);
Source

pub fn set_tab_size(&mut self, tab_size: u8)

Set the tab size. Initially 0.

This setting is used by truncate() and UnicodeWidth::str().

See also set_expand_tab().

§Examples
use unicode_width_utils::UnicodeWidth;

let mut uw = UnicodeWidth::new();
uw.set_tab_size(4);
assert_eq!(uw.truncate("A\tB", 3), Cow::Borrowed("A"));
assert_eq!(uw.truncate("A\tB", 4), Cow::Borrowed("A\t"));
assert_eq!(uw.truncate("A\tB", 5), Cow::Borrowed("A\tB"));
Source

pub fn set_expand_tab(&mut self, should_expand_tab: bool)

Set whether tabs should be expanded to spaces. Initially false.

This setting is used by truncate() and UnicodeWidth::str().

See also set_tab_size().

§Examples
use unicode_width_utils::UnicodeWidth;

let mut uw = UnicodeWidth::new();
uw.set_tab_size(4);
uw.set_expand_tab(true);
assert_eq!(uw.truncate("A\tB", 3), Cow::Borrowed("A"));
assert_eq!(uw.truncate("A\tB", 4), Cow::Owned::<str>("A   ".into()));
assert_eq!(uw.truncate("A\tB", 5), Cow::Owned::<str>("A   B".into()));
Source

pub fn char(&self, ch: char) -> usize

Return the column width of a character.

This is a wrapper of UnicodeWidthChar. It calls width or width_cjk depending on the configuration.

Control characters return 1 by default to match UnicodeWidthStr. See also char_opt() and set_control_size() for control characters.

§Examples
use unicode_width_utils::UnicodeWidth;

let uw = UnicodeWidth::new();
assert_eq!(uw.char('A'), 1);
assert_eq!(uw.char('あ'), 2);
Source

pub fn char_opt(&self, ch: char) -> Option<usize>

Return the column width of a character.

Return None for control characters or other characters without a defined width.

This is a wrapper of UnicodeWidthChar. It calls width or width_cjk depending on the configuration.

§Examples
use unicode_width_utils::UnicodeWidth;

let uw = UnicodeWidth::new();
assert_eq!(uw.char_opt('A'), Some(1));
assert_eq!(uw.char_opt('\n'), None);
Source

pub fn str(&self, str: &str) -> usize

Return the total column width of a string.

This is a wrapper of UnicodeWidthStr. It calls width or width_cjk depending on the configuration, unless the tab size is set or the control character size is set, in which case the internal logic computes the width by calling char_opt() or char() repeatedly.

§Examples
use unicode_width_utils::UnicodeWidth;

let mut uw = UnicodeWidth::new();
assert_eq!(uw.str("Hello"), 5);
assert_eq!(uw.str("Hello\t"), 6);
uw.set_tab_size(4);
assert_eq!(uw.str("Hello\t"), 8);
Source

pub fn truncate<'a>(&self, input: &'a str, max_width: usize) -> Cow<'a, str>

Truncate a string slice to a maximum column width.

The returned slice will be the longest prefix of input whose total column width does not exceed max_width.

See also set_tab_size() and set_expand_tab().

§Examples
use unicode_width_utils::UnicodeWidth;

let uw = UnicodeWidth::new();
assert_eq!(uw.truncate("hello", 3), "hel");

// Truncating CJK text (each 'あ' is 2 columns wide).
assert_eq!(uw.truncate("あああ", 3), "あ");
assert_eq!(uw.truncate("A█B", 2), "A█");

let cjk = UnicodeWidth::with_cjk(true);
assert_eq!(cjk.truncate("A█B", 2), "A");
Source

pub fn lines<'a>( &self, input: &'a str, max_width: usize, ) -> LineIterator<'_, 'a>

Return a LineIterator to iterate over chunks of a string based on display width.

Unlike truncate(), each line is guaranteed to have at least one character, even if it is wider than max_width.

§Examples
use unicode_width_utils::UnicodeWidth;

let uw = UnicodeWidth::new();
assert_eq!(
    uw.lines("12345678", 3).collect::<Vec<_>>(),
    vec!["123", "456", "78"]
);

Trait Implementations§

Source§

impl Clone for UnicodeWidth

Source§

fn clone(&self) -> UnicodeWidth

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for UnicodeWidth

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for UnicodeWidth

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.