lichtung_plot/numeric/
function.rs1use std::sync::Arc;
4
5use super::context::{NumericLabels, NumericSetContext, NumericValueContext};
6use super::format::NumericFormat;
7use crate::Result;
8
9#[cfg(test)]
10mod tests;
11
12type ValueFunction = dyn for<'a> Fn(&NumericValueContext<'a>) -> Result<String> + Send + Sync;
13type SetFunction = dyn for<'a> Fn(&NumericSetContext<'a>) -> Result<NumericLabels> + Send + Sync;
14
15enum Function {
16 Value(Box<ValueFunction>),
17 Set(Box<SetFunction>),
18}
19
20#[derive(Clone, Default)]
21pub(crate) struct Emitter(Option<Arc<Function>>);
22impl std::fmt::Debug for Emitter {
23 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 formatter.write_str(match self.0.as_deref() {
25 None => "Builtin",
26 Some(Function::Value(_)) => "ValueFunction",
27 Some(Function::Set(_)) => "SetFunction",
28 })
29 }
30}
31impl PartialEq for Emitter {
32 fn eq(&self, other: &Self) -> bool {
33 match (&self.0, &other.0) {
34 (None, None) => true,
35 (Some(a), Some(b)) => Arc::ptr_eq(a, b),
36 _ => false,
37 }
38 }
39}
40impl Eq for Emitter {}
41
42impl Emitter {
43 pub(crate) const fn is_builtin(&self) -> bool {
44 self.0.is_none()
45 }
46 pub(super) fn call(&self, context: &NumericSetContext<'_>) -> Result<NumericLabels> {
47 match self.0.as_deref() {
48 None => context.format_builtin(),
49 Some(Function::Set(function)) => {
50 crate::operation::checkpoint()?;
51 crate::operation::work(1)?;
52 let result = crate::operation::external(|| function(context))?;
53 crate::operation::checkpoint()?;
54 Ok(result)
55 }
56 Some(Function::Value(function)) => {
57 let labels = crate::data::source::collect_source((0..context.values().len()).map(
58 |index| {
59 crate::operation::checkpoint()?;
60 crate::operation::work(1)?;
61 let label = crate::operation::external(|| {
62 function(&NumericValueContext {
63 set: context,
64 index,
65 })
66 })?;
67 crate::operation::checkpoint()?;
68 Ok(label)
69 },
70 ))?;
71 Ok(NumericLabels::new(labels))
72 }
73 }
74 }
75}
76
77impl NumericFormat {
78 #[must_use]
80 pub fn value_function<F>(mut self, function: F) -> Self
81 where
82 F: for<'a> Fn(&NumericValueContext<'a>) -> Result<String> + Send + Sync + 'static,
83 {
84 self.emitter = Emitter(Some(Arc::new(Function::Value(Box::new(function)))));
85 self
86 }
87 #[must_use]
89 pub fn set_function<F>(mut self, function: F) -> Self
90 where
91 F: for<'a> Fn(&NumericSetContext<'a>) -> Result<NumericLabels> + Send + Sync + 'static,
92 {
93 self.emitter = Emitter(Some(Arc::new(Function::Set(Box::new(function)))));
94 self
95 }
96 #[must_use]
98 pub fn builtin(mut self) -> Self {
99 self.emitter = Emitter::default();
100 self
101 }
102}