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

zbraniecki / icu4x / 12020603084

23 Nov 2024 08:43PM UTC coverage: 75.71% (+0.2%) from 75.477%
12020603084

push

github

sffc
Touch Cargo.lock

55589 of 73424 relevant lines covered (75.71%)

644270.14 hits per line

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

92.0
/components/datetime/src/pattern/pattern.rs
1
// This file is part of ICU4X. For terms of use, please see the file
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::str::FromStr;
6

7
use writeable::{impl_display_with_writeable, Writeable};
8

9
use crate::provider::pattern::{runtime, PatternError, PatternItem};
10
use crate::size_test_macro::size_test;
11

12
size_test!(DateTimePattern, date_time_pattern_size, 32);
13

14
/// A pattern for formatting a datetime in a calendar.
15
///
16
/// ❗ This type forgoes most internationalization functionality of the datetime crate.
17
/// It assumes that the pattern is already localized for the customer's locale. Most clients
18
/// should use [`DateTimeFormatter`] instead of directly formatting with patterns.
19
///
20
/// There are two ways to make one of these:
21
///
22
/// 1. From a custom pattern string: [`DateTimePattern::try_from_pattern_str`]
23
/// 2. From a formatted datetime: [`FormattedDateTime::pattern`]
24
///
25
/// Things you can do with one of these:
26
///
27
/// 1. Use it to directly format a datetime via [`TypedDateTimeNames`]
28
/// 2. Convert it to a string pattern via [`Writeable`]
29
/// 3. Get the resolved components
30
#[doc = date_time_pattern_size!()]
31
///
32
/// # Examples
33
///
34
/// Create a pattern from a custom string and compare it to one from data,
35
/// then check the resolved components:
36
///
37
/// ```
38
/// use icu::calendar::Date;
39
/// use icu::calendar::Gregorian;
40
/// use icu::datetime::fields::components;
41
/// use icu::datetime::fieldsets::YMD;
42
/// use icu::datetime::pattern::DateTimePattern;
43
/// use icu::datetime::FixedCalendarDateTimeFormatter;
44
/// use icu::locale::locale;
45
/// use writeable::assert_writeable_eq;
46
///
47
/// // Create the pattern from a string:
48
/// let pattern_str = "d MMM y";
49
/// let custom_pattern =
50
///     DateTimePattern::try_from_pattern_str(pattern_str).unwrap();
51
/// assert_writeable_eq!(custom_pattern, pattern_str);
52
///
53
/// // Load data that resolves to the same pattern:
54
/// let data_pattern = FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
55
///     locale!("es-MX").into(),
56
///     YMD::medium(),
57
/// )
58
/// .unwrap()
59
/// // The pattern can depend on the datetime being formatted.
60
/// .format(
61
///     &Date::try_new_iso(2024, 1, 1)
62
///         .unwrap()
63
///         .to_calendar(Gregorian),
64
/// )
65
/// .pattern();
66
/// assert_writeable_eq!(data_pattern, pattern_str);
67
/// assert_eq!(custom_pattern, data_pattern);
68
///
69
/// // Check the resolved components:
70
/// let mut expected_components_bag = components::Bag::default();
71
/// expected_components_bag.year = Some(components::Year::Numeric);
72
/// expected_components_bag.month = Some(components::Month::Short);
73
/// expected_components_bag.day = Some(components::Day::NumericDayOfMonth);
74
/// let actual_components_bag = components::Bag::from(&data_pattern);
75
/// assert_eq!(actual_components_bag, expected_components_bag);
76
/// ```
77
///
78
/// [`DateTimeFormatter`]: crate::DateTimeFormatter
79
/// [`FormattedDateTime::pattern`]: crate::FormattedDateTime::pattern
80
/// [`TypedDateTimeNames`]: crate::pattern::TypedDateTimeNames
81
#[derive(Debug)]
×
82
pub struct DateTimePattern {
83
    pattern: runtime::Pattern<'static>,
×
84
}
85

86
impl DateTimePattern {
87
    /// Creates a [`DateTimePattern`] from a pattern string.
88
    ///
89
    /// For more details on the syntax, see UTS 35:
90
    /// <https://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns>
91
    pub fn try_from_pattern_str(pattern_str: &str) -> Result<Self, PatternError> {
304✔
92
        let pattern = runtime::Pattern::from_str(pattern_str)?;
304✔
93
        Ok(Self { pattern })
304✔
94
    }
304✔
95

96
    #[doc(hidden)] // TODO(#4467): Internal API
97
    pub fn from_runtime_pattern(pattern: runtime::Pattern<'static>) -> Self {
323✔
98
        Self { pattern }
323✔
99
    }
323✔
100

101
    pub(crate) fn iter_items(&self) -> impl Iterator<Item = PatternItem> + '_ {
251✔
102
        self.pattern.items.iter()
251✔
103
    }
251✔
104

105
    pub(crate) fn as_borrowed(&self) -> DateTimePatternBorrowed {
745✔
106
        DateTimePatternBorrowed(&self.pattern)
107
    }
745✔
108
}
109

110
impl FromStr for DateTimePattern {
111
    type Err = PatternError;
112
    fn from_str(s: &str) -> Result<Self, Self::Err> {
54✔
113
        Self::try_from_pattern_str(s)
54✔
114
    }
54✔
115
}
116

117
// Check equality on the borrowed variant since it flattens the difference
118
// between the three `Single` pattern variants, which is not public-facing
119
impl PartialEq for DateTimePattern {
120
    fn eq(&self, other: &Self) -> bool {
213✔
121
        self.as_borrowed().eq(&other.as_borrowed())
213✔
122
    }
213✔
123
}
124

125
impl Eq for DateTimePattern {}
126

127
impl Writeable for DateTimePattern {
128
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
20✔
129
        self.pattern.write_to(sink)
20✔
130
    }
20✔
131
}
132

133
impl_display_with_writeable!(DateTimePattern);
134

135
// Not clear if this needs to be public. For now, make it private.
136
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
426✔
137
pub(crate) struct DateTimePatternBorrowed<'a>(pub(crate) &'a runtime::Pattern<'a>);
213✔
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

© 2026 Coveralls, Inc