mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 18:27:00 +01:00
538 lines
22 KiB
Rust
538 lines
22 KiB
Rust
//! `Codec`: how a text part turns a value into text and text into a value (18.2), with the library codecs of this
|
||
//! crate.
|
||
|
||
use crate::quantity::Reader;
|
||
use std::borrow::Cow;
|
||
use std::fmt;
|
||
use std::ops::RangeInclusive;
|
||
use std::sync::Arc;
|
||
|
||
/// The text is not a value of the codec's type.
|
||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||
pub struct NotAValue;
|
||
|
||
/// What a parse learned beside the value.
|
||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||
#[non_exhaustive]
|
||
pub struct ParseNote {
|
||
/// The tag of the unit the text named.
|
||
pub unit: Option<u32>,
|
||
/// The number read before the codec held it to its range.
|
||
pub held: Option<f64>,
|
||
/// The text held more than the codec reads; the value is what came before the cut.
|
||
pub cut: bool,
|
||
}
|
||
|
||
/// Where the caret goes when the part takes focus.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
#[non_exhaustive]
|
||
pub enum Caret {
|
||
/// The whole text is selected.
|
||
All,
|
||
/// The caret sits after the last character.
|
||
End,
|
||
}
|
||
|
||
/// A value's text form.
|
||
pub trait Codec {
|
||
/// The value the text stands for.
|
||
type Value: Clone + PartialEq + Send + Sync + 'static;
|
||
|
||
/// Every draft is a value (plain text): a draft applies as typed and never rejects.
|
||
const DRAFTS_ARE_VALUES: bool = false;
|
||
|
||
/// The text of `v`.
|
||
fn format(&self, v: &Self::Value) -> String;
|
||
|
||
/// The value of `text`; `start` is the value when editing began, for relative input.
|
||
fn parse(&self, text: &str, start: &Self::Value) -> Result<Self::Value, NotAValue>;
|
||
|
||
/// The value of `text` and what the parse learned beside it (`Reader::read_tagged`); the default notes nothing.
|
||
fn parse_tagged(&self, text: &str, start: &Self::Value) -> Result<(Self::Value, ParseNote), NotAValue> {
|
||
self.parse(text, start).map(|value| (value, ParseNote::default()))
|
||
}
|
||
|
||
/// Whether `text` applies as soon as it is typed rather than on commit.
|
||
fn applies_as_typed(&self, _text: &str) -> bool {
|
||
false
|
||
}
|
||
|
||
/// Whether the codec takes `c` as typed.
|
||
fn filter(&self, _c: char) -> bool {
|
||
true
|
||
}
|
||
|
||
/// Whether a paste the codec reads whole replaces the field's text, wherever the caret is.
|
||
fn whole_paste(&self, _pasted: &str) -> bool {
|
||
false
|
||
}
|
||
|
||
/// The text the field shows after committing `v`, which was parsed from `text`.
|
||
fn normalise(&self, _text: &str, v: &Self::Value) -> String {
|
||
self.format(v)
|
||
}
|
||
|
||
/// Where the caret goes when the part takes focus with this text.
|
||
fn caret_on_focus(&self, _text: &str) -> Caret {
|
||
Caret::All
|
||
}
|
||
|
||
/// The widest typical text, for the field's ideal width. Codecs with bounded text only; `PlainText` returns
|
||
/// empty text, so a plain field never sizes from what the user typed.
|
||
fn sample(&self, current: &Self::Value) -> Cow<'_, str> {
|
||
self.format(current).into()
|
||
}
|
||
}
|
||
|
||
impl<C: Codec + ?Sized> Codec for &C {
|
||
type Value = C::Value;
|
||
const DRAFTS_ARE_VALUES: bool = C::DRAFTS_ARE_VALUES;
|
||
|
||
fn format(&self, v: &Self::Value) -> String {
|
||
(**self).format(v)
|
||
}
|
||
|
||
fn parse(&self, text: &str, start: &Self::Value) -> Result<Self::Value, NotAValue> {
|
||
(**self).parse(text, start)
|
||
}
|
||
|
||
fn parse_tagged(&self, text: &str, start: &Self::Value) -> Result<(Self::Value, ParseNote), NotAValue> {
|
||
(**self).parse_tagged(text, start)
|
||
}
|
||
|
||
fn applies_as_typed(&self, text: &str) -> bool {
|
||
(**self).applies_as_typed(text)
|
||
}
|
||
|
||
fn filter(&self, c: char) -> bool {
|
||
(**self).filter(c)
|
||
}
|
||
|
||
fn whole_paste(&self, pasted: &str) -> bool {
|
||
(**self).whole_paste(pasted)
|
||
}
|
||
|
||
fn normalise(&self, text: &str, v: &Self::Value) -> String {
|
||
(**self).normalise(text, v)
|
||
}
|
||
|
||
fn caret_on_focus(&self, text: &str) -> Caret {
|
||
(**self).caret_on_focus(text)
|
||
}
|
||
|
||
fn sample(&self, current: &Self::Value) -> Cow<'_, str> {
|
||
(**self).sample(current)
|
||
}
|
||
}
|
||
|
||
/// Plain text: every draft is a value.
|
||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||
pub struct PlainText;
|
||
|
||
impl Codec for PlainText {
|
||
type Value = String;
|
||
const DRAFTS_ARE_VALUES: bool = true;
|
||
|
||
fn format(&self, v: &String) -> String {
|
||
v.clone()
|
||
}
|
||
|
||
fn parse(&self, text: &str, _start: &String) -> Result<String, NotAValue> {
|
||
Ok(text.to_owned())
|
||
}
|
||
|
||
fn applies_as_typed(&self, _text: &str) -> bool {
|
||
true
|
||
}
|
||
|
||
fn caret_on_focus(&self, _text: &str) -> Caret {
|
||
Caret::End
|
||
}
|
||
|
||
fn sample(&self, _current: &String) -> Cow<'_, str> {
|
||
Cow::Borrowed("")
|
||
}
|
||
}
|
||
|
||
/// A caller's text-to-number reader.
|
||
type Custom = Arc<dyn Fn(&str) -> Option<f64> + Send + Sync>;
|
||
|
||
/// An optional number: empty text is `None`; anything else reads through a [`Reader`] unless overridden with [`NumberCodec::parse_with`].
|
||
#[derive(Clone)]
|
||
pub struct NumberCodec {
|
||
reader: Reader,
|
||
decimals: usize,
|
||
/// Every decimal place is written, trailing zeros included.
|
||
fixed: bool,
|
||
custom: Option<Custom>,
|
||
/// An authoritative reader for the complete, trimmed, non-empty input.
|
||
primary: Option<Custom>,
|
||
/// Typing rules of a zoom field ([`NumberCodec::zoom_typing`]).
|
||
zoom: bool,
|
||
/// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]).
|
||
share: bool,
|
||
signed_zoom: bool,
|
||
/// A positive value is written with its `+` ([`NumberCodec::explicit_plus`]).
|
||
plus: bool,
|
||
}
|
||
|
||
impl fmt::Debug for NumberCodec {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
f.debug_struct("NumberCodec")
|
||
.field("reader", &self.reader)
|
||
.field("decimals", &self.decimals)
|
||
.field("fixed", &self.fixed)
|
||
.field("zoom", &self.zoom)
|
||
.field("share", &self.share)
|
||
.field("signed_zoom", &self.signed_zoom)
|
||
.field("plus", &self.plus)
|
||
.field("custom", &self.custom.is_some())
|
||
.field("primary", &self.primary.is_some())
|
||
.finish()
|
||
}
|
||
}
|
||
|
||
impl PartialEq for NumberCodec {
|
||
fn eq(&self, other: &Self) -> bool {
|
||
let same_custom = match (&self.custom, &other.custom) {
|
||
(None, None) => true,
|
||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||
_ => false,
|
||
};
|
||
let same_primary = match (&self.primary, &other.primary) {
|
||
(None, None) => true,
|
||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||
_ => false,
|
||
};
|
||
self.reader == other.reader
|
||
&& self.decimals == other.decimals
|
||
&& self.fixed == other.fixed
|
||
&& self.zoom == other.zoom
|
||
&& self.share == other.share
|
||
&& self.signed_zoom == other.signed_zoom
|
||
&& self.plus == other.plus
|
||
&& same_custom
|
||
&& same_primary
|
||
}
|
||
}
|
||
|
||
/// The decimal places a step needs to be written exactly: 2 for 0.25, 3 for 0.001, 0 for a whole step. A step with
|
||
/// no finite decimal form within `MAX_STEP_DECIMALS` places gets that many.
|
||
pub fn decimals_for_step(step: f64) -> usize {
|
||
let step = step.abs();
|
||
if !step.is_finite() || step == 0.0 {
|
||
return 0;
|
||
}
|
||
let mut scale = 1.0;
|
||
for places in 0..MAX_STEP_DECIMALS {
|
||
let scaled = step * scale;
|
||
if (scaled - scaled.round()).abs() <= scaled.max(1.0) * STEP_TOLERANCE {
|
||
return places;
|
||
}
|
||
scale *= 10.0;
|
||
}
|
||
MAX_STEP_DECIMALS
|
||
}
|
||
|
||
/// The most places `decimals_for_step` reports.
|
||
const MAX_STEP_DECIMALS: usize = 12;
|
||
|
||
/// How far a scaled step may sit from a whole number, relative to its size, and still count as whole.
|
||
const STEP_TOLERANCE: f64 = 1e-9;
|
||
|
||
/// The widest number a field is sized for.
|
||
const NUMBER_SAMPLE: &str = "0000.00";
|
||
|
||
impl NumberCodec {
|
||
/// A codec reading with `reader` and writing at most `decimals` decimal places.
|
||
pub fn new(reader: Reader, decimals: usize) -> Self {
|
||
NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, share: false, signed_zoom: false, plus: false }
|
||
}
|
||
|
||
/// The same codec writing a positive value with its sign ("+2.50"), as an angle or an offset from a neutral value
|
||
/// reads; a value that rounds to zero at the codec's decimals stays unsigned ("0.00"). A leading `+` in typed text
|
||
/// is then the number's sign, as the field writes it, not the relative `+` of a plain field (which adds to the
|
||
/// value the edit started from). An authoritative [`parse_with`](Self::parse_with) reader still receives the whole
|
||
/// input, including the sign.
|
||
pub fn explicit_plus(mut self) -> Self {
|
||
self.plus = true;
|
||
self
|
||
}
|
||
|
||
/// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown
|
||
/// at a set precision does.
|
||
pub fn fixed(mut self) -> Self {
|
||
self.fixed = true;
|
||
self
|
||
}
|
||
|
||
/// The same codec with the typing rules of a zoom field: digits, `/` and the decimal separator, `a/b` as the
|
||
/// percentage `a ÷ b × 100`, and a second separator cutting the text.
|
||
pub fn zoom_typing(mut self) -> Self {
|
||
self.zoom = true;
|
||
self
|
||
}
|
||
|
||
/// Allow a leading minus in zoom input so the field can reject negative values instead of discarding the sign.
|
||
pub fn signed_zoom(mut self) -> Self {
|
||
self.signed_zoom = true;
|
||
self
|
||
}
|
||
|
||
/// The zoom reading of trimmed, non-empty `text`: the text before a second decimal separator, then `a/b` as a
|
||
/// percentage or a plain number. The filter keeps `+` and `*` out, so the reader's expressions never run.
|
||
fn read_zoom(&self, text: &str) -> Result<(f64, ParseNote), NotAValue> {
|
||
let separator = self.reader.decimal_separator();
|
||
let second = text.char_indices().filter(|&(_, c)| c == separator).nth(1).map(|(at, _)| at);
|
||
let (kept, cut) = match second {
|
||
Some(at) => (&text[..at], true),
|
||
None => (text, false),
|
||
};
|
||
if kept.strip_prefix('-').unwrap_or(kept).contains('-') {
|
||
return Err(NotAValue);
|
||
}
|
||
let number = match kept.split_once('/') {
|
||
Some((part, whole)) => {
|
||
let part = self.reader.read(part, None)?;
|
||
let whole = self.reader.read(whole, None)?;
|
||
if whole == 0.0 {
|
||
return Err(NotAValue);
|
||
}
|
||
part / whole * 100.0
|
||
}
|
||
None => self.reader.read(kept, None)?,
|
||
};
|
||
Ok((number, ParseNote { cut, ..ParseNote::default() }))
|
||
}
|
||
|
||
/// The same codec reading a lone percentage (`50%`, [`Reader::share`]) as that share of the value the edit
|
||
/// started from, as a size field does: every pass of the edit reads the same value. With no start value it is no
|
||
/// value, so it never applies as it is typed; it applies on commit.
|
||
pub fn share_of_start(mut self) -> Self {
|
||
self.share = true;
|
||
self
|
||
}
|
||
|
||
/// The same codec writing at most `decimals` decimal places.
|
||
pub fn at_most(mut self, decimals: usize) -> Self {
|
||
self.decimals = self.decimals.min(decimals);
|
||
self
|
||
}
|
||
|
||
/// The same codec with `parse` as a second reader: it runs when the reader rejects the text, so words of the
|
||
/// field's context ("Auto") can stand for numbers.
|
||
pub fn or_parse(mut self, parse: impl Fn(&str) -> Option<f64> + Send + Sync + 'static) -> Self {
|
||
self.custom = Some(Arc::new(parse));
|
||
self
|
||
}
|
||
|
||
/// The same codec with an authoritative reader for the complete, trimmed, non-empty input. It replaces the
|
||
/// reader's expressions/relative input, zoom parsing and `or_parse`: `None` or a non-finite result rejects the
|
||
/// input without fallback. Empty text still means `None`. Formatting and the character filter are unchanged.
|
||
///
|
||
/// Use this when a domain's existing grammar must own the whole value, rather than adding a word with `or_parse`.
|
||
pub fn parse_with(mut self, parse: impl Fn(&str) -> Option<f64> + Send + Sync + 'static) -> Self {
|
||
self.primary = Some(Arc::new(parse));
|
||
self
|
||
}
|
||
|
||
fn parse_builtin(&self, trimmed: &str, start: Option<f64>) -> Result<(Option<f64>, ParseNote), NotAValue> {
|
||
if self.zoom {
|
||
return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note));
|
||
}
|
||
// Without an edit-start operand the reader already treats a leading `+` as a unary sign. Take that
|
||
// path directly rather than retrying each shorter suffix, and leave signed shares as absolute amounts.
|
||
let absolute_plus = self.plus && trimmed.starts_with('+');
|
||
if self.share
|
||
&& !absolute_plus
|
||
&& let Some(share_of_start) = self.reader.share(trimmed)
|
||
{
|
||
return start.map(|start| (Some(start * share_of_start), ParseNote::default())).ok_or(NotAValue);
|
||
}
|
||
match self.reader.read_tagged(trimmed, if absolute_plus { None } else { start }) {
|
||
Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })),
|
||
Err(rejected) => self.custom.as_ref().and_then(|parse| parse(trimmed)).map(|number| (Some(number), ParseNote::default())).ok_or(rejected),
|
||
}
|
||
}
|
||
|
||
/// The widest text the codec writes for a number in `range`: the longest of each end and the number one place of
|
||
/// the last decimal inside it ("100" and "99.9" over 0 to 100 at one decimal), so a field over the range is sized
|
||
/// for any value it shows in it.
|
||
pub fn widest(&self, range: &RangeInclusive<f64>) -> String {
|
||
let (low, high) = (*range.start(), *range.end());
|
||
let place = 10f64.powi(-i32::try_from(self.decimals).unwrap_or(i32::MAX));
|
||
let inside = |end: f64, other: f64| (self.decimals > 0 && (other - end).abs() >= place).then(|| end + place.copysign(other - end));
|
||
[Some(low), Some(high), inside(low, high), inside(high, low)]
|
||
.into_iter()
|
||
.flatten()
|
||
.map(|number| self.format(&Some(number)))
|
||
.max_by_key(|text| text.chars().count())
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
/// The most decimal places the codec writes.
|
||
pub fn decimals(&self) -> usize {
|
||
self.decimals
|
||
}
|
||
|
||
/// The reader the codec parses with.
|
||
pub fn reader(&self) -> &Reader {
|
||
&self.reader
|
||
}
|
||
|
||
/// Whether the codec writes a positive value with its `+` ([`NumberCodec::explicit_plus`]): its own text then
|
||
/// starts with a sign that is the number's, not a relative edit.
|
||
pub fn writes_sign(&self) -> bool {
|
||
self.plus
|
||
}
|
||
}
|
||
|
||
impl Default for NumberCodec {
|
||
fn default() -> Self {
|
||
NumberCodec::new(Reader::new(), 3)
|
||
}
|
||
}
|
||
|
||
impl Codec for NumberCodec {
|
||
type Value = Option<f64>;
|
||
|
||
fn format(&self, v: &Option<f64>) -> String {
|
||
let Some(number) = v else { return String::new() };
|
||
let written = format!("{number:.*}", self.decimals);
|
||
// A value that rounds to zero at these decimals carries no sign.
|
||
let fixed = match written.strip_prefix('-') {
|
||
Some(digits) if digits.bytes().all(|byte| matches!(byte, b'0' | b'.')) => digits,
|
||
_ => &written,
|
||
};
|
||
let trimmed = if self.fixed {
|
||
fixed
|
||
} else if fixed.contains('.') {
|
||
fixed.trim_end_matches('0').trim_end_matches('.')
|
||
} else {
|
||
fixed
|
||
};
|
||
let shown = trimmed.replace('.', &self.reader.decimal_separator().to_string());
|
||
let zero = trimmed.bytes().all(|byte| matches!(byte, b'0' | b'.'));
|
||
if self.plus && !trimmed.starts_with('-') && !zero { format!("+{shown}") } else { shown }
|
||
}
|
||
|
||
fn parse(&self, text: &str, start: &Option<f64>) -> Result<Option<f64>, NotAValue> {
|
||
self.parse_tagged(text, start).map(|(value, _)| value)
|
||
}
|
||
|
||
/// The note's unit is the tag of the unit the text named; `None` when it named no tagged unit or a custom parser
|
||
/// read it. With zoom typing the note's `cut` says a second decimal separator cut the text.
|
||
fn parse_tagged(&self, text: &str, start: &Option<f64>) -> Result<(Option<f64>, ParseNote), NotAValue> {
|
||
let trimmed = text.trim();
|
||
if trimmed.is_empty() {
|
||
return Ok((None, ParseNote::default()));
|
||
}
|
||
if let Some(parse) = &self.primary {
|
||
return parse(trimmed).filter(|number| number.is_finite()).map(|number| (Some(number), ParseNote::default())).ok_or(NotAValue);
|
||
}
|
||
self.parse_builtin(trimmed, *start)
|
||
}
|
||
|
||
/// Zoom typing takes ASCII digits, `/` and the decimal separator, with an optional minus; other fields take every character.
|
||
fn filter(&self, c: char) -> bool {
|
||
!self.zoom || c.is_ascii_digit() || (self.signed_zoom && c == '-') || c == '/' || c == self.reader.decimal_separator()
|
||
}
|
||
|
||
fn sample(&self, _current: &Option<f64>) -> Cow<'_, str> {
|
||
Cow::Borrowed(NUMBER_SAMPLE)
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn a_value_that_rounds_to_zero_is_written_without_a_sign() {
|
||
let one = NumberCodec::new(Reader::new(), 1);
|
||
assert_eq!(one.format(&Some(-0.0)), "0");
|
||
assert_eq!(one.format(&Some(-0.04)), "0");
|
||
assert_eq!(one.format(&Some(-0.06)), "-0.1");
|
||
assert_eq!(NumberCodec::new(Reader::new(), 1).fixed().format(&Some(-0.04)), "0.0");
|
||
}
|
||
|
||
#[test]
|
||
fn an_explicit_plus_codec_writes_the_sign_of_a_positive_value() {
|
||
let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus();
|
||
assert_eq!(angle.format(&Some(2.5)), "+2.50");
|
||
assert_eq!(angle.format(&Some(-3.25)), "-3.25");
|
||
assert_eq!(angle.format(&Some(0.0)), "0.00", "zero is unsigned");
|
||
assert_eq!(angle.format(&Some(0.004)), "0.00", "a value that rounds to zero is unsigned");
|
||
assert_eq!(angle.format(&Some(-0.004)), "0.00");
|
||
assert_eq!(angle.format(&None), "");
|
||
assert_eq!(NumberCodec::new(Reader::new(), 2).explicit_plus().format(&Some(1.5)), "+1.5", "trimmed decimals keep the sign");
|
||
assert_eq!(NumberCodec::new(Reader::new(), 2).fixed().format(&Some(2.5)), "2.50", "without it a positive value has no sign");
|
||
}
|
||
|
||
#[test]
|
||
fn an_explicit_plus_codec_reads_a_leading_plus_as_the_sign() {
|
||
let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus();
|
||
assert_eq!(angle.parse("+2.50", &Some(10.0)).ok(), Some(Some(2.5)), "the written text reads back as itself, not added to the start");
|
||
assert_eq!(angle.parse(&angle.format(&Some(7.25)), &Some(-1.0)).ok(), Some(Some(7.25)));
|
||
assert_eq!(angle.parse("-3.25", &Some(10.0)).ok(), Some(Some(-3.25)));
|
||
assert_eq!(angle.parse("4", &None).ok(), Some(Some(4.0)));
|
||
assert!(angle.parse("+", &Some(1.0)).is_err(), "a lone plus is no number");
|
||
let plain = NumberCodec::new(Reader::new(), 2);
|
||
assert_eq!(plain.parse("+2", &Some(10.0)).ok(), Some(Some(12.0)), "a plain field's leading plus still adds to the start");
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod review_tests {
|
||
use super::*;
|
||
|
||
/// The `+` a field writes may be typed back with a space after it: "+ 2.50" is the number 2.5, not the relative
|
||
/// "+ 2.50" added to the start value.
|
||
#[test]
|
||
fn an_explicit_plus_codec_reads_the_space_after_the_sign() {
|
||
let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus();
|
||
assert_eq!(angle.parse("+ 2.50", &Some(10.0)).ok(), Some(Some(2.5)), "a space after the sign keeps it the number's own");
|
||
assert_eq!(angle.parse("+\t7", &Some(10.0)).ok(), Some(Some(7.0)));
|
||
assert!(angle.parse("+", &Some(10.0)).is_err(), "a lone plus stays no number");
|
||
let plain = NumberCodec::new(Reader::new(), 2);
|
||
assert_eq!(plain.parse("+ 2", &Some(10.0)).ok(), Some(Some(12.0)), "a plain field's plus still adds to the start");
|
||
// The digit after the sign may be written in any script the reader reads: Arabic-Indic ٣ is 3.
|
||
assert_eq!(angle.parse("+\u{663}", &Some(10.0)).ok(), Some(Some(3.0)), "a sign before an Arabic-Indic digit is still the number's");
|
||
// The signed text is absolute for every lead the reader accepts, an expression too: "+(2+3)" is 5, not 15.
|
||
assert_eq!(angle.parse("+(2+3)", &Some(10.0)).ok(), Some(Some(5.0)), "a signed expression is the number, not added to the start");
|
||
assert_eq!(angle.parse("+2+3", &Some(10.0)).ok(), Some(Some(5.0)), "and a signed sum reads the same as without the sign");
|
||
assert_eq!(angle.parse("-(2+3)", &Some(10.0)).ok(), Some(Some(-5.0)), "a minus stays absolute, as it was");
|
||
assert_eq!(plain.parse("+(2+3)", &Some(10.0)).ok(), Some(Some(15.0)), "a plain field still adds a leading plus to the start");
|
||
// A word the field's own parser stands for is given the text as it was typed, `+` and all.
|
||
let named = NumberCodec::new(Reader::new(), 2).explicit_plus().or_parse(|text| (text == "+Auto").then_some(42.0));
|
||
assert_eq!(named.parse("+Auto", &Some(10.0)).ok(), Some(Some(42.0)), "a custom parser still sees the signed text");
|
||
assert_eq!(named.parse("+2", &Some(10.0)).ok(), Some(Some(2.0)), "while a number after the sign stays absolute");
|
||
assert_eq!(angle.parse("\u{663}", &Some(10.0)).ok(), Some(Some(3.0)), "and the reader reads that digit as before");
|
||
assert_eq!(plain.parse("+\u{663}", &Some(10.0)).ok(), Some(Some(13.0)), "a plain field still adds it to the start");
|
||
}
|
||
|
||
/// A share field's signed percentage is that number, not a share of the start value again.
|
||
#[test]
|
||
fn an_explicit_plus_share_codec_reads_a_signed_percentage_as_the_number() {
|
||
let share = NumberCodec::new(Reader::new().unit("%", 1.0), 0).share_of_start().explicit_plus();
|
||
assert_eq!(share.parse("+50%", &Some(10.0)).ok(), Some(Some(50.0)), "a signed percentage is absolute");
|
||
assert_eq!(share.parse("50%", &Some(10.0)).ok(), Some(Some(5.0)), "an unsigned one is the share of the start");
|
||
assert_eq!(share.parse("+50", &Some(10.0)).ok(), Some(Some(50.0)), "and a signed number is absolute too");
|
||
}
|
||
#[test]
|
||
fn explicit_plus_still_gives_the_authoritative_reader_the_whole_signed_input() {
|
||
let codec = NumberCodec::default().parse_with(|text| (text == "+12").then_some(17.0)).explicit_plus();
|
||
assert_eq!(codec.parse(" +12 ", &Some(50.0)), Ok(Some(17.0)));
|
||
assert_eq!(codec.parse("+(2+3)", &Some(50.0)), Err(NotAValue), "rejects instead of falling back to the expression reader");
|
||
assert_eq!(codec.format(&Some(17.0)), "+17");
|
||
}
|
||
|
||
#[test]
|
||
fn an_explicit_plus_codec_reads_a_long_run_of_unary_signs_without_recursing() {
|
||
let codec = NumberCodec::default().explicit_plus();
|
||
let long = "+ ".repeat(32_768);
|
||
assert_eq!(codec.parse(&format!("{long}--(2+3)"), &Some(10.0)), Ok(Some(5.0)));
|
||
assert_eq!(codec.parse(&long, &Some(10.0)), Err(NotAValue));
|
||
}
|
||
}
|