mechanical_engineering/units/
temperature.rs1#[derive(Debug, Clone)]
2pub enum Unit {
3 R,
4 K,
5 C,
6 F,
7}
8
9fn convert(from_value: f32, from_unit: &Unit, to_unit: &Unit) -> f32 {
10 match from_unit {
11 Unit::R => match to_unit {
12 Unit::R => from_value,
13 Unit::K => from_value * 5.0 / 9.0,
14 Unit::F => from_value - 459.67,
15 Unit::C => from_value * 5.0 / 9.0 - 273.15,
16 },
17 Unit::K => match to_unit {
18 Unit::R => from_value * 9.0 / 5.0,
19 Unit::K => from_value,
20 Unit::F => from_value * 9.0 / 5.0 - 459.67,
21 Unit::C => from_value - 273.15,
22 },
23 Unit::F => match to_unit {
24 Unit::R => from_value + 459.67,
25 Unit::K => (from_value + 459.67) * 5.0 / 9.0,
26 Unit::F => from_value,
27 Unit::C => (from_value - 32.0) * 5.0 / 9.0,
28 },
29 Unit::C => match to_unit {
30 Unit::R => (from_value + 273.15) * 9.0 / 5.0,
31 Unit::K => from_value + 273.15,
32 Unit::F => from_value * 9.0 / 5.0 + 32.0,
33 Unit::C => from_value,
34 },
35 }
36}
37
38#[derive(Debug, Clone)]
39pub struct Temperature {
40 value: f32,
41 unit: Unit,
42}
43
44impl Temperature {
45 pub fn new(value: f32, unit: Unit) -> Self {
46 Temperature { value, unit }
47 }
48
49 pub fn value(&self) -> f32 {
50 self.value
51 }
52
53 pub fn unit(&self) -> Unit {
54 self.unit.clone()
55 }
56
57 pub fn convert_unit(&mut self, new_unit: Unit) {
58 let new_value = convert(self.value, &self.unit, &new_unit);
59 self.value = new_value;
60 self.unit = new_unit;
61 }
62
63 pub fn ratio(t1: &Temperature, t2: &Temperature) -> f32 {
64 let t1_value_k = convert(t1.value, &t1.unit, &Unit::K);
65 let t2_value_k = convert(t2.value, &t2.unit, &Unit::K);
66 t2_value_k / t1_value_k
67 }
68
69 pub fn add_temperature(self, other: &Temperature) -> Self {
70 Temperature {
71 value: self.value() + scale_temperature(other.value(), self.unit(), other.unit()),
72 unit: self.unit,
73 }
74 }
75
76 pub fn subtract_temperature(self, other: &Temperature) -> Self {
77 Temperature {
78 value: self.value() - scale_temperature(other.value(), self.unit(), other.unit()),
79 unit: self.unit,
80 }
81 }
82}
83
84fn scale_temperature(value: f32, self_unit: Unit, other_unit: Unit) -> f32 {
85 match self_unit {
86 Unit::K => match other_unit {
87 Unit::K => value,
88 Unit::C => value,
89 Unit::F => value * 5.0 / 9.0,
90 Unit::R => value * 5.0 / 9.0,
91 },
92 Unit::C => match other_unit {
93 Unit::K => value,
94 Unit::C => value,
95 Unit::F => value * 5.0 / 9.0,
96 Unit::R => value * 5.0 / 9.0,
97 },
98 Unit::R => match other_unit {
99 Unit::K => value * 9.0 / 5.0,
100 Unit::C => value * 9.0 / 5.0,
101 Unit::F => value,
102 Unit::R => value,
103 },
104 Unit::F => match other_unit {
105 Unit::K => value * 9.0 / 5.0,
106 Unit::C => value * 9.0 / 5.0,
107 Unit::F => value,
108 Unit::R => value,
109 },
110 }
111}