pub trait TemperatureConversion {
fn kelvin_to_celsius(&self) -> Self
where
Self: Sized;
fn kelvin_to_fahrenheit(&self) -> Self
where
Self: Sized;
fn celsius_to_kelvin(&self) -> Self
where
Self: Sized;
fn celsius_to_fahrenheit(&self) -> Self
where
Self: Sized;
fn fahrenheit_to_kelvin(&self) -> Self
where
Self: Sized;
fn fahrenheit_to_celsius(&self) -> Self
where
Self: Sized;
}
impl TemperatureConversion for f32 {
fn kelvin_to_celsius(&self) -> Self {
self - 273.15
}
fn kelvin_to_fahrenheit(&self) -> Self {
(self - 273.15) * (9_f32 / 5_f32) + 32_f32
}
fn celsius_to_kelvin(&self) -> Self {
self + 273.15
}
fn celsius_to_fahrenheit(&self) -> Self {
self * (9_f32 / 5_f32) + 32_f32
}
fn fahrenheit_to_kelvin(&self) -> Self {
(self - 32_f32) * (5_f32 / 9_f32) + 273.15
}
fn fahrenheit_to_celsius(&self) -> Self {
(self - 32_f32) * (5_f32 / 9_f32)
}
}
impl TemperatureConversion for f64 {
fn kelvin_to_celsius(&self) -> Self {
self - 273.15
}
fn kelvin_to_fahrenheit(&self) -> Self {
(self - 273.15) * (9_f64 / 5_f64) + 32_f64
}
fn celsius_to_kelvin(&self) -> Self {
self + 273.15
}
fn celsius_to_fahrenheit(&self) -> Self {
self * (9_f64 / 5_f64) + 32_f64
}
fn fahrenheit_to_kelvin(&self) -> Self {
(self - 32_f64) * (5_f64 / 9_f64) + 273.15
}
fn fahrenheit_to_celsius(&self) -> Self {
(self - 32_f64) * (5_f64 / 9_f64)
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[rstest]
#[case(0.0, -273.15)]
#[case(100.0, -173.15)]
#[case(1000.0, 726.85)]
#[case(5000.0, 4726.85)]
#[case(69_420.0, 69_146.85)]
fn test_kelvin_to_celsius(#[case] input: f32, #[case] output: f32) {
assert_eq!(input.kelvin_to_celsius(), output);
}
#[rstest]
#[case(0.0, -459.66998)]
#[case(100.0, -279.66998)]
#[case(1000.0, 1340.33)]
#[case(5000.0, 8540.33)]
#[case(69_420.0, 124_496.33)]
fn test_kelvin_to_fahrenheit(#[case] input: f32, #[case] output: f32) {
assert_eq!(input.kelvin_to_fahrenheit(), output);
}
#[rstest]
#[case(0.0, 273.15)]
#[case(100.0, 373.15)]
#[case(1000.0, 1273.15)]
#[case(5000.0, 5273.15)]
#[case(69_420.0, 69_693.15)]
fn test_celsius_to_kelvin(#[case] input: f32, #[case] output: f32) {
assert_eq!(input.celsius_to_kelvin(), output);
}
#[rstest]
#[case(0.0, 32.0)]
#[case(100.0, 212.0)]
#[case(1000.0, 1832.0)]
#[case(5000.0, 9032.0)]
#[case(69_420.0, 124_988.0)]
fn test_celsius_to_fahrenheit(#[case] input: f32, #[case] output: f32) {
assert_eq!(input.celsius_to_fahrenheit(), output);
}
#[rstest]
#[case(0.0, 255.37222)]
#[case(100.0, 310.92776)]
#[case(1000.0, 810.92786)]
#[case(5000.0, 3033.1501)]
#[case(69_420.0, 38_822.04)]
fn test_fahrenheit_to_kelvin(#[case] input: f32, #[case] output: f32) {
assert_eq!(input.fahrenheit_to_kelvin(), output);
}
#[rstest]
#[case(0.0, -17.777_779)]
#[case(100.0, 37.77778)]
#[case(1000.0, 537.77783)]
#[case(5000.0, 2_760.0002)]
#[case(69_420.0, 38_548.89)]
fn test_fahrenheit_to_celsius(#[case] input: f32, #[case] output: f32) {
assert_eq!(input.fahrenheit_to_celsius(), output);
}
}