papergrid/estimation/
width_func.rs

1//! A module which contains a [`WidthFunc`] trait and it's implementation [`CfgWidthFunction`]
2
3use crate::{
4    util::{string_width_multiline_tab, string_width_tab},
5    GridConfig,
6};
7
8/// A width function.
9pub trait WidthFunc {
10    /// Calculates a width of a string.
11    fn width(&self, text: &str) -> usize;
12    /// Calculates a width of a multiline string.
13    fn width_multiline(&self, text: &str) -> usize;
14}
15
16impl<W> WidthFunc for &W
17where
18    W: WidthFunc,
19{
20    fn width(&self, text: &str) -> usize {
21        W::width(self, text)
22    }
23
24    fn width_multiline(&self, text: &str) -> usize {
25        W::width_multiline(self, text)
26    }
27}
28
29/// A [`WidthFunc`] implementation which is used by [`Grid`].
30///
31/// [`Grid`]: crate::Grid
32#[derive(Debug, Default, Clone)]
33pub struct CfgWidthFunction {
34    tab_width: usize,
35}
36
37impl CfgWidthFunction {
38    /// Creates a [`CfgWidthFunction`] from [`GridConfig`].
39    pub fn from_cfg(cfg: &GridConfig) -> Self {
40        Self::new(cfg.get_tab_width())
41    }
42
43    /// Creates a [`CfgWidthFunction`] with a tab size.
44    pub fn new(tab_size: usize) -> Self {
45        Self {
46            tab_width: tab_size,
47        }
48    }
49}
50
51impl WidthFunc for CfgWidthFunction {
52    fn width(&self, text: &str) -> usize {
53        string_width_tab(text, self.tab_width)
54    }
55
56    fn width_multiline(&self, text: &str) -> usize {
57        string_width_multiline_tab(text, self.tab_width)
58    }
59}