prodash/unit/
human.rs

1use std::{fmt, fmt::Debug, hash::Hasher};
2
3pub use human_format::{Formatter, Scales};
4
5use crate::{progress::Step, unit::DisplayValue};
6
7/// A helper for formatting numbers in a format easily read by humans in renderers, as in `2.54 million objects`
8#[derive(Debug)]
9pub struct Human {
10    /// The name of the represented unit, like 'items' or 'objects'.
11    pub name: &'static str,
12    /// The formatter to format the actual numbers.
13    pub formatter: Formatter,
14}
15
16impl Human {
17    /// A convenience method to create a new new instance and its `formatter` and `name` fields.
18    pub fn new(formatter: Formatter, name: &'static str) -> Self {
19        Human { name, formatter }
20    }
21    fn format_bytes(&self, w: &mut dyn fmt::Write, value: Step) -> fmt::Result {
22        let string = self.formatter.format(value as f64);
23        for token in string.split(' ') {
24            w.write_str(token)?;
25        }
26        Ok(())
27    }
28}
29
30impl DisplayValue for Human {
31    fn display_current_value(&self, w: &mut dyn fmt::Write, value: Step, _upper: Option<Step>) -> fmt::Result {
32        self.format_bytes(w, value)
33    }
34
35    fn display_upper_bound(&self, w: &mut dyn fmt::Write, upper_bound: Step, _value: Step) -> fmt::Result {
36        self.format_bytes(w, upper_bound)
37    }
38
39    fn dyn_hash(&self, state: &mut dyn Hasher) {
40        state.write(self.name.as_bytes());
41        state.write_u8(0);
42    }
43
44    fn display_unit(&self, w: &mut dyn fmt::Write, _value: Step) -> fmt::Result {
45        w.write_str(self.name)
46    }
47}