to_display/
context.rs

1#[derive(Default, Clone, Debug, Copy, PartialEq, Eq)]
2pub enum LocalOrUTC {
3    #[default]
4    Local,
5    Utc,
6}
7
8/// Configuration that controls how values are formatted.
9///
10/// This configuration is created when [`ToDisplay::display_with_context()`] is called
11/// and propagates to all nested display implementations.
12///
13/// This struct is used by the [`Display`] implementation to get the current formatting
14/// specification.
15///
16/// [`Display`]: std::fmt::Display
17/// [`ToDisplay::display_with_context()`]: crate::ToDisplay::display_with_context
18#[derive(Default, Clone, Debug, Copy)]
19pub struct Context {
20    pub(crate) verbose: Option<bool>,
21    pub(crate) max_items: Option<usize>,
22    pub(crate) local_or_utc: Option<LocalOrUTC>,
23    pub(crate) time_format: Option<&'static str>,
24}
25
26impl Context {
27    /// Returns whether verbose formatting is enabled.
28    ///
29    /// When enabled:
30    /// - `Option` values show as `Some(v)` or `None` instead of `v` or `-`
31    /// - Collections may include type information
32    /// - Additional details may be included depending on the type
33    pub fn verbose(&self) -> bool {
34        self.verbose.unwrap_or(false)
35    }
36
37    /// Returns the maximum number of items to display for collections.
38    ///
39    /// This affects the formatting of slices, vectors, maps, and similar collections.
40    /// When a collection exceeds this limit, it will be truncated with "...".
41    ///
42    /// Defaults to 32 items.
43    pub fn max_items(&self) -> usize {
44        self.max_items.unwrap_or(32)
45    }
46
47    /// Returns whether times should be displayed in local time.
48    pub fn is_local_time(&self) -> bool {
49        self.local_or_utc.unwrap_or_default() == LocalOrUTC::Local
50    }
51
52    /// Returns whether times should be displayed in UTC.
53    pub fn is_utc_time(&self) -> bool {
54        self.local_or_utc.unwrap_or_default() == LocalOrUTC::Utc
55    }
56
57    /// Returns the time format string used for formatting timestamps.
58    ///
59    /// Format options:
60    /// - Default/`"SIMPLE"`: `"%H:%M:%S%.6f"` (e.g., "23:59:59.123456")
61    /// - `"FULL"`: `"%Y-%m-%dT%H:%M:%S%.6fZ%z"` (e.g., "2024-12-28T23:59:59.123456Z+0800")
62    /// - Custom format string using [strftime format specifiers](https://docs.rs/chrono/latest/chrono/format/strftime/index.html)
63    pub fn time_format(&self) -> &'static str {
64        const SIMPLE_FORMAT: &str = "%H:%M:%S%.6f";
65        const FULL_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.6fZ%z";
66
67        match self.time_format {
68            Some("SIMPLE") => SIMPLE_FORMAT,
69            Some("FULL") => FULL_FORMAT,
70            Some(format) => format,
71            None => SIMPLE_FORMAT,
72        }
73    }
74}