Skip to main content

lichtung_plot/spec/ticks/
function.rs

1//! Shared locator identity and required operation-local actual-view results.
2
3use std::sync::Arc;
4
5use crate::numeric::context::{DomainInfo, OwnerInfo};
6use crate::{
7    coordinates::AxisRef,
8    formatting::{NumericDomain, NumericOwner},
9    Result,
10};
11
12/// One immutable, actually assigned numeric-axis view.
13#[derive(Debug, Clone)]
14pub struct TickContext<'a> {
15    pub(crate) axis: AxisRef,
16    pub(crate) domain: &'a DomainInfo,
17    pub(crate) owner: &'a OwnerInfo,
18    pub(crate) span: f64,
19}
20impl<'a> TickContext<'a> {
21    /// Horizontal or vertical scientific coordinate.
22    pub const fn axis(&self) -> AxisRef {
23        self.axis
24    }
25    /// Final resolved scientific domain and provenance.
26    pub fn domain(&self) -> NumericDomain<'a> {
27        NumericDomain(self.domain)
28    }
29    /// Semantic producer, including raw facet and Canvas anchor identity.
30    pub fn owner(&self) -> NumericOwner<'a> {
31        NumericOwner(self.owner)
32    }
33    /// Actual assigned axis-parallel span in CSS pixels.
34    pub const fn span(&self) -> f64 {
35        self.span
36    }
37}
38
39/// Complete source-order positions, without labels or drawing instructions.
40#[derive(Debug, Clone)]
41pub enum TickPositions {
42    /// Raw data values, transformed by the actual scientific scale.
43    Data(Vec<f64>),
44    /// Mathematical powers of ten on an actual Log10 axis.
45    Log10Exponents(Vec<f64>),
46}
47impl From<Vec<f64>> for TickPositions {
48    fn from(values: Vec<f64>) -> Self {
49        Self::Data(values)
50    }
51}
52
53type Callback = dyn for<'a> Fn(&TickContext<'a>) -> Result<TickPositions> + Send + Sync;
54
55#[derive(Clone)]
56pub(crate) struct Function(Arc<Callback>);
57impl Function {
58    pub(super) fn new<F>(function: F) -> Self
59    where
60        F: for<'a> Fn(&TickContext<'a>) -> Result<TickPositions> + Send + Sync + 'static,
61    {
62        Self(Arc::new(function))
63    }
64    fn call(&self, context: &TickContext<'_>) -> Result<TickPositions> {
65        crate::operation::checkpoint()?;
66        let result = crate::operation::external(|| self.0(context))?;
67        crate::operation::checkpoint()?;
68        Ok(result)
69    }
70}
71impl std::fmt::Debug for Function {
72    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        formatter.write_str("PositionFunction")
74    }
75}
76impl PartialEq for Function {
77    fn eq(&self, other: &Self) -> bool {
78        Arc::ptr_eq(&self.0, &other.0)
79    }
80}
81impl Eq for Function {}
82
83#[derive(Debug, PartialEq, Eq)]
84pub(crate) struct View {
85    pub(crate) owner: OwnerInfo,
86    pub(crate) domain: DomainInfo,
87    pub(crate) axis: AxisRef,
88    pub(crate) span: u64,
89}
90
91#[derive(Debug)]
92struct Entry {
93    policy: crate::coordinates::TickGeneration,
94    view: View,
95    result: Arc<TickPositions>,
96}
97
98#[derive(Debug, Default)]
99pub(crate) struct PositionTable {
100    entries: Vec<Entry>,
101    sealed: bool,
102}
103impl PositionTable {
104    pub(crate) fn seal(&mut self) {
105        self.sealed = true;
106        self.entries.clear();
107    }
108
109    pub(crate) fn materialize(
110        table: &std::sync::Mutex<Self>,
111        policy: &crate::coordinates::TickGeneration,
112        view: View,
113    ) -> Result<Arc<TickPositions>> {
114        let synchronized = table
115            .lock()
116            .map_err(|_| crate::Error::Render("position table synchronization failed".into()))?;
117        if synchronized.sealed {
118            return Err(crate::Error::Render(
119                "tick positions requested after final root sealing".into(),
120            ));
121        }
122        if let Some(entry) = synchronized
123            .entries
124            .iter()
125            .find(|entry| entry.policy == *policy && entry.view == view)
126        {
127            return Ok(entry.result.clone());
128        }
129        drop(synchronized);
130        let function = policy
131            .position_function()
132            .ok_or_else(|| crate::Error::Render("position source lacks its function".into()))?;
133        let result = function
134            .call(&TickContext {
135                axis: view.axis,
136                domain: &view.domain,
137                owner: &view.owner,
138                span: f64::from_bits(view.span),
139            })
140            .map_err(|error| contextual(error, &view))?;
141        let result = crate::data::source::source_arc(result)?;
142        let mut synchronized = table
143            .lock()
144            .map_err(|_| crate::Error::Render("position table synchronization failed".into()))?;
145        crate::data::source::reserve_source(&mut synchronized.entries, 1)?;
146        synchronized.entries.push(Entry {
147            policy: policy.clone(),
148            view,
149            result: result.clone(),
150        });
151        Ok(result)
152    }
153}
154
155fn contextual(error: crate::Error, view: &View) -> crate::Error {
156    let context = format!("{:?} position function for {:?}", view.axis, view.owner);
157    error.with_prefix(&context)
158}