mechanical_engineering/units/
pressure.rs

1use crate::errors::EngCalcError;
2
3#[derive(Debug, Clone)]
4pub enum Unit {
5    Psi,
6    Kpa,
7    Pa,
8    Bar,
9}
10
11fn conversion_kpa(unit: &Unit) -> f32 {
12    match unit {
13        Unit::Psi => 0.14503774,
14        Unit::Kpa => 1.0,
15        Unit::Pa => 1000.0,
16        Unit::Bar => 0.01,
17    }
18}
19
20fn convert(from_value: f32, from_unit: &Unit, to_unit: &Unit) -> f32 {
21    let from_conversion = conversion_kpa(from_unit);
22    let to_conversion = conversion_kpa(to_unit);
23    from_value * to_conversion / from_conversion
24}
25
26#[derive(Debug, Clone)]
27pub struct Pressure {
28    value: f32,
29    unit: Unit,
30    absolute: bool,
31}
32
33impl Pressure {
34    pub fn new(value: f32, unit: Unit, absolute: bool) -> Self {
35        Pressure {
36            value,
37            unit,
38            absolute,
39        }
40    }
41
42    pub fn value(&self) -> f32 {
43        self.value
44    }
45
46    pub fn unit(&self) -> Unit {
47        self.unit.clone()
48    }
49
50    pub fn is_absolute(&self) -> bool {
51        self.absolute
52    }
53
54    pub fn convert_unit(&mut self, new_unit: Unit) {
55        let new_value = convert(self.value, &self.unit, &new_unit);
56        self.value = new_value;
57        self.unit = new_unit;
58    }
59
60    pub fn pressure_ratio(p1: &Pressure, p2: &Pressure) -> Result<f32, EngCalcError> {
61        if !p1.is_absolute() || !p2.is_absolute() {
62            return Err(EngCalcError::InvalidUnits(
63                "Pressure ratio calculation must use absolute units.",
64            ));
65        }
66
67        let p1_value_kpa = convert(p1.value, &p1.unit, &Unit::Kpa);
68        let p2_value_kpa = convert(p2.value, &p2.unit, &Unit::Kpa);
69        Ok(p2_value_kpa / p1_value_kpa)
70    }
71
72    pub fn add_pressure(self, other: &Pressure) -> Self {
73        let p2_value_conv = convert(other.value, &other.unit, &self.unit());
74        let total_pressure = self.value() + p2_value_conv;
75        Pressure {
76            value: total_pressure,
77            unit: self.unit,
78            absolute: self.absolute,
79        }
80    }
81
82    pub fn subtract_pressure(self, other: &Pressure) -> Self {
83        let p2_value_conv = convert(other.value, &other.unit, &self.unit());
84        let total_pressure = self.value() - p2_value_conv;
85        Pressure {
86            value: total_pressure,
87            unit: self.unit,
88            absolute: self.absolute,
89        }
90    }
91}