Skip to main content

ferrochart_core/
price_scale.rs

1//! Price scales: value-to-y mapping (`y = a * f(p) + b`, `f` = identity or `ln`),
2//! auto-scaling, "nice number" ticks and price formatting.
3//!
4
5use core::fmt::Write;
6
7use crate::error::{Error, Result};
8use crate::frame::{PriceMapping, YTransform};
9
10/// Price scale mode.
11///
12/// In `Percentage` and `IndexedTo100` mode every series of the scale is
13/// normalized to its own first visible value (the close of the first visible
14/// bar, or the first visible value of a value series), so series with
15/// different price levels can be compared. The scale's range, ticks,
16/// labels and crosshair price are then in percent / index points.
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19pub enum PriceScaleMode {
20    /// Linear prices.
21    #[default]
22    Normal,
23    /// Logarithmic prices.
24    Logarithmic,
25    /// Percent change from the first visible value: `(p - base) / |base| × 100`.
26    Percentage,
27    /// Indexed to 100 at the first visible value: `p / |base| × 100`.
28    IndexedTo100,
29}
30
31impl PriceScaleMode {
32    /// Whether values are normalized to a per-series base.
33    pub fn is_relative(self) -> bool {
34        matches!(self, Self::Percentage | Self::IndexedTo100)
35    }
36}
37
38/// The linear map `d = k·p + c` from a series' prices to the values its scale
39/// shows: the identity, or the percent change from /
40/// index to 100 at the series' base value.
41#[derive(Clone, Copy, Debug, PartialEq)]
42pub(crate) struct Normalize {
43    k: f64,
44    c: f64,
45}
46
47impl Normalize {
48    pub(crate) const IDENTITY: Self = Self { k: 1.0, c: 0.0 };
49
50    /// The map for `mode` with base value `base`; the identity for absolute
51    /// modes, `None` if a relative mode has no usable base (zero or not finite).
52    pub(crate) fn new(mode: PriceScaleMode, base: Option<f64>) -> Option<Self> {
53        if !mode.is_relative() {
54            return Some(Self::IDENTITY);
55        }
56        let base = base.filter(|b| b.is_finite() && *b != 0.0)?;
57        let k = 100.0 / base.abs();
58        let c = if mode == PriceScaleMode::Percentage {
59            -100.0 * base.signum()
60        } else {
61            0.0
62        };
63        Some(Self { k, c })
64    }
65
66    /// Displayed value of price `p`.
67    pub(crate) fn apply(self, p: f64) -> f64 {
68        self.k * p + self.c
69    }
70
71    /// Price of displayed value `d`.
72    pub(crate) fn invert(self, d: f64) -> f64 {
73        (d - self.c) / self.k
74    }
75
76    /// The transform of a series from the transform of its scale: since
77    /// `y = a·(d − d_ref) + b` and `d = k·p + c`, the series uses `a·k` and the
78    /// price reference `invert(d_ref)`.
79    pub(crate) fn series_transform(self, scale: YTransform, a: f64) -> YTransform {
80        if self == Self::IDENTITY {
81            return scale;
82        }
83        YTransform {
84            a: (a * self.k) as f32,
85            view_ref: self.invert(scale.view_ref),
86            ..scale
87        }
88    }
89}
90
91/// Which side of a pane a price scale sits on.
92#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
93pub enum ScaleSide {
94    /// Left axis.
95    Left,
96    /// Right axis.
97    #[default]
98    Right,
99}
100
101/// A price scale.
102///
103/// # Examples
104///
105/// ```
106/// use ferrochart_core::{Chart, ChartOptions};
107/// use ferrochart_core::price_scale::{PriceScaleMode, ScaleSide};
108///
109/// let mut chart = Chart::new(ChartOptions::default());
110/// let pane = chart.main_pane();
111/// let scale = chart.price_scale(pane, ScaleSide::Right).unwrap();
112/// scale.set_mode(PriceScaleMode::Logarithmic)?;
113/// scale.set_range(10.0, 1000.0)?; // also turns auto-scale off
114/// assert!(!scale.auto_scale());
115/// # Ok::<(), ferrochart_core::Error>(())
116/// ```
117#[derive(Clone, Debug)]
118pub struct PriceScale {
119    mode: PriceScaleMode,
120    auto_scale: bool,
121    inverted: bool,
122    margins: (f32, f32),
123    range: (f64, f64),
124    pub(crate) changed: bool,
125}
126
127impl PriceScale {
128    pub(crate) fn new(margins: (f32, f32)) -> Self {
129        Self {
130            mode: PriceScaleMode::Normal,
131            auto_scale: true,
132            inverted: false,
133            margins,
134            range: (0.0, 1.0),
135            changed: true,
136        }
137    }
138
139    /// Current mode.
140    pub fn mode(&self) -> PriceScaleMode {
141        self.mode
142    }
143
144    /// Sets the mode. Switching between price modes (`Normal`,
145    /// `Logarithmic`) and relative modes (`Percentage`, `IndexedTo100`)
146    /// turns auto-scaling on, because the old range is in other units.
147    ///
148    /// # Errors
149    ///
150    /// None so far; the `Result` leaves room for modes with preconditions.
151    ///
152    /// # Examples
153    ///
154    /// ```
155    /// use ferrochart_core::{Chart, ChartOptions};
156    /// use ferrochart_core::price_scale::{PriceScaleMode, ScaleSide};
157    ///
158    /// let mut chart = Chart::new(ChartOptions::default());
159    /// let pane = chart.main_pane();
160    /// let scale = chart.price_scale(pane, ScaleSide::Right).unwrap();
161    /// scale.set_range(90.0, 110.0)?;
162    /// scale.set_mode(PriceScaleMode::Percentage)?;
163    /// assert!(scale.auto_scale());
164    /// # Ok::<(), ferrochart_core::Error>(())
165    /// ```
166    pub fn set_mode(&mut self, mode: PriceScaleMode) -> Result<()> {
167        if mode.is_relative() != self.mode.is_relative() {
168            self.auto_scale = true;
169        }
170        self.mode = mode;
171        self.changed = true;
172        Ok(())
173    }
174
175    /// Whether the range follows the visible data.
176    pub fn auto_scale(&self) -> bool {
177        self.auto_scale
178    }
179
180    /// Turns auto-scaling on or off.
181    pub fn set_auto_scale(&mut self, on: bool) {
182        self.auto_scale = on;
183        self.changed = true;
184    }
185
186    /// Whether higher prices are drawn lower.
187    pub fn inverted(&self) -> bool {
188        self.inverted
189    }
190
191    /// Inverts the scale.
192    pub fn set_inverted(&mut self, inverted: bool) {
193        self.inverted = inverted;
194        self.changed = true;
195    }
196
197    /// Top and bottom margins as fractions of the pane height.
198    pub fn margins(&self) -> (f32, f32) {
199        self.margins
200    }
201
202    /// Sets the top and bottom margins.
203    ///
204    /// # Errors
205    ///
206    /// [`Error::InvalidArgument`] unless both are in `[0, 1)` and their sum is `< 1`.
207    pub fn set_margins(&mut self, top: f32, bottom: f32) -> Result<()> {
208        let ok = |m: f32| (0.0..1.0).contains(&m);
209        if !(ok(top) && ok(bottom) && top + bottom < 1.0) {
210            return Err(Error::InvalidArgument(
211                "margins must be in [0, 1) and sum < 1",
212            ));
213        }
214        self.margins = (top, bottom);
215        self.changed = true;
216        Ok(())
217    }
218
219    /// Current price range `(low, high)` (without margins).
220    pub fn range(&self) -> (f64, f64) {
221        self.range
222    }
223
224    /// Sets the price range and turns auto-scaling off.
225    ///
226    /// # Errors
227    ///
228    /// [`Error::InvalidArgument`] unless `low < high`, both finite, and (in
229    /// logarithmic mode) `low > 0`.
230    pub fn set_range(&mut self, low: f64, high: f64) -> Result<()> {
231        if !(low.is_finite() && high.is_finite() && low < high) {
232            return Err(Error::InvalidArgument(
233                "price range must be finite with low < high",
234            ));
235        }
236        if self.mode == PriceScaleMode::Logarithmic && low <= 0.0 {
237            return Err(Error::InvalidArgument(
238                "logarithmic price range must be positive",
239            ));
240        }
241        self.range = (low, high);
242        self.auto_scale = false;
243        self.changed = true;
244        Ok(())
245    }
246
247    fn mapping(&self) -> PriceMapping {
248        match self.mode {
249            PriceScaleMode::Logarithmic => PriceMapping::Log,
250            _ => PriceMapping::Linear,
251        }
252    }
253
254    fn f(&self, p: f64) -> f64 {
255        match self.mapping() {
256            PriceMapping::Linear => p,
257            PriceMapping::Log => p.ln(),
258        }
259    }
260
261    fn f_inv(&self, v: f64) -> f64 {
262        match self.mapping() {
263            PriceMapping::Linear => v,
264            PriceMapping::Log => v.exp(),
265        }
266    }
267
268    /// Auto-scale: sets the range to `(low, high)`, widening degenerate ranges.
269    pub(crate) fn fit(&mut self, low: f64, high: f64) {
270        if !(self.auto_scale && low.is_finite() && high.is_finite()) {
271            return;
272        }
273        let (mut lo, mut hi) = (low.min(high), low.max(high));
274        if self.mapping() == PriceMapping::Log {
275            if hi <= 0.0 {
276                return;
277            }
278            lo = lo.max(hi * 1e-9);
279        }
280        if hi - lo <= hi.abs() * 1e-12 {
281            let pad = if hi == 0.0 { 1.0 } else { hi.abs() * 0.01 };
282            lo -= pad;
283            hi += pad;
284            if self.mapping() == PriceMapping::Log {
285                lo = lo.max(hi * 1e-9);
286            }
287        }
288        self.range = (lo, hi);
289    }
290
291    /// Price at the vertical center of the current range.
292    pub(crate) fn center_price(&self) -> f64 {
293        self.f_inv((self.f(self.range.0) + self.f(self.range.1)) * 0.5)
294    }
295
296    fn set_interactive_range(&mut self, flo: f64, fhi: f64) {
297        let (lo, hi) = (self.f_inv(flo), self.f_inv(fhi));
298        if lo.is_finite() && hi.is_finite() && hi > lo && hi - lo > hi.abs().max(lo.abs()) * 1e-12 {
299            self.range = (lo, hi);
300            self.auto_scale = false;
301            self.changed = true;
302        }
303    }
304
305    /// Scales the range by `factor` (> 1 shows more) around `center`, turning
306    /// auto-scale off (price-axis drag, Alt + wheel).
307    pub(crate) fn zoom_around(&mut self, factor: f64, center: f64) {
308        let c = self.f(center);
309        if !(factor.is_finite() && factor > 0.0 && c.is_finite()) {
310            return;
311        }
312        let (fl, fh) = (self.f(self.range.0), self.f(self.range.1));
313        self.set_interactive_range(c - (c - fl) * factor, c + (fh - c) * factor);
314    }
315
316    /// Moves the content down by `dy` px in a pane of `height` px, turning
317    /// auto-scale off.
318    pub(crate) fn pan_px(&mut self, dy: f64, height: f64) {
319        let usable = height * (1.0 - f64::from(self.margins.0) - f64::from(self.margins.1));
320        if !(usable > 0.0 && dy.is_finite()) || dy == 0.0 {
321            return;
322        }
323        let (fl, fh) = (self.f(self.range.0), self.f(self.range.1));
324        let d = (fh - fl) * dy / usable;
325        let d = if self.inverted { -d } else { d };
326        self.set_interactive_range(fl + d, fh + d);
327    }
328
329    /// The f32 transform for a pane spanning `top..top + height` (physical
330    /// px), for the values the scale shows; series of relative scales use
331    /// [`series_transform`](Self::series_transform).
332    pub(crate) fn transform(&self, top: f64, height: f64) -> YTransform {
333        self.transform_and_a(top, height).0
334    }
335
336    /// The transform of a series normalized by `norm`.
337    pub(crate) fn series_transform(&self, top: f64, height: f64, norm: Normalize) -> YTransform {
338        let (t, a) = self.transform_and_a(top, height);
339        norm.series_transform(t, a)
340    }
341
342    fn transform_and_a(&self, top: f64, height: f64) -> (YTransform, f64) {
343        let (mt, mb) = (f64::from(self.margins.0), f64::from(self.margins.1));
344        let (fl, fh) = (self.f(self.range.0), self.f(self.range.1));
345        let usable = height * (1.0 - mt - mb);
346        let span = (fh - fl).max(f64::MIN_POSITIVE);
347        let a = if self.inverted {
348            usable / span
349        } else {
350            -usable / span
351        };
352        let view = (fl + fh) * 0.5;
353        let b = top + mt * height + usable * 0.5;
354        let t = YTransform {
355            a: a as f32,
356            b: b as f32,
357            view_ref: self.f_inv(view),
358            mapping: self.mapping(),
359        };
360        (t, a)
361    }
362
363    /// y (f64) of price `p` in a pane spanning `top..top + height`.
364    pub(crate) fn price_to_y(&self, p: f64, top: f64, height: f64) -> f64 {
365        let (mt, mb) = (f64::from(self.margins.0), f64::from(self.margins.1));
366        let (fl, fh) = (self.f(self.range.0), self.f(self.range.1));
367        let usable = height * (1.0 - mt - mb);
368        let t = (self.f(p) - fl) / (fh - fl).max(f64::MIN_POSITIVE);
369        let from_top = mt * height + usable * (1.0 - t);
370        if self.inverted {
371            top + height - from_top
372        } else {
373            top + from_top
374        }
375    }
376
377    /// Price at y in a pane spanning `top..top + height`.
378    pub(crate) fn y_to_price(&self, y: f64, top: f64, height: f64) -> f64 {
379        let (mt, mb) = (f64::from(self.margins.0), f64::from(self.margins.1));
380        let (fl, fh) = (self.f(self.range.0), self.f(self.range.1));
381        let usable = (height * (1.0 - mt - mb)).max(f64::MIN_POSITIVE);
382        let from_top = if self.inverted {
383            top + height - y
384        } else {
385            y - top
386        };
387        let t = 1.0 - (from_top - mt * height) / usable;
388        self.f_inv(fl + t * (fh - fl))
389    }
390
391    /// Tick prices for a pane of `height` px, at least `min_spacing` px apart,
392    /// written to `out` (cleared first, sorted ascending). No allocation once
393    /// `out` has capacity.
394    pub(crate) fn ticks(&self, height: f64, min_spacing: f64, out: &mut Vec<f64>) {
395        out.clear();
396        if height <= 0.0 || min_spacing <= 0.0 {
397            return;
398        }
399        let p_a = self.y_to_price(0.0, 0.0, height);
400        let p_b = self.y_to_price(height, 0.0, height);
401        let (lo, hi) = (p_a.min(p_b), p_a.max(p_b));
402        if self.mapping() == PriceMapping::Log && lo > 0.0 {
403            log_ticks(lo, hi, height, min_spacing, out);
404        } else {
405            linear_ticks(lo, hi, height, min_spacing, out);
406        }
407    }
408}
409
410/// Ticks for values `lo..=hi` on a linear axis `length` px long, at least
411/// `min_spacing` px apart: multiples of a nice step `{1, 2, 2.5, 5} × 10^k`.
412/// Written to `out` (cleared first, ascending); at most 1000 ticks;
413/// no allocation once `out` has capacity.
414///
415/// ```
416/// use ferrochart_core::price_scale::linear_ticks;
417///
418/// let mut out = Vec::new();
419/// linear_ticks(0.0, 100.0, 500.0, 100.0, &mut out);
420/// assert_eq!(out, [0.0, 20.0, 40.0, 60.0, 80.0, 100.0]);
421/// ```
422pub fn linear_ticks(lo: f64, hi: f64, length: f64, min_spacing: f64, out: &mut Vec<f64>) {
423    let to_px = |p: f64| (p - lo) / (hi - lo) * length;
424    nice_ticks(lo, hi, length, min_spacing, to_px, out);
425}
426
427/// Ticks for positive values `lo..=hi` on a logarithmic axis `length` px
428/// long, at least `min_spacing` px apart: powers of ten, then 2 and 5 of each
429/// decade; ranges under one decade use linear nice steps spaced on the log
430/// axis. Written to `out` (cleared first, ascending); empty for `lo <= 0`.
431///
432/// ```
433/// use ferrochart_core::price_scale::log_ticks;
434///
435/// let mut out = Vec::new();
436/// log_ticks(1.0, 1000.0, 600.0, 30.0, &mut out);
437/// assert!(out.contains(&1.0) && out.contains(&10.0) && out.contains(&1000.0));
438/// ```
439pub fn log_ticks(lo: f64, hi: f64, length: f64, min_spacing: f64, out: &mut Vec<f64>) {
440    out.clear();
441    if lo.is_nan() || lo <= 0.0 {
442        return;
443    }
444    let (fl, fh) = (lo.ln(), hi.ln());
445    let to_px = |p: f64| (p.ln() - fl) / (fh - fl) * length;
446    if (hi / lo).log10() >= 1.0 {
447        if !(hi.is_finite() && lo < hi && length > 0.0 && min_spacing > 0.0) {
448            return;
449        }
450        let d0 = lo.log10().floor() as i32;
451        let d1 = hi.log10().ceil() as i32;
452        // Powers of ten first, then 2 and 5 in each decade, each only if spaced.
453        for mults in [&[1.0][..], &[2.0, 5.0][..]] {
454            for d in d0..=d1 {
455                for &m in mults {
456                    let p = m * 10f64.powi(d);
457                    if (lo..=hi).contains(&p) && out.len() < 1000 {
458                        push_spaced(out, p, to_px, min_spacing);
459                    }
460                }
461            }
462        }
463        out.sort_unstable_by(f64::total_cmp);
464    } else {
465        nice_ticks(lo, hi, length, min_spacing, to_px, out);
466    }
467}
468
469/// Nice-step ticks in `lo..=hi`, spaced by `to_px`.
470fn nice_ticks(
471    lo: f64,
472    hi: f64,
473    length: f64,
474    min_spacing: f64,
475    to_px: impl Fn(f64) -> f64,
476    out: &mut Vec<f64>,
477) {
478    out.clear();
479    if length <= 0.0 || min_spacing <= 0.0 || !(lo.is_finite() && hi.is_finite()) || lo >= hi {
480        return;
481    }
482    let max_ticks = (length / min_spacing).floor().max(1.0);
483    let mut step = nice_step((hi - lo) / max_ticks);
484    // A step close to the whole range may have no multiple inside it
485    // (short panes): fall back to smaller nice steps until one fits.
486    for _ in 0..8 {
487        if (lo / step).ceil() <= (hi / step).floor() {
488            break;
489        }
490        step = nice_step_below(step);
491    }
492    let first = (lo / step).ceil() as i64;
493    let last = (hi / step).floor() as i64;
494    for m in first..=last {
495        if out.len() >= 1000 {
496            break;
497        }
498        push_spaced(out, m as f64 * step, &to_px, min_spacing);
499    }
500    out.sort_unstable_by(f64::total_cmp);
501}
502
503/// Pushes `p` unless an existing tick is closer than `min_spacing` px.
504fn push_spaced(out: &mut Vec<f64>, p: f64, y: impl Fn(f64) -> f64, min_spacing: f64) {
505    let yp = y(p);
506    if out.iter().all(|&q| (y(q) - yp).abs() >= min_spacing) {
507        out.push(p);
508    }
509}
510
511/// Smallest "nice" step `{1, 2, 2.5, 5} × 10^k` that is `>= raw`.
512///
513/// # Examples
514///
515/// ```
516/// use ferrochart_core::price_scale::nice_step;
517///
518/// assert_eq!(nice_step(0.7), 1.0);
519/// assert_eq!(nice_step(2.2), 2.5);
520/// assert_eq!(nice_step(31.0), 50.0);
521/// assert_eq!(nice_step(0.012), 0.02);
522/// ```
523pub fn nice_step(raw: f64) -> f64 {
524    if !(raw.is_finite() && raw > 0.0) {
525        return 1.0;
526    }
527    let exp = raw.log10().floor() as i32;
528    let base = 10f64.powi(exp);
529    for m in [1.0, 2.0, 2.5, 5.0, 10.0] {
530        let step = m * base;
531        if step >= raw * (1.0 - 1e-12) {
532            return step;
533        }
534    }
535    10.0 * base
536}
537
538/// A nice step roughly 2–2.5× smaller than `step`.
539fn nice_step_below(step: f64) -> f64 {
540    nice_step(step * 0.39)
541}
542
543/// Formats prices for axis labels. Writes into a caller-provided buffer, so the
544/// hot path does not allocate once the buffer has capacity.
545///
546/// # Examples
547///
548/// ```
549/// use ferrochart_core::price_scale::{DefaultPriceFormatter, PriceFormatter};
550///
551/// let mut s = String::new();
552/// DefaultPriceFormatter { precision: Some(2) }.format(1234.5, &mut s);
553/// assert_eq!(s, "1234.50");
554/// ```
555pub trait PriceFormatter: Send {
556    /// Appends the label of `price` to `out`.
557    fn format(&self, price: f64, out: &mut String);
558}
559
560/// Fixed or automatic decimals; never prints `-0.00`.
561///
562/// With `precision: None` each price gets at least 2 decimals and 4
563/// significant digits, and prices below 1 with four or more zeros after the
564/// point are written with a subscript count (`0.0₄1234` is `0.00001234`).
565///
566/// ```
567/// use ferrochart_core::price_scale::{DefaultPriceFormatter, PriceFormatter};
568///
569/// let auto = DefaultPriceFormatter { precision: None };
570/// for (price, label) in [(63412.5, "63412.50"), (0.0123456, "0.01235"), (0.00001234, "0.0₄1234")] {
571///     let mut s = String::new();
572///     auto.format(price, &mut s);
573///     assert_eq!(s, label);
574/// }
575/// ```
576#[derive(Clone, Copy, Debug)]
577pub struct DefaultPriceFormatter {
578    /// Decimal places; `None` is automatic.
579    pub precision: Option<u8>,
580}
581
582/// Writes `price` with `precision` decimals, avoiding negative zero.
583pub(crate) fn write_price(out: &mut impl Write, price: f64, precision: u8) {
584    let scale = 10f64.powi(i32::from(precision));
585    let p = if (price * scale).round() == 0.0 {
586        0.0
587    } else {
588        price
589    };
590    let _ = write!(out, "{:.*}", usize::from(precision), p);
591}
592
593impl PriceFormatter for DefaultPriceFormatter {
594    fn format(&self, price: f64, out: &mut String) {
595        match self.precision {
596            Some(p) => write_price(out, price, p),
597            None => {
598                crate::format::write_price_auto(out, price, crate::format::auto_decimals(price));
599            }
600        }
601    }
602}
603
604/// Volume-style formatter with K/M/B suffixes (`1.25M`).
605///
606/// # Examples
607///
608/// ```
609/// use ferrochart_core::price_scale::{CompactFormatter, PriceFormatter};
610///
611/// let mut s = String::new();
612/// CompactFormatter.format(1_250_000.0, &mut s);
613/// assert_eq!(s, "1.25M");
614/// ```
615#[derive(Clone, Copy, Debug, Default)]
616pub struct CompactFormatter;
617
618impl PriceFormatter for CompactFormatter {
619    fn format(&self, v: f64, out: &mut String) {
620        write_compact(out, v);
621    }
622}
623
624/// Writes `v` with a K/M/B suffix and at most two decimals, trailing zeros of
625/// the fraction trimmed ("1.5K", "2"). Does not allocate.
626pub(crate) fn write_compact(out: &mut impl Write, v: f64) {
627    let a = v.abs();
628    let (x, suffix) = if a >= 1e9 {
629        (v / 1e9, "B")
630    } else if a >= 1e6 {
631        (v / 1e6, "M")
632    } else if a >= 1e3 {
633        (v / 1e3, "K")
634    } else {
635        (v, "")
636    };
637    let mut s = crate::text::StackStr::<48>::new();
638    write_price(&mut s, x, 2);
639    let mut digits = s.as_str();
640    // Trim trailing zeros of the fraction ("1.50K" -> "1.5K", "2.00" -> "2").
641    if digits.contains('.') {
642        digits = digits.trim_end_matches('0').trim_end_matches('.');
643    }
644    let _ = out.write_str(digits);
645    let _ = out.write_str(suffix);
646}
647
648#[cfg(test)]
649mod tests {
650    use super::*;
651    use crate::format::{auto_decimals, write_price_auto};
652    use proptest::prelude::*;
653
654    fn auto(price: f64, decimals: u8) -> String {
655        let mut s = String::new();
656        write_price_auto(&mut s, price, decimals);
657        s
658    }
659
660    #[test]
661    fn auto_decimals_keep_four_significant_digits() {
662        assert_eq!(auto_decimals(63_412.5), 2);
663        assert_eq!(auto_decimals(1.2345), 3);
664        assert_eq!(auto_decimals(0.012_345), 5);
665        assert_eq!(auto_decimals(0.000_012_34), 8);
666        assert_eq!(auto_decimals(-0.5), 4);
667        assert_eq!(auto_decimals(1e-40), 30);
668        assert_eq!(auto_decimals(0.0), 2);
669        assert_eq!(auto_decimals(f64::NAN), 2);
670        for k in -20..10 {
671            let p = 10f64.powi(k);
672            assert_eq!(auto_decimals(p), (3 - k).clamp(2, 30) as u8, "1e{k}");
673        }
674    }
675
676    #[test]
677    fn auto_writes_subscript_zeros() {
678        assert_eq!(auto(63_412.5, 2), "63412.50");
679        assert_eq!(auto(1.234_56, 3), "1.235");
680        assert_eq!(auto(0.012_345_6, 5), "0.01235");
681        assert_eq!(auto(0.000_123_4, 7), "0.0001234");
682        assert_eq!(auto(0.000_012_34, 8), "0.0₄1234");
683        assert_eq!(auto(-0.000_012_34, 8), "-0.0₄1234");
684        assert_eq!(auto(1.234e-15, 18), "0.0₁₄1234");
685        assert_eq!(auto(0.0, 8), "0");
686        assert_eq!(auto(0.0, 3), "0.000");
687        assert_eq!(auto(-1e-12, 8), "0");
688        assert_eq!(auto(0.999_99, 2), "1.00");
689        assert_eq!(auto(f64::NAN, 2), "NaN");
690    }
691
692    #[test]
693    fn no_negative_zero() {
694        let mut s = String::new();
695        write_price(&mut s, -0.001, 2);
696        assert_eq!(s, "0.00");
697    }
698
699    #[test]
700    fn log_ticks_cover_decades() {
701        let mut ps = PriceScale::new((0.0, 0.0));
702        ps.set_mode(PriceScaleMode::Logarithmic).unwrap();
703        ps.set_range(1.0, 10_000.0).unwrap();
704        let mut out = Vec::new();
705        ps.ticks(800.0, 25.0, &mut out);
706        for p in [1.0, 10.0, 100.0, 1000.0, 10_000.0] {
707            assert!(out.contains(&p), "{p} in {out:?}");
708        }
709    }
710
711    proptest! {
712        /// Linear ticks are evenly spaced nice numbers, at least `min` px apart,
713        /// and there is at least one tick for any sane range.
714        #[test]
715        fn linear_ticks_are_nice(lo in -1e6f64..1e6, span in 1e-6f64..1e6, h in 50.0f64..2000.0) {
716            let mut ps = PriceScale::new((0.1, 0.1));
717            ps.fit(lo, lo + span);
718            let mut out = Vec::new();
719            ps.ticks(h, 30.0, &mut out);
720            prop_assert!(!out.is_empty());
721            for w in out.windows(2) {
722                let dy = (ps.price_to_y(w[0], 0.0, h) - ps.price_to_y(w[1], 0.0, h)).abs();
723                prop_assert!(dy >= 30.0 - 1e-6);
724            }
725        }
726
727        /// The f32 transform agrees with the f64 mapping to well under a pixel.
728        #[test]
729        fn transform_matches_f64(lo in 1.0f64..1e5, span in 1e-3f64..1e5, t in 0.0f64..1.0, log: bool) {
730            let mut ps = PriceScale::new((0.1, 0.05));
731            if log { ps.set_mode(PriceScaleMode::Logarithmic).unwrap(); }
732            ps.fit(lo, lo + span);
733            let p = lo + t * span;
734            let yt = ps.transform(10.0, 600.0);
735            let y32 = crate::transform_helpers::y_of_price(&yt, p);
736            prop_assert!((f64::from(y32) - ps.price_to_y(p, 10.0, 600.0)).abs() < 0.01);
737        }
738    }
739}