use super::units::{Units, format_quantity};
use crate::{Context, Outcome, Plugin, number, re};
#[derive(Default)]
pub struct Physics {
units: Units,
}
impl Plugin for Physics {
fn evaluate(&self, input: &str, _: &Context) -> Outcome {
if let Some(c) =
re!(r"(?i)^(?:ppi|density) of (.+?)(?: device| screen| display)? at (\d+)x(\d+)$")
.captures(input)
{
let q = self.units.quantity(&c[1])?;
if q.unit.dimension != [1, 0, 0, 0, 0, 0, 0, 0] {
return None;
}
let diagonal = q.base / 0.0254;
return Some(Ok(format!(
"{} PPI",
number(c[2].parse::<f64>().ok()?.hypot(c[3].parse().ok()?) / diagonal)
)));
}
if let Some(c) = re!(r"(?i)^pixels in (.+) at ([\d.]+) (?:ppi|dpi)$").captures(input) {
let q = self.units.quantity(&c[1])?;
if q.unit.dimension != [1, 0, 0, 0, 0, 0, 0, 0] {
return None;
}
return Some(Ok(format_quantity(
0.0254 / c[2].parse::<f64>().ok()? / q.unit.scale,
&q.unit,
)));
}
if let Some(c) = re!(r"(?i)^(.+) at ([\d.]+) rpm in (.+)$").captures(input) {
let q = self.units.quantity(&c[1])?;
let target = self.units.unit(&c[3])?;
let rate = c[2].parse::<f64>().ok()? * std::f64::consts::TAU / 60.0;
let (value, dimension) = if q.unit.dimension == [2, 1, -2, 0, 0, 0, 0, 0] {
(q.base * rate, [2, 1, -3, 0, 0, 0, 0, 0])
} else if q.unit.dimension == [2, 1, -3, 0, 0, 0, 0, 0] {
(q.base / rate, [2, 1, -2, 0, 0, 0, 0, 0])
} else {
return None;
};
return Some(if dimension == target.dimension {
Ok(format_quantity(value / target.scale, &target))
} else {
Err(crate::Error("internal_error".into()))
});
}
if let Some(c) = re!(r"(?i)^(.+) (?:to|in) (?:px|pixels) (?:at|with) ([\d.]+) (?:ppi|dpi)$")
.captures(input)
{
let q = self.units.quantity(&c[1])?;
if q.unit.dimension != [1, 0, 0, 0, 0, 0, 0, 0] {
return None;
}
return Some(Ok(format!(
"{}px",
number(q.base / 0.0254 * c[2].parse::<f64>().ok()?).replace(',', "")
)));
}
if let Some(c) = re!(r"(?i)^speed of (.+) (?:tyre|tire) at ([\d.]+) rpm$").captures(input) {
let q = self.units.quantity(&c[1])?;
if q.unit.dimension != [1, 0, 0, 0, 0, 0, 0, 0] {
return None;
}
let mph = q.base * std::f64::consts::PI * c[2].parse::<f64>().ok()? * 60.0 / 1609.344;
return Some(Ok(format!("{} mph", number(mph))));
}
if let Some(c) = re!(r"(?i)^(.+) for (.+)$").captures(input) {
let a = self.units.quantity(&c[1])?;
let b = self.units.quantity(&c[2])?;
if a.unit.dimension == [1, 0, -1, 0, 0, 0, 0, 0]
&& b.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0]
{
let base = if a.unit.symbol == "mph" {
"mi"
} else {
a.unit.symbol.split('/').next()?
};
let target = self.units.unit(base)?;
return Some(Ok(format_quantity(a.base * b.base / target.scale, &target)));
}
}
if let Some(c) = re!(r"(?i)^(.+) at ([\d.]+) rpm$").captures(input) {
let q = self.units.quantity(&c[1])?;
if q.unit.dimension != [2, 1, -3, 0, 0, 0, 0, 0] {
return None;
}
return Some(Ok(format!(
"{} N⋅m",
number(q.base / (c[2].parse::<f64>().ok()? * std::f64::consts::TAU / 60.0))
)));
}
None
}
}