embedded-unit-converter/src/lib.rs

65 lines
1.4 KiB
Rust
Raw Normal View History

#![feature(specialization)]
2019-11-05 22:29:47 -05:00
#[macro_use]
extern crate pyo3;
use pyo3::prelude::*;
2019-11-06 17:42:41 -05:00
#[pyclass(module = "unit_converter")]
struct Temperature {
celsius: f32,
}
#[pymethods]
impl Temperature {
#[new]
fn new(obj: &PyRawObject, temperature: f32) {
obj.init(Temperature {
celsius: temperature,
});
}
fn to_fahrenheit(&self) -> f32 {
self.celsius * 1.8 + 32.0
}
fn windchill(&self, wind_speed_kph: f32) -> f32 {
13.12 + (0.6215 * self.celsius) - (11.37 * wind_speed_kph.powf(0.16))
+ (0.3965 * self.celsius * wind_speed_kph.powf(0.16))
}
}
// TODO: Add a test that -20 C and 32 kph feels like -32.9
#[pyfunction]
2019-11-06 17:38:19 -05:00
fn convert_to_fahrenheit(celsius: f32) -> f32 {
celsius * 1.8 + 32.0
}
2019-11-05 22:29:47 -05:00
#[pyfunction]
2019-11-06 17:38:19 -05:00
fn batch_convert_to_fahrenheit(celsius: Vec<f32>) -> Vec<f32> {
2019-11-05 22:29:47 -05:00
celsius
.iter()
2019-11-06 17:38:19 -05:00
.map(|temperature| convert_to_fahrenheit(temperature.clone()))
2019-11-05 22:29:47 -05:00
.collect()
}
#[pymodule]
fn unit_converter(_py: Python, m: &PyModule) -> PyResult<()> {
2019-11-06 17:38:19 -05:00
m.add_wrapped(wrap_pyfunction!(convert_to_fahrenheit))?;
m.add_wrapped(wrap_pyfunction!(batch_convert_to_fahrenheit))?;
2019-11-06 17:42:41 -05:00
m.add_class::<Temperature>()?;
Ok(())
}
#[cfg(test)]
mod tests {
2019-11-06 17:38:19 -05:00
use super::convert_to_fahrenheit;
#[test]
fn conversion_celsius_to_fahrenheit() {
2019-11-06 17:38:19 -05:00
assert_eq!(convert_to_fahrenheit(25.0), 77.0);
}
2019-02-06 08:17:16 -05:00
}