pwr 0.2.2

Check power supplies of a system
Documentation
use crate::error::PwrError;
use colored::*;

/// Battery health.
///
/// This contains a floating point value between 0 and 1 and represents the amount of charge that
/// the battery can hold. A factory-new battery has a health of 1, meaning that all of the charge
/// it is supposed to hold is still available.
///
/// This value will steadily decrease as a battery ages. Note that for example a battery with a
/// health of 0.2 is drained about 5 times as quick as a new battery.
pub struct Health {
    value: f32,
}

impl Health {
    pub fn new(value: f32) -> Result<Self, PwrError> {
        if !(0.0..=1.0).contains(&value) {
            return Err(PwrError::InvalidHealth(value));
        }

        Ok(Health { value })
    }

    /// Return the batteries health as textual representation.
    ///
    /// Returns a short description of battery health (e.g. "Good", or "Poor").
    pub fn text(&self) -> String {
        let health_p = f32::round(self.value * 100.0) as u32;
        match health_p {
            0..=20 => "Very poor",
            21..=50 => "Poor",
            51..=70 => "Okay",
            71..=90 => "Good",
            91..=100 => "Excellent",
            _ => "Invalid",
        }
        .to_owned()
    }
}

impl std::fmt::Display for Health {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let soc_p: u32 = f32::round(self.value * 100.0) as u32;
        let string = format!("{:3} %", soc_p);
        let string = match soc_p {
            0..=20 => string.red().bold(),
            21..=50 => string.red(),
            51..=70 => string.yellow(),
            71..=90 => string.green(),
            91..=100 => string.green().bold(),
            _ => string.black().strikethrough(),
        };
        write!(f, "{}", string)
    }
}