91 lines
2 KiB
Rust
91 lines
2 KiB
Rust
|
use crate::units::{Metric, MetricQuantity, NonMetric, NonMetricQuantity};
|
||
|
|
||
|
struct Conversion {
|
||
|
from: f64,
|
||
|
to: MetricQuantity,
|
||
|
}
|
||
|
|
||
|
fn get_conversion(unit: NonMetric) -> Conversion {
|
||
|
match unit {
|
||
|
// Length
|
||
|
NonMetric::Foot => Conversion {
|
||
|
from: 10_000.0,
|
||
|
to: MetricQuantity { amount: 3048.0, unit: Metric::Metre },
|
||
|
},
|
||
|
NonMetric::Inch => Conversion {
|
||
|
from: 10_000.0,
|
||
|
to: MetricQuantity { amount: 254.0, unit: Metric::Metre },
|
||
|
},
|
||
|
NonMetric::Yard => Conversion {
|
||
|
from: 10_000.0,
|
||
|
to: MetricQuantity { amount: 9144.0, unit: Metric::Metre },
|
||
|
},
|
||
|
NonMetric::Mile => Conversion {
|
||
|
from: 1_000.0,
|
||
|
to: MetricQuantity { amount: 1609344.0, unit: Metric::Metre },
|
||
|
},
|
||
|
// Weight
|
||
|
NonMetric::Ounce => Conversion {
|
||
|
from: 1_000_000_000.0,
|
||
|
to: MetricQuantity { amount: 28349523125.0, unit: Metric::Gram },
|
||
|
},
|
||
|
NonMetric::Pound => Conversion {
|
||
|
from: 100_000.0,
|
||
|
to: MetricQuantity { amount: 45359237.0, unit: Metric::Gram },
|
||
|
},
|
||
|
NonMetric::Stone => Conversion {
|
||
|
from: 100_000.0,
|
||
|
to: MetricQuantity { amount: 635029318.0, unit: Metric::Gram },
|
||
|
},
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub fn convert(from: NonMetricQuantity) -> MetricQuantity {
|
||
|
let conversion = get_conversion(from.unit);
|
||
|
let amount = from.amount * conversion.to.amount / conversion.from;
|
||
|
let unit = conversion.to.unit;
|
||
|
MetricQuantity { amount, unit }
|
||
|
}
|
||
|
|
||
|
#[cfg(test)]
|
||
|
mod test {
|
||
|
use super::*;
|
||
|
|
||
|
struct Test(NonMetric, f64);
|
||
|
|
||
|
fn run_tests(tests: &[Test], unit: Metric) {
|
||
|
for test in tests {
|
||
|
let from = NonMetricQuantity {
|
||
|
amount: 1.0,
|
||
|
unit: test.0,
|
||
|
};
|
||
|
let to = MetricQuantity {
|
||
|
amount: test.1,
|
||
|
unit: unit,
|
||
|
};
|
||
|
assert_eq!(convert(from), to);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
#[test]
|
||
|
fn length() {
|
||
|
let tests = [
|
||
|
Test(NonMetric::Inch, 0.0254),
|
||
|
Test(NonMetric::Foot, 0.3048),
|
||
|
Test(NonMetric::Yard, 0.9144),
|
||
|
Test(NonMetric::Mile, 1609.344),
|
||
|
];
|
||
|
run_tests(&tests, Metric::Metre);
|
||
|
}
|
||
|
|
||
|
#[test]
|
||
|
fn weight() {
|
||
|
let tests = [
|
||
|
Test(NonMetric::Ounce, 28.349523125),
|
||
|
Test(NonMetric::Pound, 453.59237),
|
||
|
Test(NonMetric::Stone, 6350.29318),
|
||
|
];
|
||
|
run_tests(&tests, Metric::Gram);
|
||
|
}
|
||
|
}
|