Skip to main content

datumesh_engine/
whatif.rs

1//! Scenarios (Build 2 Part 3, E1 and E2; SPEC 5.9): [`Engine::whatif`] evaluates a cell as of
2//! an asof with overrides in place, and writes nothing. The solver ([`Solve`]) finds the value
3//! of one number cell that makes another equal a number, by bisection.
4//!
5//! A scenario answer is not an [`Answer`](crate::Answer): it has no receipt and is never
6//! stored, signed or memoised. Cells that do not depend on the overrides answer as `get` would,
7//! from the memo and the store; the dependent ones are evaluated in the request's scope.
8
9use std::collections::{HashMap, HashSet};
10use std::sync::Arc;
11
12use datumesh_core::{lexical, Arg, Cell, CellRef, FunctionDescriptor, Scalar, Type};
13
14use crate::check::{check_args, check_no_slice};
15use crate::engine::{Engine, STORED};
16use crate::error::{EngineError, StoreError};
17use crate::eval::{Done, Req};
18use crate::runtime::{Budget, Pattern, SlicePattern};
19use crate::slice::cells_slice;
20
21/// The most overrides a scenario may have (SPEC 5.9).
22const MAX_OVERRIDES: usize = 64;
23
24/// The overrides of a scenario: value overrides and slice overrides, in the order given.
25#[derive(Clone, Debug, Default)]
26pub struct Overrides {
27    items: Vec<Override>,
28}
29
30#[derive(Clone, Debug)]
31enum Override {
32    Value { cell: CellRef, value: Scalar },
33    Slice { slice: CellRef, members: Option<Vec<(CellRef, Scalar)>>, add: Vec<(CellRef, Scalar)>, remove: Vec<CellRef> },
34}
35
36impl Overrides {
37    /// No overrides.
38    pub fn new() -> Overrides {
39        Overrides::default()
40    }
41
42    /// `cell` answers `value` (of the function's return type) in the scenario.
43    pub fn value(mut self, cell: CellRef, value: Scalar) -> Overrides {
44        self.items.push(Override::Value { cell, value });
45        self
46    }
47
48    /// The members of the stored slice `slice` (a cell reference with its open arguments left
49    /// open) change: `add` are new members with their values, `remove` are members that go.
50    pub fn slice(self, slice: CellRef, add: Vec<(CellRef, Scalar)>, remove: Vec<CellRef>) -> Overrides {
51        self.slice_full(slice, None, add, remove)
52    }
53
54    /// The members of the stored slice `slice` become exactly `members` (cells and their values,
55    /// possibly none): the stored members are not read. Since 0.6.0 (SPEC 5.9).
56    pub fn slice_members(self, slice: CellRef, members: Vec<(CellRef, Scalar)>) -> Overrides {
57        self.slice_full(slice, Some(members), Vec::new(), Vec::new())
58    }
59
60    /// The general form of the slice overrides. `members`, when `Some`, is the member set, as
61    /// [`slice_members`](Overrides::slice_members); it is refused with a non-empty `add` or
62    /// `remove` (`E_SLICE_MEMBER`, when the scenario is built). Since 0.6.0.
63    pub fn slice_full(
64        mut self,
65        slice: CellRef,
66        members: Option<Vec<(CellRef, Scalar)>>,
67        add: Vec<(CellRef, Scalar)>,
68        remove: Vec<CellRef>,
69    ) -> Overrides {
70        self.items.push(Override::Slice { slice, members, add, remove });
71        self
72    }
73
74    /// The number of overrides.
75    pub fn len(&self) -> usize {
76        self.items.len()
77    }
78
79    /// Whether there are no overrides.
80    pub fn is_empty(&self) -> bool {
81        self.items.is_empty()
82    }
83}
84
85/// A solve for [`Engine::whatif`]: find the value of `vary` (a number cell) in `[lo, hi]` at
86/// which `target` (a number cell) equals `equals`. All four are number scalars. The value found
87/// carries 15 significant digits (rounded half-even), and the answer is the requested cell's
88/// value under it: the target's, when the requested cell is the target.
89#[derive(Clone, Debug)]
90pub struct Solve {
91    vary: CellRef,
92    target: CellRef,
93    equals: Scalar,
94    lo: Scalar,
95    hi: Scalar,
96}
97
98impl Solve {
99    /// The solve of `target = equals` over `vary` in `[lo, hi]`.
100    pub fn new(vary: CellRef, target: CellRef, equals: Scalar, lo: Scalar, hi: Scalar) -> Solve {
101        Solve { vary, target, equals, lo, hi }
102    }
103}
104
105/// A scenario's answer ([`Engine::whatif`]): the value of the cell as of the asof, with the
106/// overrides in place. It is labelled a scenario: it has no receipt and is never stored.
107#[non_exhaustive]
108#[derive(Clone, Debug, PartialEq)]
109pub struct ScenarioAnswer {
110    /// The cell asked for.
111    pub cell: Cell,
112    /// Its type (the function's return type).
113    pub ty: Type,
114    /// Its value in the scenario.
115    pub value: Scalar,
116    /// The asof: the one asked for, else the clock's now.
117    pub asof: String,
118    /// The overrides, sorted by [`ScenarioOverride::id`].
119    pub overrides: Vec<ScenarioOverride>,
120    /// The solved cell and the value found for it, when the request had a solve.
121    pub solved: Option<(Cell, Scalar)>,
122}
123
124/// An override of a scenario, as its answer lists it.
125#[non_exhaustive]
126#[derive(Clone, Debug, PartialEq)]
127pub enum ScenarioOverride {
128    /// A cell with a value.
129    Value {
130        /// The cell.
131        cell: Cell,
132        /// Its value.
133        value: Scalar,
134    },
135    /// A stored slice with members added and removed; both sorted by cell id.
136    Slice {
137        /// The slice (its open arguments are [`Arg::Slice`]).
138        slice: Cell,
139        /// The added members, with their values.
140        add: Vec<(Cell, Scalar)>,
141        /// The removed members.
142        remove: Vec<Cell>,
143    },
144    /// A stored slice whose whole member set is replaced (since 0.6.0); the members sorted by
145    /// cell id, present even when there are none.
146    Members {
147        /// The slice (its open arguments are [`Arg::Slice`]).
148        slice: Cell,
149        /// The members, with their values.
150        members: Vec<(Cell, Scalar)>,
151    },
152}
153
154impl ScenarioOverride {
155    /// The id of the overridden cell, or of the slice.
156    pub fn id(&self) -> String {
157        match self {
158            ScenarioOverride::Value { cell, .. } => cell.id(),
159            ScenarioOverride::Slice { slice, .. } | ScenarioOverride::Members { slice, .. } => slice.id(),
160        }
161    }
162}
163
164/// The overrides of one scenario, validated and resolved, as the evaluation reads them.
165#[derive(Clone, Debug, Default)]
166pub(crate) struct Scope {
167    /// The overridden cells, by cell id.
168    pub(crate) values: HashMap<String, (Cell, Scalar)>,
169    /// The overridden slices, by slice id.
170    pub(crate) slices: HashMap<String, SliceOverride>,
171    /// The names of the overridden functions.
172    pub(crate) affected: HashSet<String>,
173}
174
175/// A slice override: the members added, and the cell ids of those removed.
176#[derive(Clone, Debug)]
177pub(crate) struct SliceOverride {
178    pub(crate) add: Vec<(Cell, Scalar)>,
179    pub(crate) remove: HashSet<String>,
180    /// The whole member set, when the override replaces it (`members`).
181    pub(crate) members: Option<Vec<(Cell, Scalar)>>,
182}
183
184impl Scope {
185    /// This scope with `cell` overridden to `value` as well (the solver's trial values).
186    pub(crate) fn with_value(&self, cell: Cell, value: Scalar) -> Scope {
187        let mut s = self.clone();
188        s.affected.insert(cell.function_name());
189        s.values.insert(cell.id(), (cell, value));
190        s
191    }
192}
193
194impl Engine {
195    /// The value of `cell` as of `asof` (else `cell.asof`, else now) with `overrides` in place.
196    /// With `solve`, `vary` is first set to the value that makes its `target` equal its `equals`
197    /// (bisection within its interval; see [`Solve`]), and `cell`'s value is then that under the
198    /// solved `vary`; the answer's `solved` says what was found.
199    ///
200    /// The overridden cells answer their values; a slice override changes a stored slice's
201    /// members. A cell that does not depend on the overrides answers from the memo and the
202    /// store as [`get`](Engine::get) would; a dependent cell is evaluated in the request's scope.
203    /// Nothing is written: no receipt, computed version, memo entry or signature. The answer
204    /// is labelled a scenario, not a fact.
205    ///
206    /// Errors: [`EngineError::Override`] for overrides that are not valid (or more than 64),
207    /// [`EngineError::NotCovered`] when the cell has no value (a fault in scope included), and
208    /// [`EngineError::WhatifNoSolution`] for a solve without a solution or out of fuel. The
209    /// usual request errors (asof, arguments, unlicensed, budget) are those of `get`.
210    pub fn whatif(
211        &self,
212        cell: &CellRef,
213        asof: Option<&str>,
214        overrides: &Overrides,
215        solve: Option<&Solve>,
216    ) -> Result<ScenarioAnswer, EngineError> {
217        let now = self.clock.now();
218        let a = asof.or(cell.asof.as_deref()).unwrap_or(&now).to_string();
219        lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
220        check_no_slice(&cell.args)?;
221        if overrides.len() > MAX_OVERRIDES {
222            return Err(EngineError::Override("E_CANON_LIMIT".into()));
223        }
224        let Some((fn_hash, desc)) = self.function_as_of(&cell.ns, &cell.fn_name, &a)? else {
225            return Err(EngineError::NotCovered { fault: None });
226        };
227        let target = cell.resolve(&fn_hash).map_err(EngineError::Invalid)?;
228        check_args(&target, &desc).map_err(EngineError::Invalid)?;
229        let (scope, list) = self.build_scope(overrides, &a)?;
230        let scope = Arc::new(scope);
231        // One budget for the whole request: a solve's iterations share its fuel.
232        let budget = Budget::with_work(self.fuel, self.work_limit);
233        let ty = desc.signature.returns.ty;
234        let (value, solved) = match solve {
235            None => (self.scope_value(&target, &desc, &a, &now, &scope, &budget)?, None),
236            Some(s) => self.solve(s, &target, &desc, &a, &now, &scope, &budget)?,
237        };
238        Ok(ScenarioAnswer { cell: target, ty, value, asof: a, overrides: list, solved })
239    }
240
241    /// The function `<ns>/<fn_name>` means as of `asof`: its hash and descriptor, or none when
242    /// the name is unbound or has no descriptor.
243    fn function_as_of(
244        &self,
245        ns: &str,
246        fn_name: &str,
247        asof: &str,
248    ) -> Result<Option<(String, Arc<FunctionDescriptor>)>, EngineError> {
249        let name = format!("{ns}/{fn_name}");
250        let Some(hash) = self.store.resolve_name(&name, asof).map_err(|e| StoreError::new("resolve_name", e))? else {
251            return Ok(None);
252        };
253        Ok(self.descriptor_of(&hash)?.map(|d| (hash, d)))
254    }
255
256    /// A cell reference resolved as of `asof`, with its arguments checked against the signature.
257    fn resolve_cell(&self, c: &CellRef, asof: &str) -> Result<(Cell, Arc<FunctionDescriptor>), EngineError> {
258        check_no_slice(&c.args)?;
259        let Some((hash, desc)) = self.function_as_of(&c.ns, &c.fn_name, asof)? else {
260            return Err(EngineError::NameUnresolved { fn_name: format!("{}/{}", c.ns, c.fn_name), asof: asof.into() });
261        };
262        let cell = c.resolve(&hash).map_err(EngineError::Invalid)?;
263        check_args(&cell, &desc).map_err(EngineError::Invalid)?;
264        Ok((cell, desc))
265    }
266
267    /// Validates the overrides as of `asof` (SPEC 5.9) and makes the scope and the sorted list
268    /// the answer shows.
269    fn build_scope(&self, overrides: &Overrides, asof: &str) -> Result<(Scope, Vec<ScenarioOverride>), EngineError> {
270        let refused = |code: &str| EngineError::Override(code.to_string());
271        let mut scope = Scope::default();
272        let mut list = Vec::new();
273        for o in &overrides.items {
274            match o {
275                Override::Value { cell, value } => {
276                    let (c, desc) = self.resolve_cell(cell, asof)?;
277                    if value.ty() != desc.signature.returns.ty {
278                        return Err(refused("E_CANON_TYPE"));
279                    }
280                    let id = c.id();
281                    if scope.values.contains_key(&id) {
282                        return Err(refused("E_CANON_ARG_DUPLICATE"));
283                    }
284                    scope.affected.insert(c.function_name());
285                    scope.values.insert(id, (c.clone(), value.clone()));
286                    list.push(ScenarioOverride::Value { cell: c, value: value.clone() });
287                }
288                Override::Slice { slice, members, add, remove } => {
289                    if members.is_some() && (!add.is_empty() || !remove.is_empty()) {
290                        return Err(refused("E_SLICE_MEMBER"));
291                    }
292                    let Some((hash, desc)) = self.function_as_of(&slice.ns, &slice.fn_name, asof)? else {
293                        return Err(EngineError::NameUnresolved {
294                            fn_name: format!("{}/{}", slice.ns, slice.fn_name),
295                            asof: asof.into(),
296                        });
297                    };
298                    let fn_name = format!("{}/{}", slice.ns, slice.fn_name);
299                    // Only stored slices change by membership.
300                    if desc.lang != STORED {
301                        return Err(refused("E_SLICE_MEMBER"));
302                    }
303                    let pattern: SlicePattern = slice
304                        .args
305                        .iter()
306                        .map(|(k, a)| {
307                            let p = match a {
308                                Arg::Value(v) => Pattern::Value(v.clone()),
309                                Arg::Slice => Pattern::Open,
310                            };
311                            (k.clone(), p)
312                        })
313                        .collect();
314                    let s = cells_slice(&fn_name, &hash, &desc, &pattern).map_err(EngineError::Invalid)?;
315                    let sid = s.id().to_string();
316                    if scope.slices.contains_key(&sid) {
317                        return Err(refused("E_CANON_ARG_DUPLICATE"));
318                    }
319                    let slice_cell = slice.resolve(&hash).map_err(EngineError::Invalid)?;
320                    let mut adds: Vec<(Cell, Scalar)> = Vec::with_capacity(add.len());
321                    for (c, v) in add {
322                        let cell = c.resolve(&hash).map_err(EngineError::Invalid)?;
323                        check_args(&cell, &desc).map_err(EngineError::Invalid)?;
324                        if cell.function_name() != fn_name {
325                            return Err(refused("E_SLICE_MEMBER"));
326                        }
327                        adds.push((cell, v.clone()));
328                    }
329                    let mut removes: Vec<Cell> = Vec::with_capacity(remove.len());
330                    for c in remove {
331                        let cell = c.resolve(&hash).map_err(EngineError::Invalid)?;
332                        check_args(&cell, &desc).map_err(EngineError::Invalid)?;
333                        if cell.function_name() != fn_name {
334                            return Err(refused("E_SLICE_MEMBER"));
335                        }
336                        removes.push(cell);
337                    }
338                    // The whole member set: each a cell of the slice (its function and arguments),
339                    // once, with a value of the return type.
340                    let member_list = match members {
341                        None => None,
342                        Some(ms) => {
343                            let mut out: Vec<(Cell, Scalar)> = Vec::with_capacity(ms.len());
344                            let mut ids = HashSet::new();
345                            for (c, v) in ms {
346                                let cell = c.resolve(&hash).map_err(EngineError::Invalid)?;
347                                if cell.function_name() != fn_name
348                                    || !matches(&pattern, &cell)
349                                    || !ids.insert(cell.id())
350                                {
351                                    return Err(refused("E_SLICE_MEMBER"));
352                                }
353                                check_args(&cell, &desc).map_err(EngineError::Invalid)?;
354                                if v.ty() != desc.signature.returns.ty {
355                                    return Err(refused("E_CANON_TYPE"));
356                                }
357                                out.push((cell, v.clone()));
358                            }
359                            Some(out)
360                        }
361                    };
362                    let mut add_ids = HashSet::new();
363                    for (c, _) in &adds {
364                        if !add_ids.insert(c.id()) {
365                            return Err(refused("E_CANON_ARG_DUPLICATE"));
366                        }
367                    }
368                    let mut remove_ids = HashSet::new();
369                    for c in &removes {
370                        if !remove_ids.insert(c.id()) {
371                            return Err(refused("E_CANON_ARG_DUPLICATE"));
372                        }
373                    }
374                    if adds.iter().any(|(c, _)| remove_ids.contains(&c.id())) {
375                        return Err(refused("E_SLICE_MEMBER"));
376                    }
377                    let stored: HashSet<String> = self
378                        .store
379                        .slice_values(&s, asof)
380                        .map_err(|e| StoreError::new("slice_values", e))?
381                        .into_iter()
382                        .map(|v| v.version.cell_id)
383                        .collect();
384                    for c in &removes {
385                        if !matches(&pattern, c) || !stored.contains(&c.id()) {
386                            return Err(refused("E_SLICE_MEMBER"));
387                        }
388                    }
389                    // A member answers its value read alone, as an added one does.
390                    for (c, v) in member_list.iter().flatten() {
391                        scope.values.insert(c.id(), (c.clone(), v.clone()));
392                    }
393                    for (c, v) in &adds {
394                        if !matches(&pattern, c) || stored.contains(&c.id()) {
395                            return Err(refused("E_SLICE_MEMBER"));
396                        }
397                        if v.ty() != desc.signature.returns.ty {
398                            return Err(refused("E_CANON_TYPE"));
399                        }
400                        // Read alone, an added member answers its value, as an overridden cell does.
401                        scope.values.insert(c.id(), (c.clone(), v.clone()));
402                    }
403                    scope.affected.insert(fn_name);
404                    let mut add_sorted = adds.clone();
405                    add_sorted.sort_by_key(|(c, _)| c.id());
406                    removes.sort_by_key(|c| c.id());
407                    match member_list {
408                        Some(mut ms) => {
409                            ms.sort_by_key(|(c, _)| c.id());
410                            scope.slices.insert(
411                                sid,
412                                SliceOverride { add: Vec::new(), remove: HashSet::new(), members: Some(ms.clone()) },
413                            );
414                            list.push(ScenarioOverride::Members { slice: slice_cell, members: ms });
415                        }
416                        None => {
417                            scope.slices.insert(sid, SliceOverride { add: adds, remove: remove_ids, members: None });
418                            list.push(ScenarioOverride::Slice { slice: slice_cell, add: add_sorted, remove: removes });
419                        }
420                    }
421                }
422            }
423        }
424        list.sort_by_key(|o| o.id());
425        Ok((scope, list))
426    }
427
428    /// The value of `target` in `scope` as of `asof`: the override's value when it is
429    /// overridden, else what the scenario evaluation gives.
430    fn scope_value(
431        &self,
432        target: &Cell,
433        desc: &Arc<FunctionDescriptor>,
434        asof: &str,
435        now: &str,
436        scope: &Arc<Scope>,
437        budget: &Budget,
438    ) -> Result<Scalar, EngineError> {
439        if let Some((_, v)) = scope.values.get(&target.id()) {
440            return Ok(v.clone());
441        }
442        let mut req = Req::scoped(self, asof, now, scope.clone(), budget);
443        match req.scope_run(target.clone(), desc.clone())? {
444            Done::Value(a) => Ok(a.value.clone()),
445            Done::Fault(f) => Err(EngineError::NotCovered { fault: Some(f.fault) }),
446            Done::NotCovered | Done::Unsigned(..) | Done::Withdrawn(_) => Err(EngineError::NotCovered { fault: None }),
447        }
448    }
449
450    /// The solve of [`Engine::whatif`] (E2): bisection of `target - equals` over `vary`. Out of
451    /// fuel, or no sign change, is `WhatifNoSolution`.
452    #[allow(clippy::too_many_arguments)]
453    fn solve(
454        &self,
455        s: &Solve,
456        target: &Cell,
457        desc: &Arc<FunctionDescriptor>,
458        asof: &str,
459        now: &str,
460        scope: &Arc<Scope>,
461        budget: &Budget,
462    ) -> Result<(Scalar, Option<(Cell, Scalar)>), EngineError> {
463        // The bisection is on the solve's `target`; the answer is the requested cell's value.
464        let (vary, vary_desc) = self.resolve_cell(&s.vary, asof)?;
465        let (solve_target, solve_desc) = self.resolve_cell(&s.target, asof)?;
466        let number = Type::Number;
467        if vary_desc.signature.returns.ty != number
468            || solve_desc.signature.returns.ty != number
469            || [&s.equals, &s.lo, &s.hi].iter().any(|x| x.ty() != number)
470        {
471            return Err(EngineError::Override("E_CANON_TYPE".into()));
472        }
473        let result = (|| {
474            let num = |x: &Scalar| -> f64 { x.lexical().parse().unwrap_or(f64::NAN) };
475            let (eq, lo, hi) = (num(&s.equals), num(&s.lo), num(&s.hi));
476            if lo > hi {
477                return Err(EngineError::WhatifNoSolution);
478            }
479            // The scope with `vary` at `x`, rounded as the answer will carry it.
480            let trial = |x: f64| -> Result<(Scalar, Arc<Scope>), EngineError> {
481                let text = decimal15(x).ok_or(EngineError::WhatifNoSolution)?;
482                let value = Scalar::from_lexical(number, &text).map_err(|_| EngineError::WhatifNoSolution)?;
483                Ok((value.clone(), Arc::new(scope.with_value(vary.clone(), value))))
484            };
485            let f = |x: f64| -> Result<f64, EngineError> {
486                let (_, sc) = trial(x)?;
487                let v = self.scope_value(&solve_target, &solve_desc, asof, now, &sc, budget)?;
488                Ok(num(&v) - eq)
489            };
490            let flo = f(lo)?;
491            let x = if flo == 0.0 {
492                lo
493            } else {
494                let fhi = f(hi)?;
495                if fhi == 0.0 {
496                    hi
497                } else {
498                    if (flo < 0.0) == (fhi < 0.0) {
499                        return Err(EngineError::WhatifNoSolution);
500                    }
501                    let (mut a, mut fa, mut b, mut fb) = (lo, flo, hi, fhi);
502                    loop {
503                        let mid = a + (b - a) / 2.0;
504                        if mid <= a || mid >= b {
505                            // The interval holds no double between its ends: the nearer one.
506                            break if fa.abs() <= fb.abs() { a } else { b };
507                        }
508                        let fm = f(mid)?;
509                        if fm.abs() <= 1e-12 * eq.abs().max(1.0)
510                            || (b - a).abs() <= 1e-12 * a.abs().max(b.abs()).max(1.0)
511                        {
512                            break mid;
513                        }
514                        if (fm < 0.0) == (fa < 0.0) {
515                            a = mid;
516                            fa = fm;
517                        } else {
518                            b = mid;
519                            fb = fm;
520                        }
521                    }
522                }
523            };
524            let (value, sc) = trial(x)?;
525            let v = self.scope_value(target, desc, asof, now, &sc, budget)?;
526            Ok((v, Some((vary.clone(), value))))
527        })();
528        match result {
529            Err(EngineError::BudgetExceeded { .. } | EngineError::WorkExceeded { .. }) => {
530                Err(EngineError::WhatifNoSolution)
531            }
532            other => other,
533        }
534    }
535}
536
537/// The hash standing for an unsigned scenario answer (an overridden value, or a member a
538/// scenario changed): not a receipt's, but distinct for each cell and value.
539pub(crate) fn scoped_hash(id: &str, value: &Scalar) -> String {
540    datumesh_core::sha256_hex(format!("scenario {id} {} {}", value.ty().as_str(), value.lexical()).as_bytes())
541}
542
543/// Whether `cell`'s arguments match `pattern` (a bound argument equal, an open one anything).
544fn matches(pattern: &SlicePattern, cell: &Cell) -> bool {
545    pattern.iter().all(|(k, p)| match (cell.args.get(k), p) {
546        (Some(Arg::Value(v)), Pattern::Value(pv)) => v == pv,
547        (Some(Arg::Value(_)), Pattern::Open) => true,
548        _ => false,
549    })
550}
551
552/// A finite number rounded to 15 significant digits, half-even (the rounding of the Rust float
553/// formatter on the exact binary value), as a canonical decimal (SPEC 3.1: no exponent, no
554/// trailing zeros). Solve values carry these digits: the bisection runs on binary doubles, and
555/// 15 digits are what a double holds deterministically. `None` for a non-finite value or one
556/// whose text is too long.
557fn decimal15(x: f64) -> Option<String> {
558    if !x.is_finite() {
559        return None;
560    }
561    if x == 0.0 {
562        return Some("0".into());
563    }
564    let text = format!("{:.14e}", x.abs());
565    let (mantissa, exp) = text.split_once('e')?;
566    let exp: i64 = exp.parse().ok()?;
567    let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
568    let digits = digits.trim_end_matches('0');
569    let mut out = String::new();
570    if x < 0.0 {
571        out.push('-');
572    }
573    if exp >= 0 {
574        let int_len = usize::try_from(exp).ok()? + 1;
575        if digits.len() <= int_len {
576            out.push_str(digits);
577            out.extend(std::iter::repeat_n('0', int_len - digits.len()));
578        } else {
579            out.push_str(&digits[..int_len]);
580            out.push('.');
581            out.push_str(&digits[int_len..]);
582        }
583    } else {
584        out.push_str("0.");
585        out.extend(std::iter::repeat_n('0', usize::try_from(-exp - 1).ok()?));
586        out.push_str(digits);
587    }
588    (out.len() <= 128).then_some(out)
589}
590
591#[cfg(test)]
592mod tests {
593    use super::decimal15;
594
595    #[test]
596    fn decimals_are_canonical() {
597        assert_eq!(decimal15(3.0).as_deref(), Some("3"));
598        assert_eq!(decimal15(-0.5).as_deref(), Some("-0.5"));
599        assert_eq!(decimal15(0.0).as_deref(), Some("0"));
600        assert_eq!(decimal15(1e-5).as_deref(), Some("0.00001"));
601        assert_eq!(decimal15(120.0).as_deref(), Some("120"));
602        assert_eq!(decimal15(2f64.sqrt()).as_deref(), Some("1.4142135623731"));
603    }
604}