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