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 let result = crate::operation::external(|| function(context))?;
52 crate::operation::checkpoint()?;
53 Ok(result)
54 }
55 Some(Function::Value(function)) => {
56 let labels = crate::data::source::collect_source((0..context.values().len()).map(
57 |index| {
58 crate::operation::checkpoint()?;
59 let label = crate::operation::external(|| {
60 function(&NumericValueContext {
61 set: context,
62 index,
63 })
64 })?;
65 crate::operation::checkpoint()?;
66 Ok(label)
67 },
68 ))?;
69 Ok(NumericLabels::new(labels))
70 }
71 }
72 }
73}
74
75impl NumericFormat {
76 #[must_use]
78 pub fn value_function<F>(mut self, function: F) -> Self
79 where
80 F: for<'a> Fn(&NumericValueContext<'a>) -> Result<String> + Send + Sync + 'static,
81 {
82 self.emitter = Emitter(Some(Arc::new(Function::Value(Box::new(function)))));
83 self
84 }
85 #[must_use]
87 pub fn set_function<F>(mut self, function: F) -> Self
88 where
89 F: for<'a> Fn(&NumericSetContext<'a>) -> Result<NumericLabels> + Send + Sync + 'static,
90 {
91 self.emitter = Emitter(Some(Arc::new(Function::Set(Box::new(function)))));
92 self
93 }
94 #[must_use]
96 pub fn builtin(mut self) -> Self {
97 self.emitter = Emitter::default();
98 self
99 }
100}