source_span/
metrics.rs

1/// Default character metrics.
2pub static DEFAULT_METRICS: DefaultMetrics = DefaultMetrics::new();
3
4/// Gives the size of each character and tab stop length.
5///
6/// This is used to correctly compute spans in the source text,
7/// and render the text using a [`Formatter`](`crate::fmt::Formatter`).
8pub trait Metrics {
9	/// Get the size (width in columns) of a character.
10	fn char_width(&self, c: char) -> usize;
11
12	/// Get the tab stop length.
13	fn tab_stop(&self) -> usize;
14}
15
16/// Default metrics infos.
17///
18/// By default, tab stop length is 8, but it can be set using [`DefaultMetrics::with_tab_stop`].
19#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
20pub struct DefaultMetrics {
21	tab_stop: usize,
22}
23
24impl DefaultMetrics {
25	/// Create a new default metrics instance.
26	///
27	/// Tab stop length will be 8.
28	#[must_use]
29	pub const fn new() -> DefaultMetrics { Self::with_tab_stop(8) }
30
31	/// Create a new default metrics with a custom tab stop length.
32	#[must_use]
33	pub const fn with_tab_stop(tab_stop: usize) -> DefaultMetrics { DefaultMetrics { tab_stop } }
34}
35
36impl Metrics for DefaultMetrics {
37	fn char_width(&self, c: char) -> usize {
38		match c {
39			'\r' | '\n' => 0,
40			_ => 1,
41		}
42	}
43
44	fn tab_stop(&self) -> usize { self.tab_stop }
45}