1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::fmt::{Debug, Display, Formatter, Result};
use std::rc::Rc;
use crate::AnyValue;

pub struct Fmt<F>(pub F)
    where
        F: Fn(&mut Formatter) -> Result;

impl<F> Debug for Fmt<F>
    where
        F: Fn(&mut Formatter) -> Result,
{
    fn fmt(&self, f: &mut Formatter) -> Result {
        (self.0)(f)
    }
}

impl<F> Display for Fmt<F>
    where
        F: Fn(&mut Formatter) -> Result,
{
    fn fmt(&self, f: &mut Formatter) -> Result {
        (self.0)(f)
    }
}

pub(crate) type DebugFmtFn = Rc<dyn Fn(&AnyValue, &mut Formatter) -> Result>;

#[cfg(feature = "printing")]
pub fn get_debug_fmt_fn<T>(param: &T) -> Option<DebugFmtFn> {
    trait Detect {
        fn fmt_fn(&self) -> Option<DebugFmtFn>;
    }
    impl<T> Detect for T {
        default fn fmt_fn(&self) -> Option<DebugFmtFn> {
            None
        }
    }
    impl<T> Detect for T
        where
            T: Debug + 'static,
    {
        fn fmt_fn(&self) -> Option<DebugFmtFn> {
            Some(Rc::new(|value: &AnyValue, f: &mut Formatter<'_>| {
                <Self as Debug>::fmt(value.as_ref::<T>(), f)
            }))
        }
    }
    param.fmt_fn()
}
#[cfg(not(feature = "printing"))]
pub fn get_debug_fmt_fn<T>(param: &T) -> Option<DebugFmtFn> {
    None
}

pub(crate) type DisplayFmtFn = Rc<dyn Fn(&AnyValue, &mut Formatter) -> Result>;
#[cfg(feature = "printing")]
pub fn get_display_fmt_fn<T>(param: &T) -> Option<DisplayFmtFn> {
    trait Detect {
        fn fmt_fn(&self) -> Option<DisplayFmtFn>;
    }
    impl<T> Detect for T {
        default fn fmt_fn(&self) -> Option<DisplayFmtFn> {
            None
        }
    }
    impl<T> Detect for T
        where
            T: Display + 'static,
    {
        fn fmt_fn(&self) -> Option<DisplayFmtFn> {
            Some(Rc::new(|value: &AnyValue, f: &mut Formatter<'_>| {
                <Self as Display>::fmt(value.as_ref::<T>(), f)
            }))
        }
    }
    param.fmt_fn()
}

#[cfg(not(feature = "printing"))]
pub fn get_display_fmt_fn<T>(param: &T) -> Option<DisplayFmtFn> {
    None
}