• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

zbraniecki / icu4x / 6815798908

09 Nov 2023 05:17PM UTC coverage: 72.607% (-2.4%) from 75.01%
6815798908

push

github

web-flow
Implement `Any/BufferProvider` for some smart pointers (#4255)

Allows storing them as a `Box<dyn Any/BufferProvider>` without using a
wrapper type that implements the trait.

44281 of 60987 relevant lines covered (72.61%)

201375.86 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

48.48
/components/datetime/src/format/time_zone.rs
1
// This file is part of ICU4X. For terms of use, please see the file
204✔
2
// called LICENSE at the top level of the ICU4X source tree
3
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4

5
use core::fmt;
6

7
use crate::error::DateTimeError as Error;
8
use crate::{
9
    input::TimeZoneInput,
10
    time_zone::{FormatTimeZone, TimeZoneFormatter, TimeZoneFormatterUnit},
11
    DateTimeError,
12
};
13
use writeable::Writeable;
14

15
/// [`FormattedTimeZone`] is a intermediate structure which can be retrieved as an output from [`TimeZoneFormatter`].
16
#[derive(Debug)]
17
pub struct FormattedTimeZone<'l, T>
18
where
19
    T: TimeZoneInput,
20
{
21
    pub(crate) time_zone_format: &'l TimeZoneFormatter,
22
    pub(crate) time_zone: &'l T,
23
}
24

25
impl<'l, T> Writeable for FormattedTimeZone<'l, T>
26
where
27
    T: TimeZoneInput,
28
{
29
    /// Format time zone with fallbacks.
30
    fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
262✔
31
        match self.write_no_fallback(sink) {
262✔
32
            Ok(Ok(r)) => Ok(r),
204✔
33
            _ => match self.time_zone_format.fallback_unit {
58✔
34
                TimeZoneFormatterUnit::LocalizedGmt(fallback) => {
35
                    match fallback.format(
58✔
36
                        sink,
37
                        self.time_zone,
58✔
38
                        &self.time_zone_format.data_payloads,
58✔
39
                    ) {
40
                        Ok(Ok(r)) => Ok(r),
58✔
41
                        Ok(Err(e)) => Err(e),
×
42
                        Err(e) => self.handle_last_resort_error(e, sink),
×
43
                    }
44
                }
45
                TimeZoneFormatterUnit::Iso8601(fallback) => {
×
46
                    match fallback.format(
×
47
                        sink,
48
                        self.time_zone,
×
49
                        &self.time_zone_format.data_payloads,
×
50
                    ) {
51
                        Ok(Ok(r)) => Ok(r),
×
52
                        Ok(Err(e)) => Err(e),
×
53
                        Err(e) => self.handle_last_resort_error(e, sink),
×
54
                    }
55
                }
56
                _ => Err(core::fmt::Error),
×
57
            },
58
        }
59
    }
262✔
60

61
    // TODO(#489): Implement writeable_length_hint
62
}
63

64
impl<'l, T> fmt::Display for FormattedTimeZone<'l, T>
65
where
66
    T: TimeZoneInput,
67
{
68
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69
        self.write_to(f)
70
    }
71
}
72

73
impl<'l, T> FormattedTimeZone<'l, T>
74
where
75
    T: TimeZoneInput,
76
{
77
    /// Write time zone with no fallback.
78
    ///
79
    /// # Examples
80
    ///
81
    /// ```
82
    /// use icu::datetime::time_zone::TimeZoneFormatter;
83
    /// use icu::datetime::DateTimeError;
84
    /// use icu::locid::locale;
85
    /// use icu::timezone::CustomTimeZone;
86
    /// use tinystr::tinystr;
87
    ///
88
    /// let mut tzf =
89
    ///     TimeZoneFormatter::try_new(&locale!("en").into(), Default::default())
90
    ///         .unwrap();
91
    /// let mut buf = String::new();
92
    ///
93
    /// let mut time_zone = "Z".parse::<CustomTimeZone>().unwrap();
94
    /// time_zone.time_zone_id = Some(tinystr!(8, "gblon").into());
95
    ///
96
    /// // There are no non-fallback formats enabled:
97
    /// assert!(matches!(
98
    ///     tzf.format(&time_zone).write_no_fallback(&mut buf),
99
    ///     Err(DateTimeError::UnsupportedOptions)
100
    /// ));
101
    /// assert!(buf.is_empty());
102
    ///
103
    /// // Enable a non-fallback format:
104
    /// tzf.include_generic_location_format().unwrap();
105
    /// assert!(matches!(
106
    ///     tzf.format(&time_zone).write_no_fallback(&mut buf),
107
    ///     Ok(Ok(_))
108
    /// ));
109
    /// assert_eq!("London Time", buf);
110
    ///
111
    /// // Errors still occur if the time zone is not supported:
112
    /// buf.clear();
113
    /// time_zone.time_zone_id = Some(tinystr!(8, "zzzzz").into());
114
    /// assert!(matches!(
115
    ///     tzf.format(&time_zone).write_no_fallback(&mut buf),
116
    ///     Err(DateTimeError::UnsupportedOptions)
117
    /// ));
118
    ///
119
    /// // Use the `Writable` trait instead to enable infallible formatting:
120
    /// writeable::assert_writeable_eq!(tzf.format(&time_zone), "GMT");
121
    /// ```
122
    pub fn write_no_fallback<W>(&self, w: &mut W) -> Result<fmt::Result, Error>
262✔
123
    where
124
        W: core::fmt::Write + ?Sized,
125
    {
126
        for unit in self.time_zone_format.format_units.iter() {
320✔
127
            match unit.format(w, self.time_zone, &self.time_zone_format.data_payloads) {
262✔
128
                Ok(r) => return Ok(r),
204✔
129
                Err(DateTimeError::UnsupportedOptions) => continue,
130
                Err(e) => return Err(e),
×
131
            }
132
        }
133
        Err(DateTimeError::UnsupportedOptions)
58✔
134
    }
262✔
135

136
    fn handle_last_resort_error<W>(&self, e: DateTimeError, sink: &mut W) -> fmt::Result
×
137
    where
138
        W: core::fmt::Write + ?Sized,
139
    {
140
        match e {
×
141
            DateTimeError::MissingInputField(Some("gmt_offset")) => {
×
142
                debug_assert!(
×
143
                    false,
144
                    "Warning: using last-resort time zone fallback: {:?}.\
145
 To fix this warning, ensure the gmt_offset field is present.",
146
                    &self
×
147
                        .time_zone_format
148
                        .data_payloads
149
                        .zone_formats
150
                        .get()
151
                        .gmt_offset_fallback
152
                );
153
                sink.write_str(
154
                    &self
155
                        .time_zone_format
156
                        .data_payloads
157
                        .zone_formats
158
                        .get()
159
                        .gmt_offset_fallback,
160
                )
161
            }
162
            _ => {
163
                debug_assert!(false, "{e:?}");
×
164
                Err(core::fmt::Error)
165
            }
166
        }
167
    }
168
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc