aboutsummaryrefslogtreecommitdiffstats
path: root/src/unit_of_measurement.rs
blob: ce459bfecbd24ef5e10873267d23c2a7c7f9d4cb (plain) (blame)
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
pub trait UnitOfMeasurement {
    type Unit;

    fn from_unit(unit: Self::Unit, n: i32) -> Self;
    fn as_unit(&self, unit: Self::Unit) -> i32;
}

pub mod pressure {
    use super::UnitOfMeasurement;

    #[derive(Default, Clone)]
    pub struct Pressure(i32);

    #[derive(Copy, Clone)]
    pub enum Unit {
        Pascal = 1,
        KiloPascal = 1000,
    }

    impl Unit {
        // Pseudo iter::Cycle behavior.
        pub fn next(&mut self) {
            match self {
                Unit::Pascal => {
                    *self = Unit::KiloPascal;
                }
                Unit::KiloPascal => {
                    *self = Unit::Pascal;
                }
            }
        }
    }

    impl ToString for Unit {
        fn to_string(&self) -> String {
            match self {
                Self::Pascal => String::from("Pa"),
                Self::KiloPascal => String::from("kPa"),
            }
        }
    }

    impl UnitOfMeasurement for Pressure {
        type Unit = Unit;

        fn from_unit(unit: Self::Unit, n: i32) -> Self {
            Self(n * unit as i32)
        }

        fn as_unit(&self, unit: Self::Unit) -> i32 {
            self.0 / unit as i32
        }
    }
}