temperature_converter 0.1.2

Biblioteca Rust para converter temperaturas entre Celsius, Fahrenheit e Kelvin
Documentation
//! temperature_converter — biblioteca para conversão de temperaturas.
//!
//! # Exemplos
//!
//! ```
//! use temperature_converter::{celsius_to_kelvin, fahrenheit_to_celsius};
//!
//! assert_eq!(celsius_to_kelvin(0.0).unwrap(), 273.15);
//! // função que retorna f64 puro, não Result:
//! assert_eq!(fahrenheit_to_celsius(32.0), 0.0);
//! ```

use thiserror::Error;

/// Erros possíveis ao converter temperaturas
#[derive(Debug, Error, PartialEq)]
pub enum TemperatureError {
    /// Quando valor em Celsius está abaixo do zero absoluto (-273.15 °C)
    #[error("temperatura abaixo do zero absoluto")]
    BelowAbsoluteZero,
}

/// Converte Celsius para Kelvin.
///
/// # Erro
/// Retorna [`TemperatureError::BelowAbsoluteZero`] se `celsius < -273.15`.
pub fn celsius_to_kelvin(celsius: f64) -> Result<f64, TemperatureError> {
    if celsius < -273.15 {
        Err(TemperatureError::BelowAbsoluteZero)
    } else {
        Ok(celsius + 273.15)
    }
}

/// Converte Kelvin para Celsius.
///
/// # Erro
/// Retorna [`TemperatureError::BelowAbsoluteZero`] se `kelvin <= 0.0`.
pub fn kelvin_to_celsius(kelvin: f64) -> Result<f64, TemperatureError> {
    if kelvin <= 0.0 {
        Err(TemperatureError::BelowAbsoluteZero)
    } else {
        Ok(kelvin - 273.15)
    }
}

/// Converte Celsius para Fahrenheit.
///
/// Fórmula: °F = °C × 9/5 + 32
pub fn celsius_to_fahrenheit(celsius: f64) -> f64 {
    celsius * 9.0 / 5.0 + 32.0
}

/// Converte Fahrenheit para Celsius.
///
/// Fórmula: °C = (°F − 32) × 5/9
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);
    }
}