use thiserror::Error;
#[derive(Debug, Error, PartialEq)]
pub enum TemperatureError {
#[error("temperatura abaixo do zero absoluto")]
BelowAbsoluteZero,
}
pub fn celsius_to_kelvin(celsius: f64) -> Result<f64, TemperatureError> {
if celsius < -273.15 {
Err(TemperatureError::BelowAbsoluteZero)
} else {
Ok(celsius + 273.15)
}
}
pub fn kelvin_to_celsius(kelvin: f64) -> Result<f64, TemperatureError> {
if kelvin <= 0.0 {
Err(TemperatureError::BelowAbsoluteZero)
} else {
Ok(kelvin - 273.15)
}
}
pub fn celsius_to_fahrenheit(celsius: f64) -> f64 {
celsius * 9.0 / 5.0 + 32.0
}
pub fn fahrenheit_to_celsius(fahrenheit: f64) -> f64 {
(fahrenheit - 32.0) * 5.0 / 9.0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_celsius_kelvin() {
assert_eq!(celsius_to_kelvin(0.0).unwrap(), 273.15);
assert_eq!(celsius_to_kelvin(-273.15).unwrap(), 0.0);
assert_eq!(
celsius_to_kelvin(-300.0),
Err(TemperatureError::BelowAbsoluteZero)
);
}
#[test]
fn test_kelvin_celsius() {
assert_eq!(kelvin_to_celsius(273.15).unwrap(), 0.0);
assert_eq!(
kelvin_to_celsius(0.0),
Err(TemperatureError::BelowAbsoluteZero)
);
}
#[test]
fn test_fahrenheit_celsius_roundtrip() {
let c = 25.0;
let f = celsius_to_fahrenheit(c);
assert!((fahrenheit_to_celsius(f) - c).abs() < 1e-10);
}
}