diff --git a/termwiz/benches/wcwidth.rs b/termwiz/benches/wcwidth.rs index c902c8ba9..756f17525 100644 --- a/termwiz/benches/wcwidth.rs +++ b/termwiz/benches/wcwidth.rs @@ -1,22 +1,100 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use termwiz::cell::grapheme_column_width; +use termwiz::cell::{grapheme_column_width, UnicodeVersion}; + +include!("../src/widechar_width.rs"); pub fn criterion_benchmark(c: &mut Criterion) { - c.bench_function("grapheme_column_width a", |b| { - b.iter(|| grapheme_column_width(black_box("a"), None)) - }); + let table = WcLookupTable::new(); - c.bench_function("grapheme_column_width emoji with variation selector", |b| { - b.iter(|| grapheme_column_width(black_box("\u{00a9}\u{FE0F}"), None)) - }); + { + let mut group = c.benchmark_group("Classify ASCII"); + group.bench_function("WcWidth", |b| b.iter(|| WcWidth::from_char(black_box('a')))); + group.bench_function("WcLookupTable", |b| { + b.iter(|| table.classify(black_box('a'))) + }); + group.finish(); + } - c.bench_function("grapheme_column_width WidenedIn9", |b| { - b.iter(|| grapheme_column_width(black_box("\u{231a}"), None)) - }); + { + let mut group = c.benchmark_group("Classify DoubleWidth"); - c.bench_function("grapheme_column_width Unassigned", |b| { - b.iter(|| grapheme_column_width(black_box("\u{fbc9}"), None)) - }); + group.bench_function("WcWidth", |b| { + b.iter(|| WcWidth::from_char(black_box('\u{1100}'))) + }); + group.bench_function("WcLookupTable", |b| { + b.iter(|| table.classify(black_box('\u{1100}'))) + }); + + group.finish(); + } + + { + let mut group = c.benchmark_group("Classify WidenedIn9"); + + group.bench_function("WcWidth", |b| { + b.iter(|| WcWidth::from_char(black_box('\u{231a}'))) + }); + group.bench_function("WcLookupTable", |b| { + b.iter(|| table.classify(black_box('\u{231a}'))) + }); + group.finish(); + } + + { + let mut group = c.benchmark_group("Classify Unassigned"); + + group.bench_function("WcWidth", |b| { + b.iter(|| WcWidth::from_char(black_box('\u{fbc9}'))) + }); + group.bench_function("WcLookupTable", |b| { + b.iter(|| table.classify(black_box('\u{fbc9}'))) + }); + group.finish(); + } + + { + let mut group = c.benchmark_group("column_width ASCII"); + group.bench_function("grapheme_column_width", |b| { + b.iter(|| grapheme_column_width(black_box("a"), None)) + }); + group.finish(); + } + + { + let mut group = c.benchmark_group("column_width variation selector"); + group.bench_function("grapheme_column_width", |b| { + b.iter(|| grapheme_column_width(black_box("\u{00a9}\u{FE0F}"), None)) + }); + group.finish(); + } + + { + let mut group = c.benchmark_group("column_width variation selector unicode 14"); + let version = UnicodeVersion { + version: 14, + ambiguous_are_wide: false, + }; + group.bench_function("grapheme_column_width", |b| { + b.iter(|| grapheme_column_width(black_box("\u{00a9}\u{FE0F}"), Some(version))) + }); + group.finish(); + } + + { + let mut group = c.benchmark_group("column_width WidenedIn9"); + group.bench_function("grapheme_column_width", |b| { + b.iter(|| grapheme_column_width(black_box("\u{231a}"), None)) + }); + group.finish(); + } + + { + let mut group = c.benchmark_group("column_width Unassigned"); + group.bench_function("grapheme_column_width", |b| { + b.iter(|| grapheme_column_width(black_box("\u{fbc9}"), None)) + }); + group.finish(); + } } criterion_group!(benches, criterion_benchmark); diff --git a/termwiz/codegen/src/main.rs b/termwiz/codegen/src/main.rs index f153f4bc7..c2ebebf1b 100644 --- a/termwiz/codegen/src/main.rs +++ b/termwiz/codegen/src/main.rs @@ -1,11 +1,19 @@ const VARIATION_SEQUENCES: &str = include_str!("../../data/emoji-variation-sequences.txt"); include!("../../src/emoji_presentation.rs"); +include!("../../src/widechar_width.rs"); /// Parses emoji-variation-sequences.txt, which is part of the UCD download /// for a given version of the Unicode spec. /// It defines which sequences can have explicit presentation selectors. fn main() { + println!("//! This file was generated by running:"); + println!("//! cd ../codegen ; cargo run > ../emoji_variation.rs"); + println!(); + emit_variation_map(); +} + +fn emit_variation_map() { let mut map = phf_codegen::Map::new(); 'next_line: for line in VARIATION_SEQUENCES.lines() { @@ -46,9 +54,6 @@ fn main() { } } - println!("//! This file was generated by running:"); - println!("//! cd ../codegen ; cargo run > ../emoji_variation.rs"); - println!(); println!("use crate::emoji::Presentation;"); println!(); println!( diff --git a/termwiz/src/cell.rs b/termwiz/src/cell.rs index 17b0636be..1a0d73cb0 100644 --- a/termwiz/src/cell.rs +++ b/termwiz/src/cell.rs @@ -3,7 +3,7 @@ use crate::color::{ColorAttribute, PaletteIndex}; pub use crate::emoji::Presentation; pub use crate::escape::osc::Hyperlink; use crate::image::ImageCell; -use crate::widechar_width::WcWidth; +use crate::widechar_width::{WcLookupTable, WcWidth}; #[cfg(feature = "use_serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::mem; @@ -850,6 +850,27 @@ impl UnicodeVersion { ambiguous_are_wide: false, } } + + #[inline] + fn width(&self, c: WcWidth) -> usize { + // Special case for symbol fonts that are naughtly and use + // the unassigned range instead of the private use range. + // + if c == WcWidth::Unassigned { + 1 + } else if c == WcWidth::Ambiguous && self.ambiguous_are_wide { + 2 + } else if self.version >= 9 { + c.width_unicode_9_or_later() as usize + } else { + c.width_unicode_8_or_earlier() as usize + } + } + + #[inline] + pub fn idx(&self) -> usize { + (if self.version > 9 { 2 } else { 0 }) | (if self.ambiguous_are_wide { 1 } else { 0 }) + } } pub const LATEST_UNICODE_VERSION: UnicodeVersion = UnicodeVersion { @@ -868,6 +889,10 @@ pub fn unicode_column_width(s: &str, version: Option) -> usize { .sum() } +lazy_static::lazy_static! { + static ref WCWIDTH_TABLE: WcLookupTable = WcLookupTable::new(); +} + /// Returns the number of cells visually occupied by a grapheme. /// The input string must be a single grapheme. /// @@ -899,41 +924,47 @@ pub fn unicode_column_width(s: &str, version: Option) -> usize { /// the Cell that is used to hold a grapheme, and that per-Cell version /// can then be used to calculate width. pub fn grapheme_column_width(s: &str, version: Option) -> usize { - let version = version.unwrap_or(LATEST_UNICODE_VERSION); - let ambiguous_are_wide = version.ambiguous_are_wide; - let version = version.version; + let version = version.as_ref().unwrap_or(&LATEST_UNICODE_VERSION); - let width: usize = s - .chars() - .map(|c| { - let c = WcWidth::from_char(c); - - // Special case for symbol fonts that are naughtly and use - // the unassigned range instead of the private use range. - // - if c == WcWidth::Unassigned { - 1 - } else if c == WcWidth::Ambiguous && ambiguous_are_wide { - 2 - } else if version >= 9 { - c.width_unicode_9_or_later() - } else { - c.width_unicode_8_or_earlier() - } - }) - .sum::() - .into(); - - if version >= 14 { - match Presentation::for_grapheme(s) { - (_, Some(Presentation::Emoji)) => 2, - (_, Some(Presentation::Text)) => 1, - (Presentation::Emoji, None) => 2, - (Presentation::Text, None) => width.min(2), - } - } else { - width.min(2) + // Optimization: if there is a single byte we can directly cast + // that byte as a char which will be in the range 0.255. + // This takes ~1.5ns, and we can then look that up in the table + // which is valid for chars in the range 0-0xffff. + // That lookup also takes ~1.5ns, giving us a hot path latency + // of ~3-4ns for a grapheme string that is comprised of a single + // ASCII byte. + // + // Since we know this is a single ASCII char, we know that it + // cannot be a sequence with a variation selector, so we don't + // need to requested `Presentation` for it. + if s.len() == 1 { + let c = WCWIDTH_TABLE.classify(s.as_bytes()[0] as char); + return version.width(c); } + + // Slow path: `s.chars()` will dominate and pull up the minimum + // runtime to ~20ns + + if version.version >= 14 { + // Lookup the grapheme to see if the presentation of + // the grapheme forces the width. We can bypass + // the WcWidth classification if that is true. + match Presentation::for_grapheme(s) { + (_, Some(Presentation::Emoji)) => return 2, + (_, Some(Presentation::Text)) => return 1, + (Presentation::Emoji, None) => return 2, + (Presentation::Text, None) => {} + } + } + + // Otherwise, classify and sum up + let mut width = 0; + for c in s.chars() { + let c = WCWIDTH_TABLE.classify(c); + width += version.width(c); + } + + width.min(2) } /// Models a change in the attributes of a cell in a stream of changes. diff --git a/termwiz/src/widechar_width.rs b/termwiz/src/widechar_width.rs index 087044778..6433ac11c 100644 --- a/termwiz/src/widechar_width.rs +++ b/termwiz/src/widechar_width.rs @@ -11,6 +11,7 @@ type R = (u32, u32); #[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[repr(u8)] pub enum WcWidth { /// The character is single-width One, @@ -1492,6 +1493,7 @@ impl WcWidth { } /// Returns width for applications that are using unicode 8 or earlier + #[inline] pub fn width_unicode_8_or_earlier(self) -> u8 { match self { Self::One => 1, @@ -1503,6 +1505,7 @@ impl WcWidth { } /// Returns width for applications that are using unicode 9 or later + #[inline] pub fn width_unicode_9_or_later(self) -> u8 { if self == Self::WidenedIn9 { return 2; @@ -1511,6 +1514,89 @@ impl WcWidth { } } +/// An alternative interface that precomputes the values for the first 64k +/// codepoints and maintains a table that is 64kb in size. +/// Lookups are then a simple O(1) index operation that takes ~1.5ns +/// constant time for codepoints in that range, falling back to +/// the regular WcWidth::from_char for codepoints outside that range +/// (which takes 20-75ns depending on the codepoint and which table +/// it is resolved to) +pub struct WcLookupTable { + pub table: [WcWidth; 65536], +} + +impl WcLookupTable { + pub fn new() -> Self { + let mut table = [WcWidth::One; 65536]; + // Populate the table with data from the other tables in + // the reverse order to that used to lookup in + // WcWidth::from_char so that the precedence is the + // same in the event that there are any overlaps. + for &(start, end) in WIDENED_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::WidenedIn9; + } + } + for &(start, end) in UNASSIGNED_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::Unassigned; + } + } + for &(start, end) in AMBIGUOUS_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::Ambiguous; + } + } + for &(start, end) in DOUBLEWIDE_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::Two; + } + } + for &(start, end) in COMBININGLETTERS_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::Combining; + } + } + for &(start, end) in COMBINING_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::Combining; + } + } + for &(start, end) in NONCHAR_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::NonCharacter; + } + } + for &(start, end) in NONPRINT_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::NonPrint; + } + } + for &(start, end) in PRIVATE_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::PrivateUse; + } + } + /* Implicit, as we initialized to One + for &(start, end) in ASCII_TABLE { + for i in start..=end.min(0xffff) { + table[i as usize] = WcWidth::One; + } + } + */ + Self { table } + } + + /// Classify a char as a WcWidth + pub fn classify(&self, c: char) -> WcWidth { + let c32 = c as u32; + if c32 <= 0xffff { + return self.table[c32 as usize]; + } + WcWidth::from_char(c) + } +} + #[cfg(test)] mod test { use super::*;