1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
use crate::errors::*;

use super::placeholder::Placeholder;
use super::prefix::Prefix;
use super::unit::Unit;

#[derive(Debug, Clone)]
pub struct Value {
    unit: Unit,
    min_width: usize,
    icon: Option<String>,
    value: InternalValue,
}

#[derive(Debug, Clone)]
enum InternalValue {
    Text(String),
    Integer(i64),
    Float(f64),
}

fn format_number(
    raw_value: f64,
    min_width: usize,
    min_prefix: Prefix,
    unit: Unit,
    pad_with: char,
) -> String {
    let is_byte = unit.is_byte();

    let mut min_exp_level = match min_prefix {
        Prefix::Tera => 4,
        Prefix::Giga => 3,
        Prefix::Mega => 2,
        Prefix::Kilo => 1,
        Prefix::One => 0,
        Prefix::Milli => -1,
        Prefix::Micro => -2,
        Prefix::Nano => -3,
    };

    if is_byte {
        min_exp_level = min_exp_level.max(0);
    }

    let (mut value, mut prefix) = if !is_byte {
        let exp_level = (raw_value.log10().div_euclid(3.) as i32).clamp(min_exp_level, 4);
        let value = raw_value / (10f64).powi(exp_level * 3);

        let prefix = match exp_level {
            4 => Prefix::Tera,
            3 => Prefix::Giga,
            2 => Prefix::Mega,
            1 => Prefix::Kilo,
            0 => Prefix::One,
            -1 => Prefix::Milli,
            -2 => Prefix::Micro,
            _ => Prefix::Nano,
        };
        (value, prefix)
    } else {
        let exp_level = (raw_value.log2().div_euclid(10.) as i32).clamp(min_exp_level, 4);
        let value = raw_value / (2f64).powi(exp_level * 10);

        let prefix = match exp_level {
            4 => Prefix::Tera,
            3 => Prefix::Giga,
            2 => Prefix::Mega,
            1 => Prefix::Kilo,
            _ => Prefix::One,
        };
        (value, prefix)
    };

    if unit == Unit::Percents {
        value = raw_value;
        prefix = Prefix::One;
    }

    // The length of the integer part of a number
    let digits = (value.log10().floor() + 1.0).max(1.0) as isize;
    // How many characters is left for "." and the fractional part?
    match min_width as isize - digits {
        // No characters left
        x if x <= 0 => format!("{:.0}{}", value, prefix),
        // Only one character -> pad text to the right
        x if x == 1 => format!("{}{:.0}{}", pad_with, value, prefix),
        // There is space for fractional part
        rest => format!("{:.*}{}", (rest as usize) - 1, value, prefix),
    }
}

fn format_bar(value: f64, length: usize) -> String {
    let value = value.clamp(0., 1.);
    let chars_to_fill = value * length as f64;
    (0..length)
        .map(|i| {
            let printed_chars = i as f64;
            let val = (chars_to_fill - printed_chars).clamp(0., 1.) * 8.;
            match val as usize {
                //TODO make those characters configurable?
                0 => ' ',
                1 => '\u{258f}',
                2 => '\u{258e}',
                3 => '\u{258d}',
                4 => '\u{258c}',
                5 => '\u{258b}',
                6 => '\u{258a}',
                7 => '\u{2589}',
                _ => '\u{2588}',
            }
        })
        .collect()
}

impl Value {
    // Constuctors
    pub fn from_string(text: String) -> Self {
        Self {
            icon: None,
            min_width: 0,
            unit: Unit::None,
            value: InternalValue::Text(text),
        }
    }
    pub fn from_integer(value: i64) -> Self {
        Self {
            icon: None,
            min_width: 2,
            unit: Unit::None,
            value: InternalValue::Integer(value),
        }
    }
    pub fn from_float(value: f64) -> Self {
        Self {
            icon: None,
            min_width: 3,
            unit: Unit::None,
            value: InternalValue::Float(value),
        }
    }

    // Set options
    pub fn icon(mut self, icon: String) -> Self {
        self.icon = Some(icon);
        self
    }
    //pub fn min_width(mut self, min_width: usize) -> Self {
    //self.min_width = min_width;
    //self
    //}

    // Units
    pub fn bytes(mut self) -> Self {
        self.unit = Unit::Bytes;
        self
    }
    pub fn bits(mut self) -> Self {
        self.unit = Unit::Bits;
        self
    }
    pub fn degrees(mut self) -> Self {
        self.unit = Unit::Degrees;
        self
    }
    pub fn percents(mut self) -> Self {
        self.unit = Unit::Percents;
        self
    }
    pub fn seconds(mut self) -> Self {
        self.unit = Unit::Seconds;
        self
    }
    pub fn watts(mut self) -> Self {
        self.unit = Unit::Watts;
        self
    }
    pub fn hertz(mut self) -> Self {
        self.unit = Unit::Hertz;
        self
    }

    //TODO impl Display
    pub fn format(&self, var: &Placeholder) -> Result<String> {
        let min_width = var.min_width.unwrap_or(self.min_width);
        let pad_with = var.pad_with.unwrap_or(' ');
        let unit = var.unit.unwrap_or(self.unit);

        // Draw the bar instead of usual formatting if `bar_max_value` is set
        // (olny for integers and floats)
        if let Some(bar_max_value) = var.bar_max_value {
            match self.value {
                InternalValue::Integer(i) => {
                    return Ok(format_bar(i as f64 / bar_max_value, min_width))
                }
                InternalValue::Float(f) => return Ok(format_bar(f / bar_max_value, min_width)),
                _ => (),
            }
        }

        let value = match self.value {
            InternalValue::Text(ref text) => {
                let mut text = text.clone();
                let text_len = text.len();
                for _ in text_len..min_width {
                    text.push(pad_with);
                }
                if let Some(max_width) = var.max_width {
                    text.truncate(max_width);
                }
                text
            }
            InternalValue::Integer(value) => {
                let value = (value as f64 * self.unit.convert(unit)?) as i64;

                let text = value.to_string();
                let mut retval = String::new();
                let text_len = text.len();
                for _ in text_len..min_width {
                    retval.push(pad_with);
                }
                retval.push_str(&text);
                retval
            }
            InternalValue::Float(value) => {
                let value = value * self.unit.convert(unit)?;

                format_number(
                    value,
                    min_width,
                    var.min_prefix.unwrap_or(Prefix::Nano),
                    unit,
                    pad_with,
                )
            }
        };

        let icon_str = self.icon.as_deref().unwrap_or("");

        let unit = unit.to_string();
        let unit_str = if var.unit_hidden { "" } else { unit.as_str() };

        Ok(format!("{}{}{}", icon_str, value, unit_str))
    }
}