Document WidthDB

This commit is contained in:
Joscha 2022-05-28 10:14:15 +02:00
parent 79e8813884
commit 833defd1ce
3 changed files with 17 additions and 0 deletions

View file

@ -8,6 +8,7 @@ use crossterm::QueueableCommand;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
/// Measures and stores the with (in terminal coordinates) of graphemes.
#[derive(Debug, Default)]
pub struct WidthDB {
known: HashMap<String, u8>,
@ -15,6 +16,10 @@ pub struct WidthDB {
}
impl WidthDB {
/// Determine the width of a string based on its graphemes.
///
/// If the width of a grapheme has not been measured yet, it is estimated
/// using the Unicode Standard Annex #11.
pub fn width(&mut self, s: &str) -> u8 {
let mut total = 0;
for grapheme in s.graphemes(true) {
@ -28,10 +33,18 @@ impl WidthDB {
total
}
/// Whether any new graphemes have been seen since the last time
/// [`Self::measure_widths`] was called.
pub fn measuring_required(&self) -> bool {
!self.requested.is_empty()
}
/// Measure the width of all new graphemes that have been seen since the
/// last time this function was called.
///
/// This function measures the actual width of graphemes by writing them to
/// the terminal. After it finishes, the terminal's contents should be
/// assumed to be garbage and a full redraw should be performed.
pub fn measure_widths(&mut self, out: &mut impl Write) -> io::Result<()> {
for grapheme in self.requested.drain() {
out.queue(Clear(ClearType::All))?