From c65a817f96a537ab9477e6773037aba575142380 Mon Sep 17 00:00:00 2001 From: Dr Sohil Momin Date: Mon, 9 Nov 2026 11:59:01 +0000 Subject: [PATCH 1/2] feat(units): convert ten dimensions, and resolve the split instead of guessing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unit conversion knew length, mass and temperature, so `2 h in min`, `10 GB in MB`, `5 km/h in mph`, `3 tbsp in ml` and `1 bar in psi` all fell through the cascade to a web search. The table now carries a dimension with each factor — time, volume, area, speed, data, pressure and energy join the original three — and conversion requires the two units to share one. The amount side is parsed by resolution, not by cutting at a fixed column: - candidate connector splits are tried right to left, and the first one that resolves on both sides wins, so `10 in in cm` is ten inches into centimetres rather than a failed split on the first " in "; - a suffix is only accepted as a unit when a number (or an expression the calc engine already handles) sits in front of it, so `1e3 m in km` and `2*3 km in mi` work and `5min` is still minutes, not 5 metres + "in". Factors follow Numbat's unit definitions (MIT/Apache-2.0); only the physical constants are reused, credited in the source. No dependency added. --- README.md | 2 +- changes/units-ten-dimensions.md | 5 + docs/USER_GUIDE.md | 22 +- docs/index.html | 9 +- src/extras.rs | 468 ++++++++++++++++++++++++++------ 5 files changed, 411 insertions(+), 95 deletions(-) create mode 100644 changes/units-ten-dimensions.md diff --git a/README.md b/README.md index e4855e6..17220e1 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ desktop shortcut or global hotkey; it stays resident in the background and | 🪟 **Tray-resident, one keystroke** | Lives in the background; the shortcut **summons** the existing window instead of opening a duplicate | | 🧠 **Smart routing cascade** | math → unit conversion → existing path → PATH binary → web search | | 🧮 **Zero-dep calculator** | `+ - * / % ^ ( )` with unary minus, right-associative power, div/mod-by-zero guards | -| 📐 **Unit conversion** | `10 km in mi`, `100 f to c`, `5kg to lb` — length, mass, temperature | +| 📐 **Unit conversion** | `10 km in mi`, `2 h in min`, `10 GB in MB` — ten dimensions: length, mass, time, volume, area, speed, data, pressure, energy, temperature | | 🗂️ **Slash commands** | `/run` `/cmd` `/open` `/ls` `/find` `/web` `/calc` `/sys` `/help` `/clear` | | ⏱️ **Command history** | `↑`/`↓` (or `Ctrl+P`/`Ctrl+N`), persisted between runs | | 📋 **Copy without a clipboard crate** | `Ctrl+Y` copies the last result via OSC 52 — works over SSH | diff --git a/changes/units-ten-dimensions.md b/changes/units-ten-dimensions.md new file mode 100644 index 0000000..209f6f1 --- /dev/null +++ b/changes/units-ten-dimensions.md @@ -0,0 +1,5 @@ +--- +bump: minor +--- + +Unit conversion covers ten dimensions: time, volume, area, speed, data, pressure and energy join length, mass and temperature. `10 in in cm`, `1e3 m in km` and `2*3 km in mi` now parse instead of falling through to a web search. diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 5c631fb..d519132 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -49,9 +49,25 @@ on PATH as a binary? → spawn detached e.g. code . otherwise? → web search e.g. rust lifetimes ``` -Unit conversion understands length (`mm cm m km in ft yd mi nmi`), mass -(`mg g kg oz lb st t`) and temperature (`c f k`), and accepts long names -(`10 kilometres in miles`). +Unit conversion understands ten dimensions: + +| Dimension | Units | +|---|---| +| length | `mm cm m km in ft yd mi nmi` | +| mass | `mg g kg oz lb st t` | +| time | `ms s min h day week` | +| volume | `ml cl dl l m3 tsp tbsp floz cup pint quart gal` | +| area | `m2 km2 cm2 ha acre ft2 yd2 mi2` | +| speed | `m/s km/h mph kn ft/s` | +| data | `b kb mb gb tb` (decimal, 1 kB = 1000 B) and `kib mib gib tib` (binary) | +| pressure | `pa kpa mpa bar mbar atm psi mmhg torr` | +| energy | `j kj mj cal kcal wh kwh btu` | +| temperature | `c f k` | + +Long names work (`10 kilometres in miles`, `2 hours in minutes`). The amount on +the left may be a literal, an exponent (`1e3 m in km`) or an expression +(`2*3 km in mi`). A unit only converts inside its own dimension: `10 km in kg` +is not a conversion, and falls through to the next step of the cascade. ## 4. Slash commands diff --git a/docs/index.html b/docs/index.html index 3133c84..0a73091 100644 --- a/docs/index.html +++ b/docs/index.html @@ -463,7 +463,7 @@

Zero-dep calculator

04

Unit conversion

-

10 km in mi, 100 f to c, 5kg to lb — length, mass and temperature.

+

10 km in mi, 2 h in min, 10 GB in MB — ten dimensions, from length and mass to time, data, pressure and energy.

05 @@ -568,9 +568,10 @@

PATH binary→ web search -

Unit conversion understands length (mm cm m km in ft yd mi nmi), - mass (mg g kg oz lb st t) and temperature (c f k), and accepts long names such as - 10 kilometres in miles.

+

Unit conversion understands ten dimensions — length, mass, time, volume, + area, speed, data, pressure, energy and temperature — accepts long names such as + 10 kilometres in miles, and reads exponents and expressions on the amount + (1e3 m in km, 2*3 km in mi).

diff --git a/src/extras.rs b/src/extras.rs index ba9653b..a5ac829 100644 --- a/src/extras.rs +++ b/src/extras.rs @@ -13,7 +13,8 @@ //! lookup path beyond the once-per-process load) //! * Aliases — `alias.g = /web`, expanded one level deep before routing //! * History — `~/.config/cldr/history`, capped and de-duplicated -//! * convert_units — length / mass / temperature, wired into the cascade +//! * convert_units — ten dimensions (length, mass, time, volume, area, speed, +//! data, pressure, energy, temperature), wired into the cascade //! * base64 — for OSC 52 clipboard copy (no clipboard crate) //! * self_test — `cldr --self-test`, headless sanity check for CI @@ -228,58 +229,311 @@ pub fn append_history(line: &str) { // Unit conversion (length / mass / temperature) // --------------------------------------------------------------------------- -const LEN: &[(&str, f64)] = &[ - ("mm", 0.001), - ("cm", 0.01), - ("m", 1.0), - ("km", 1000.0), - ("in", 0.0254), - ("ft", 0.3048), - ("yd", 0.9144), - ("mi", 1609.344), - ("nmi", 1852.0), -]; +/// Which quantity a unit measures. Two units convert only when the dimension +/// matches; temperature is the one affine case, handled separately. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Dim { + Len, + Mass, + Time, + Vol, + Area, + Speed, + Data, + Press, + Energy, + Temp, +} -const MASS: &[(&str, f64)] = &[ - ("mg", 0.001), - ("g", 1.0), - ("kg", 1000.0), - ("oz", 28.349_523_125), - ("lb", 453.592_37), - ("st", 6350.293_18), - ("t", 1_000_000.0), +/// A resolved unit: its dimension, its factor to that dimension's base unit, +/// and a canonical code (temperature only — it picks the affine formula). +#[derive(Clone, Copy)] +struct Unit { + dim: Dim, + factor: f64, + code: &'static str, +} + +/// Every accepted spelling, lowercase (input is lowercased before lookup). +/// +/// Base units: length → metre, mass → kilogram, time → second, volume → litre, +/// area → square metre, speed → metre per second, data → byte, pressure → +/// pascal, energy → joule. Data is decimal (1 kB = 1000 B) with the binary +/// forms spelled out separately (`KiB`, `MiB`, …), the same split Numbat makes. +/// +/// The factors follow the definitions in Numbat's unit module +/// (github.com/sharkdp/numbat, MIT/Apache-2.0). Only the physical constants are +/// reused; no code is taken. +const UNITS: &[(&str, Dim, f64, &str)] = &[ + // length — base: metre + ("mm", Dim::Len, 0.001, "mm"), + ("millimeter", Dim::Len, 0.001, "mm"), + ("millimeters", Dim::Len, 0.001, "mm"), + ("millimetre", Dim::Len, 0.001, "mm"), + ("millimetres", Dim::Len, 0.001, "mm"), + ("cm", Dim::Len, 0.01, "cm"), + ("centimeter", Dim::Len, 0.01, "cm"), + ("centimeters", Dim::Len, 0.01, "cm"), + ("centimetre", Dim::Len, 0.01, "cm"), + ("centimetres", Dim::Len, 0.01, "cm"), + ("m", Dim::Len, 1.0, "m"), + ("meter", Dim::Len, 1.0, "m"), + ("meters", Dim::Len, 1.0, "m"), + ("metre", Dim::Len, 1.0, "m"), + ("metres", Dim::Len, 1.0, "m"), + ("km", Dim::Len, 1000.0, "km"), + ("kilometer", Dim::Len, 1000.0, "km"), + ("kilometers", Dim::Len, 1000.0, "km"), + ("kilometre", Dim::Len, 1000.0, "km"), + ("kilometres", Dim::Len, 1000.0, "km"), + ("in", Dim::Len, 0.0254, "in"), + ("inch", Dim::Len, 0.0254, "in"), + ("inches", Dim::Len, 0.0254, "in"), + ("ft", Dim::Len, 0.3048, "ft"), + ("foot", Dim::Len, 0.3048, "ft"), + ("feet", Dim::Len, 0.3048, "ft"), + ("yd", Dim::Len, 0.9144, "yd"), + ("yard", Dim::Len, 0.9144, "yd"), + ("yards", Dim::Len, 0.9144, "yd"), + ("mi", Dim::Len, 1609.344, "mi"), + ("mile", Dim::Len, 1609.344, "mi"), + ("miles", Dim::Len, 1609.344, "mi"), + ("nmi", Dim::Len, 1852.0, "nmi"), + ("nauticalmile", Dim::Len, 1852.0, "nmi"), + ("nauticalmiles", Dim::Len, 1852.0, "nmi"), + // mass — base: kilogram + ("mg", Dim::Mass, 0.000001, "mg"), + ("milligram", Dim::Mass, 0.000001, "mg"), + ("milligrams", Dim::Mass, 0.000001, "mg"), + ("g", Dim::Mass, 0.001, "g"), + ("gram", Dim::Mass, 0.001, "g"), + ("grams", Dim::Mass, 0.001, "g"), + ("gramme", Dim::Mass, 0.001, "g"), + ("grammes", Dim::Mass, 0.001, "g"), + ("kg", Dim::Mass, 1.0, "kg"), + ("kilogram", Dim::Mass, 1.0, "kg"), + ("kilograms", Dim::Mass, 1.0, "kg"), + ("kilo", Dim::Mass, 1.0, "kg"), + ("kilos", Dim::Mass, 1.0, "kg"), + ("t", Dim::Mass, 1000.0, "t"), + ("tonne", Dim::Mass, 1000.0, "t"), + ("tonnes", Dim::Mass, 1000.0, "t"), + ("ton", Dim::Mass, 1000.0, "t"), + ("tons", Dim::Mass, 1000.0, "t"), + ("oz", Dim::Mass, 0.028349523125, "oz"), + ("ounce", Dim::Mass, 0.028349523125, "oz"), + ("ounces", Dim::Mass, 0.028349523125, "oz"), + ("lb", Dim::Mass, 0.45359237, "lb"), + ("lbs", Dim::Mass, 0.45359237, "lb"), + ("pound", Dim::Mass, 0.45359237, "lb"), + ("pounds", Dim::Mass, 0.45359237, "lb"), + ("st", Dim::Mass, 6.35029318, "st"), + ("stone", Dim::Mass, 6.35029318, "st"), + ("stones", Dim::Mass, 6.35029318, "st"), + // time — base: second + ("ms", Dim::Time, 0.001, "ms"), + ("millisecond", Dim::Time, 0.001, "ms"), + ("milliseconds", Dim::Time, 0.001, "ms"), + ("s", Dim::Time, 1.0, "s"), + ("sec", Dim::Time, 1.0, "s"), + ("secs", Dim::Time, 1.0, "s"), + ("second", Dim::Time, 1.0, "s"), + ("seconds", Dim::Time, 1.0, "s"), + ("min", Dim::Time, 60.0, "min"), + ("minute", Dim::Time, 60.0, "min"), + ("minutes", Dim::Time, 60.0, "min"), + ("h", Dim::Time, 3600.0, "h"), + ("hr", Dim::Time, 3600.0, "h"), + ("hrs", Dim::Time, 3600.0, "h"), + ("hour", Dim::Time, 3600.0, "h"), + ("hours", Dim::Time, 3600.0, "h"), + ("d", Dim::Time, 86400.0, "d"), + ("day", Dim::Time, 86400.0, "d"), + ("days", Dim::Time, 86400.0, "d"), + ("wk", Dim::Time, 604800.0, "wk"), + ("week", Dim::Time, 604800.0, "wk"), + ("weeks", Dim::Time, 604800.0, "wk"), + // volume — base: litre + ("ml", Dim::Vol, 0.001, "ml"), + ("milliliter", Dim::Vol, 0.001, "ml"), + ("milliliters", Dim::Vol, 0.001, "ml"), + ("millilitre", Dim::Vol, 0.001, "ml"), + ("millilitres", Dim::Vol, 0.001, "ml"), + ("cl", Dim::Vol, 0.01, "cl"), + ("dl", Dim::Vol, 0.1, "dl"), + ("l", Dim::Vol, 1.0, "l"), + ("liter", Dim::Vol, 1.0, "l"), + ("liters", Dim::Vol, 1.0, "l"), + ("litre", Dim::Vol, 1.0, "l"), + ("litres", Dim::Vol, 1.0, "l"), + ("m3", Dim::Vol, 1000.0, "m3"), + ("cubicmeter", Dim::Vol, 1000.0, "m3"), + ("cubicmetre", Dim::Vol, 1000.0, "m3"), + ("tsp", Dim::Vol, 0.00492892159375, "tsp"), + ("teaspoon", Dim::Vol, 0.00492892159375, "tsp"), + ("teaspoons", Dim::Vol, 0.00492892159375, "tsp"), + ("tbsp", Dim::Vol, 0.01478676478125, "tbsp"), + ("tablespoon", Dim::Vol, 0.01478676478125, "tbsp"), + ("tablespoons", Dim::Vol, 0.01478676478125, "tbsp"), + ("floz", Dim::Vol, 0.0295735295625, "floz"), + ("cup", Dim::Vol, 0.2365882365, "cup"), + ("cups", Dim::Vol, 0.2365882365, "cup"), + ("pint", Dim::Vol, 0.473176473, "pint"), + ("pints", Dim::Vol, 0.473176473, "pint"), + ("quart", Dim::Vol, 0.946352946, "quart"), + ("quarts", Dim::Vol, 0.946352946, "quart"), + ("gal", Dim::Vol, 3.785411784, "gal"), + ("gallon", Dim::Vol, 3.785411784, "gal"), + ("gallons", Dim::Vol, 3.785411784, "gal"), + // area — base: square metre + ("m2", Dim::Area, 1.0, "m2"), + ("sqm", Dim::Area, 1.0, "m2"), + ("squaremeter", Dim::Area, 1.0, "m2"), + ("squaremetre", Dim::Area, 1.0, "m2"), + ("km2", Dim::Area, 1000000.0, "km2"), + ("sqkm", Dim::Area, 1000000.0, "km2"), + ("cm2", Dim::Area, 0.0001, "cm2"), + ("sqcm", Dim::Area, 0.0001, "cm2"), + ("ha", Dim::Area, 10000.0, "ha"), + ("hectare", Dim::Area, 10000.0, "ha"), + ("hectares", Dim::Area, 10000.0, "ha"), + ("acre", Dim::Area, 4046.8564224, "acre"), + ("acres", Dim::Area, 4046.8564224, "acre"), + ("ft2", Dim::Area, 0.09290304, "ft2"), + ("sqft", Dim::Area, 0.09290304, "ft2"), + ("yd2", Dim::Area, 0.83612736, "yd2"), + ("sqyd", Dim::Area, 0.83612736, "yd2"), + ("mi2", Dim::Area, 2589988.110336, "mi2"), + ("sqmi", Dim::Area, 2589988.110336, "mi2"), + // speed — base: metre per second + ("m/s", Dim::Speed, 1.0, "m/s"), + ("mps", Dim::Speed, 1.0, "m/s"), + ("km/h", Dim::Speed, 0.27777777777777779, "km/h"), + ("kph", Dim::Speed, 0.27777777777777779, "km/h"), + ("kmph", Dim::Speed, 0.27777777777777779, "km/h"), + ("mph", Dim::Speed, 0.44704, "mph"), + ("mi/h", Dim::Speed, 0.44704, "mph"), + ("kn", Dim::Speed, 0.51444444444444448, "kn"), + ("knot", Dim::Speed, 0.51444444444444448, "kn"), + ("knots", Dim::Speed, 0.51444444444444448, "kn"), + ("ft/s", Dim::Speed, 0.3048, "ft/s"), + // data — base: byte, decimal by default + ("b", Dim::Data, 1.0, "b"), + ("byte", Dim::Data, 1.0, "b"), + ("bytes", Dim::Data, 1.0, "b"), + ("kb", Dim::Data, 1000.0, "kb"), + ("kilobyte", Dim::Data, 1000.0, "kb"), + ("kilobytes", Dim::Data, 1000.0, "kb"), + ("mb", Dim::Data, 1000000.0, "mb"), + ("megabyte", Dim::Data, 1000000.0, "mb"), + ("megabytes", Dim::Data, 1000000.0, "mb"), + ("gb", Dim::Data, 1000000000.0, "gb"), + ("gigabyte", Dim::Data, 1000000000.0, "gb"), + ("gigabytes", Dim::Data, 1000000000.0, "gb"), + ("tb", Dim::Data, 1000000000000.0, "tb"), + ("terabyte", Dim::Data, 1000000000000.0, "tb"), + ("terabytes", Dim::Data, 1000000000000.0, "tb"), + ("kib", Dim::Data, 1024.0, "kib"), + ("kibibyte", Dim::Data, 1024.0, "kib"), + ("kibibytes", Dim::Data, 1024.0, "kib"), + ("mib", Dim::Data, 1048576.0, "mib"), + ("mebibyte", Dim::Data, 1048576.0, "mib"), + ("mebibytes", Dim::Data, 1048576.0, "mib"), + ("gib", Dim::Data, 1073741824.0, "gib"), + ("gibibyte", Dim::Data, 1073741824.0, "gib"), + ("gibibytes", Dim::Data, 1073741824.0, "gib"), + ("tib", Dim::Data, 1099511627776.0, "tib"), + ("tebibyte", Dim::Data, 1099511627776.0, "tib"), + ("tebibytes", Dim::Data, 1099511627776.0, "tib"), + // pressure — base: pascal + ("pa", Dim::Press, 1.0, "pa"), + ("pascal", Dim::Press, 1.0, "pa"), + ("pascals", Dim::Press, 1.0, "pa"), + ("kpa", Dim::Press, 1000.0, "kpa"), + ("mpa", Dim::Press, 1000000.0, "mpa"), + ("bar", Dim::Press, 100000.0, "bar"), + ("mbar", Dim::Press, 100.0, "mbar"), + ("atm", Dim::Press, 101325.0, "atm"), + ("psi", Dim::Press, 6894.757293168, "psi"), + ("mmhg", Dim::Press, 133.322387415, "mmhg"), + ("torr", Dim::Press, 133.322368421, "torr"), + // energy — base: joule + ("j", Dim::Energy, 1.0, "j"), + ("joule", Dim::Energy, 1.0, "j"), + ("joules", Dim::Energy, 1.0, "j"), + ("kj", Dim::Energy, 1000.0, "kj"), + ("mj", Dim::Energy, 1000000.0, "mj"), + ("cal", Dim::Energy, 4.184, "cal"), + ("calorie", Dim::Energy, 4.184, "cal"), + ("calories", Dim::Energy, 4.184, "cal"), + ("kcal", Dim::Energy, 4184.0, "kcal"), + ("kilocalorie", Dim::Energy, 4184.0, "kcal"), + ("kilocalories", Dim::Energy, 4184.0, "kcal"), + ("wh", Dim::Energy, 3600.0, "wh"), + ("kwh", Dim::Energy, 3600000.0, "kwh"), + ("btu", Dim::Energy, 1055.05585262, "btu"), + // temperature — affine, factor unused, code picks the formula + ("c", Dim::Temp, 1.0, "c"), + ("celsius", Dim::Temp, 1.0, "c"), + ("centigrade", Dim::Temp, 1.0, "c"), + ("f", Dim::Temp, 1.0, "f"), + ("fahrenheit", Dim::Temp, 1.0, "f"), + ("k", Dim::Temp, 1.0, "k"), + ("kelvin", Dim::Temp, 1.0, "k"), ]; -/// Normalise a user-typed unit name to a canonical short code. -fn canon(u: &str) -> &str { - match u { - "mm" | "millimeter" | "millimeters" | "millimetre" | "millimetres" => "mm", - "cm" | "centimeter" | "centimeters" | "centimetre" | "centimetres" => "cm", - "m" | "meter" | "meters" | "metre" | "metres" => "m", - "km" | "kilometer" | "kilometers" | "kilometre" | "kilometres" => "km", - "in" | "inch" | "inches" => "in", - "ft" | "foot" | "feet" => "ft", - "yd" | "yard" | "yards" => "yd", - "mi" | "mile" | "miles" => "mi", - "nmi" | "nauticalmile" | "nauticalmiles" => "nmi", - "mg" | "milligram" | "milligrams" => "mg", - "g" | "gram" | "grams" | "gramme" | "grammes" => "g", - "kg" | "kilogram" | "kilograms" | "kilo" | "kilos" => "kg", - "oz" | "ounce" | "ounces" => "oz", - "lb" | "lbs" | "pound" | "pounds" => "lb", - "st" | "stone" | "stones" => "st", - "t" | "tonne" | "tonnes" | "ton" | "tons" => "t", - "c" | "celsius" | "centigrade" => "c", - "f" | "fahrenheit" => "f", - "k" | "kelvin" => "k", - other => other, +/// The longest alias in [`UNITS`]; bounds the suffix scan in [`parse_amount`]. +const MAX_ALIAS: usize = 12; + +/// Resolve a unit name (already lowercase) to its dimension and factor. +fn unit_of(name: &str) -> Option { + let n = name.trim(); + UNITS + .iter() + .find(|(alias, _, _, _)| *alias == n) + .map(|(_, dim, factor, code)| Unit { dim: *dim, factor: *factor, code: *code }) +} + +/// The numeric value on the left of a conversion: a literal, or an arithmetic +/// expression the calc engine already understands (`2*3`, `(1+1)/2`). +fn left_value(s: &str) -> Option { + let t = s.trim(); + if t.is_empty() { + return None; + } + if let Ok(v) = t.parse::() { + return Some(v); } + calc(t).ok() } -fn factor(u: &str) -> Option { - for (k, v) in LEN.iter().chain(MASS.iter()) { - if *k == u { - return Some(*v); +/// Parse the amount side of a conversion: `10 km`, `5kg`, `1e3 m`, `2*3 km`. +/// +/// The unit is found by *resolving* a candidate against [`UNITS`], never by +/// cutting at a fixed column, which is what makes `10 in in cm` read as ten +/// inches into centimetres. +fn parse_amount(s: &str) -> Option<(f64, Unit)> { + let t = s.trim(); + if t.is_empty() { + return None; + } + // "10 km" / "1e3 m" / "2*3 km" — unit is the last whitespace-separated token. + if let Some((head, tail)) = t.rsplit_once(char::is_whitespace) { + if let (Some(u), Some(v)) = (unit_of(tail), left_value(head)) { + return Some((v, u)); + } + } + // "5kg" / "1.5kg" / "10km" — shortest suffix that is a known unit *and* + // leaves a number (or an expression) in front of it. + let len = t.len(); + for k in 1..=MAX_ALIAS.min(len) { + let i = len - k; + if !t.is_char_boundary(i) { + continue; + } + let (head, tail) = t.split_at(i); + if let (Some(u), Some(v)) = (unit_of(tail), left_value(head)) { + return Some((v, u)); } } None @@ -301,55 +555,49 @@ fn from_celsius(c: f64, to: &str) -> f64 { } } -/// Split a leading numeric literal from its trailing unit, e.g. `10km` → ("10", "km"). -fn split_num_unit(s: &str) -> Option<(String, String)> { - let b = s.as_bytes(); - let mut i = 0usize; - while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || b[i] == b'-' || b[i] == b'+') { - i += 1; - } - if i == 0 { - return None; - } - let num = s[..i].trim().to_string(); - let unit = s[i..].trim().split_whitespace().next()?.to_string(); - Some((num, unit)) -} +/// Words that turn one amount into another: `10 km in mi`, `2 h to min`. +const CONNECTORS: &[&str] = &[" in ", " to ", " as ", " -> ", " => ", " = "]; /// Convert a natural-language-ish expression such as `10 km in mi`, -/// `100 f to c`, `5kg to lb`. Returns `None` when it is not a conversion. +/// `2 h to min`, `10 GB in MB`. Returns `None` when it is not a conversion. +/// +/// Candidate splits are tried right to left and the first one that resolves on +/// both sides wins. That ordering is deliberate: the unit itself may be a +/// connector word (`in` is inch), so the split is decided by what parses, not +/// by where the first `" in "` happens to sit. pub fn convert_units(s: &str) -> Option { let low = s.trim().to_lowercase(); - let connectors = [" in ", " to ", " as ", " -> ", " => ", " = "]; - let mut best = usize::MAX; - let mut split: Option<(&str, &str)> = None; - for c in connectors { - if let Some(i) = low.find(c) { - if i < best { - best = i; - split = Some((&low[..i], &low[i + c.len()..])); - } + + let mut splits: Vec<(usize, usize)> = Vec::new(); + for c in CONNECTORS { + let mut from = 0; + while let Some(off) = low[from..].find(c) { + let at = from + off; + splits.push((at, c.len())); + from = at + 1; } } - let (left, right) = split?; - let to = canon(right.trim().split_whitespace().next()?); - let (num, from_raw) = split_num_unit(left.trim())?; - let from = canon(&from_raw); - let value: f64 = num.parse().ok()?; + splits.sort_by(|a, b| b.0.cmp(&a.0)); - let temps = ["c", "f", "k"]; - if temps.contains(&from) || temps.contains(&to) { - if !(temps.contains(&from) && temps.contains(&to)) { - return None; + for (at, clen) in splits { + let (left, right) = (&low[..at], &low[at + clen..]); + let Some(to) = right.split_whitespace().next().and_then(unit_of) else { + continue; + }; + let Some((value, from)) = parse_amount(left) else { + continue; + }; + if from.dim != to.dim { + continue; } - let out = from_celsius(to_celsius(value, from), to); + let out = if from.dim == Dim::Temp { + from_celsius(to_celsius(value, from.code), to.code) + } else { + value * from.factor / to.factor + }; return Some(format!("{s} = {}", fmt_num(out))); } - - let from_f = factor(from)?; - let to_f = factor(to)?; - let out = value * from_f / to_f; - Some(format!("{s} = {}", fmt_num(out))) + None } // --------------------------------------------------------------------------- @@ -409,10 +657,26 @@ pub fn self_test() -> i32 { check!("convert km->mi", convert_units("10 km in mi").is_some()); check!("convert kg->lb", convert_units("5 kg to lb").is_some()); check!("convert c->f", convert_units("100 c to f").is_some()); + check!( + "convert h->min", + convert_units("2 h in min").map(|r| r.ends_with("= 120")).unwrap_or(false) + ); + check!( + "convert gb->mb", + convert_units("10 gb in mb").map(|r| r.ends_with("= 10000")).unwrap_or(false) + ); + check!( + "convert inch vs connector", + convert_units("10 in in cm").map(|r| r.ends_with("= 25.4")).unwrap_or(false) + ); + check!( + "convert exponent literal", + convert_units("1e3 m in km").map(|r| r.ends_with("= 1")).unwrap_or(false) + ); check!("convert non-conversion is None", convert_units("hello world").is_none()); if fails == 0 { - println!("self-test: OK (14/14)"); + println!("self-test: OK (18/18)"); 0 } else { println!("self-test: {fails} FAILED"); @@ -449,6 +713,36 @@ mod tests { assert!(convert_units("100 c to km").is_none()); } + #[test] + fn conversion_time_volume_data() { + assert_eq!(convert_units("2 h in min").as_deref(), Some("2 h in min = 120")); + assert_eq!(convert_units("90 min in h").as_deref(), Some("90 min in h = 1.5")); + assert_eq!(convert_units("10 gb in mb").as_deref(), Some("10 gb in mb = 10000")); + assert_eq!(convert_units("1 gib in mib").as_deref(), Some("1 gib in mib = 1024")); + assert!(convert_units("3 tbsp in ml").unwrap().contains("44.3602")); + } + + #[test] + fn conversion_speed_area_pressure_energy() { + assert!(convert_units("5 km/h in mph").unwrap().contains("3.1068")); + assert!(convert_units("1 acre in m2").unwrap().contains("4046.85")); + assert!(convert_units("1 bar in psi").unwrap().contains("14.5037")); + assert!(convert_units("1 kcal in j").unwrap().contains("4184")); + } + + #[test] + fn conversion_parsing_resolves_the_split() { + // "in" is both a connector and the inch: the split is decided by what + // parses, not by where the first " in " happens to sit. + assert!(convert_units("10 in in cm").unwrap().contains("25.4")); + // Exponents and expressions on the amount side. + assert_eq!(convert_units("1e3 m in km").as_deref(), Some("1e3 m in km = 1")); + assert!(convert_units("2*3 km in mi").unwrap().contains("3.7282")); + // One dimension cannot become another. + assert!(convert_units("10 km in kg").is_none()); + assert!(convert_units("2 h in gb").is_none()); + } + #[test] fn non_conversions() { assert!(convert_units("hello world").is_none()); From c268490478686bc6a1dfea3a3f18b60097cf6b8e Mon Sep 17 00:00:00 2001 From: Dr Sohil Momin Date: Mon, 9 Nov 2026 11:59:05 +0000 Subject: [PATCH 2/2] feat(cmd): say how much of a long line was dropped MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `/cmd` cuts an output line at 500 characters and appended a bare ellipsis, so a wrapped line and a 40 KB minified JSON line looked the same. The marker now carries the count — `… (+39412 chars)` — which makes the size of what is missing visible without printing any of it. --- README.md | 3 ++- changes/cmd-truncation-count.md | 5 +++++ src/engine.rs | 20 ++++++++++++++++++-- 3 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 changes/cmd-truncation-count.md diff --git a/README.md b/README.md index 17220e1..4cfc4b6 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,8 @@ folders 4 - Arguments are split the way a shell would, so quotes work: `/cmd lumen search "harbour at dawn"`. - stdout and stderr are both captured, capped at `max_results` rows; a single - line longer than 500 characters is truncated. + line longer than 500 characters is truncated and says how many characters + were dropped (`… (+39412 chars)`). - The exit code is shown on the summary line. - **It gives up after five seconds.** A launcher that freezes is worse than one that says "still running", so a command that outlives the cap is reported and diff --git a/changes/cmd-truncation-count.md b/changes/cmd-truncation-count.md new file mode 100644 index 0000000..38b0eea --- /dev/null +++ b/changes/cmd-truncation-count.md @@ -0,0 +1,5 @@ +--- +bump: patch +--- + +A `/cmd` output line cut at 500 characters now says how many characters were dropped, so a truncated line reads as truncated instead of as a wrapped one. diff --git a/src/engine.rs b/src/engine.rs index ea3e9cd..a7fc411 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -384,12 +384,18 @@ fn split_args(raw: &str) -> Result, String> { Ok(out) } +/// Cut a long output line at `cap` characters and say how much was dropped. +/// +/// A bare ellipsis leaves the reader unable to tell a line that just wrapped +/// from one with 40 KB of minified JSON behind it; the count makes the size of +/// what is missing visible without printing any of it. fn truncate_line(line: &str, cap: usize) -> String { - if line.chars().count() <= cap { + let total = line.chars().count(); + if total <= cap { return line.to_string(); } let mut s: String = line.chars().take(cap).collect(); - s.push('…'); + s.push_str(&format!("… (+{} chars)", total - cap)); s } @@ -924,4 +930,14 @@ mod tests { fn url_encoding() { assert_eq!(urlencode("hi there&you"), "hi+there%26you"); } + + #[test] + fn long_lines_say_how_much_was_cut() { + let line = "x".repeat(600); + let out = truncate_line(&line, 500); + assert!(out.ends_with("… (+100 chars)"), "truncation marker missing"); + assert_eq!(out.chars().count(), 500 + "… (+100 chars)".chars().count()); + // A line at or under the cap is untouched. + assert_eq!(truncate_line("short", 500), "short"); + } }