Debian Codegraph @

src/app/data/temperature.rs

raw symbols SCIP
1 //! Code around temperature data.
2
3 use std::{fmt::Display, str::FromStr};
4
5 #[derive(Clone, Debug, Copy, PartialEq, Eq, Default)]
6 pub enum TemperatureType {
7 #[default]
8 Celsius,
9 Kelvin,
10 Fahrenheit,
11 }
12
13 impl FromStr for TemperatureType {
14 type Err = String;
15
16 fn from_str(s: &str) -> Result<Self, Self::Err> {
17 match s {
18 "fahrenheit" | "f" => Ok(TemperatureType::Fahrenheit),
19 "kelvin" | "k" => Ok(TemperatureType::Kelvin),
20 "celsius" | "c" => Ok(TemperatureType::Celsius),
21 _ => Err(format!(
22 "'{s}' is an invalid temperature type, use one of: [kelvin, k, celsius, c, fahrenheit, f]."
23 )),
24 }
25 }
26 }
27
28 impl TemperatureType {
29 /// Return the unit string.
30 pub fn unit(&self) -> &'static str {
31 match self {
32 TemperatureType::Celsius => "Β°C",
33 TemperatureType::Kelvin => "K",
34 TemperatureType::Fahrenheit => "Β°F",
35 }
36 }
37
38 /// Given a temperature in Celsius, convert it if necessary for a different
39 /// unit.
40 pub fn convert_temp_unit(&self, celsius: f32) -> TypedTemperature {
41 match self {
42 TemperatureType::Celsius => TypedTemperature::Celsius(celsius.ceil() as u32),
43 TemperatureType::Kelvin => TypedTemperature::Kelvin((celsius + 273.15).ceil() as u32),
44 TemperatureType::Fahrenheit => {
45 TypedTemperature::Fahrenheit(((celsius * (9.0 / 5.0)) + 32.0).ceil() as u32)
46 }
47 }
48 }
49
50 /// Given a temperature in Celsius, convert it if necessary for a different
51 /// unit as a bare float.
52 pub fn convert_temp_unit_float(&self, celsius: f32) -> f32 {
53 match self {
54 TemperatureType::Celsius => celsius,
55 TemperatureType::Kelvin => celsius + 273.15,
56 TemperatureType::Fahrenheit => celsius * (9.0 / 5.0) + 32.0,
57 }
58 }
59 }
60
61 /// A temperature and its type.
62 #[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Ord)]
63 pub enum TypedTemperature {
64 Celsius(u32),
65 Kelvin(u32),
66 Fahrenheit(u32),
67 }
68
69 impl Display for TypedTemperature {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 match self {
72 TypedTemperature::Celsius(val) => write!(f, "{val}Β°C"),
73 TypedTemperature::Kelvin(val) => write!(f, "{val}K"),
74 TypedTemperature::Fahrenheit(val) => write!(f, "{val}Β°F"),
75 }
76 }
77 }
78
79 #[cfg(test)]
80 mod test {
81 use super::*;
82
83 #[test]
84 fn temp_conversions() {
85 const TEMP: f32 = 100.0;
86
87 assert_eq!(
88 TemperatureType::Celsius.convert_temp_unit(TEMP),
89 TypedTemperature::Celsius(TEMP as u32),
90 );
91
92 assert_eq!(
93 TemperatureType::Kelvin.convert_temp_unit(TEMP),
94 TypedTemperature::Kelvin(373.15_f32.ceil() as u32)
95 );
96
97 assert_eq!(
98 TemperatureType::Fahrenheit.convert_temp_unit(TEMP),
99 TypedTemperature::Fahrenheit(212)
100 );
101 }
102 }