/* * asklyphe-frontend unit_converter.rs * - wrapper for the unit converter library * * Copyright (C) 2025 Real Microsoft, LLC * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ use std::str::FromStr; use unit_converter::length_units::{LengthUnit, LENGTH_NAMES}; use unit_converter::unit_defs::{BestUnit, ConvertTo, FromUnitName, UnitName}; use unit_converter::{parse_number, remove_leading_conversion_word}; #[derive(Clone, Debug)] pub struct UnitConversion { pub value: String, pub unit_a: String, pub equals: String, pub unit_b: String, } pub fn convert_unit(query_text: &str) -> Option { let (number, remainder) = parse_number(query_text); if number.is_nan() { return None; } let og_number = number.clone(); let unit = LengthUnit::parse(remainder); unit.as_ref()?; let (unit_a, remainder) = unit.unwrap(); let remainder = remove_leading_conversion_word(&remainder); if let Some((unit_b, _)) = LengthUnit::parse(remainder) { let conversion = unit_a.convert_to(number, unit_b); let approx = f64::from_str(&format!("{}", conversion)).unwrap(); let approx_og = f64::from_str(&format!("{}", og_number)).unwrap(); Some(UnitConversion { value: format!("{}", approx_og), unit_a: unit_a.unit_name(og_number), equals: format!("{}", approx), unit_b: unit_b.unit_name(conversion), }) } else { let best_unit = LengthUnit::best_unit(unit_a, number.clone()); let conversion = unit_a.convert_to(number, best_unit); let approx = f64::from_str(&format!("{}", conversion)).unwrap(); let approx_og = f64::from_str(&format!("{}", og_number)).unwrap(); Some(UnitConversion { value: format!("{}", approx_og), unit_a: unit_a.unit_name(og_number), equals: format!("{}", approx), unit_b: best_unit.unit_name(conversion), }) } }