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

zbraniecki / icu4x / 11904027177

19 Nov 2024 12:33AM UTC coverage: 75.477% (+0.3%) from 75.174%
11904027177

push

github

web-flow
Move DateTimePattern into pattern module (#5834)

#1317

Also removes `NeoNeverMarker` and fixes #5689

258 of 319 new or added lines in 6 files covered. (80.88%)

6967 existing lines in 278 files now uncovered.

54522 of 72237 relevant lines covered (75.48%)

655305.49 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
/// [`DateTimePattern`] 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: [`FormattedNeoDateTime::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
///
31
#[doc = date_time_pattern_size!()]
32
///
33
/// # Examples
34
///
35
/// Create a pattern from a custom string and compare it to one from data,
36
/// then check the resolved components:
37
///
38
/// ```
39
/// use icu::calendar::Date;
40
/// use icu::calendar::Gregorian;
41
/// use icu::datetime::fieldset::YMD;
42
/// use icu::datetime::pattern::DateTimePattern;
43
/// use icu::datetime::fields::components;
44
/// use icu::datetime::FixedCalendarDateTimeFormatter;
45
/// use icu::locale::locale;
46
/// use writeable::assert_writeable_eq;
47
///
48
/// // Create the pattern from a string:
49
/// let pattern_str = "d MMM y";
50
/// let custom_pattern =
51
///     DateTimePattern::try_from_pattern_str(pattern_str).unwrap();
52
/// assert_writeable_eq!(custom_pattern, pattern_str);
53
///
54
/// // Load data that resolves to the same pattern:
55
/// let data_pattern = FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
56
///     &locale!("es-MX").into(),
57
///     YMD::medium(),
58
/// )
59
/// .unwrap()
60
/// // The pattern can depend on the datetime being formatted.
61
/// .format(&Date::try_new_iso(2024, 1, 1).unwrap().to_calendar(Gregorian))
62
/// .pattern();
63
/// assert_writeable_eq!(data_pattern, pattern_str);
64
/// assert_eq!(custom_pattern, data_pattern);
65
///
66
/// // Check the resolved components:
67
/// let mut expected_components_bag = components::Bag::default();
68
/// expected_components_bag.year = Some(components::Year::Numeric);
69
/// expected_components_bag.month = Some(components::Month::Short);
70
/// expected_components_bag.day = Some(components::Day::NumericDayOfMonth);
71
/// let actual_components_bag = components::Bag::from(&data_pattern);
72
/// assert_eq!(actual_components_bag, expected_components_bag);
73
/// ```
74
///
75
/// [`DateTimeFormatter`]: crate::DateTimeFormatter
76
/// [`FormattedNeoDateTime::pattern`]: crate::FormattedNeoDateTime::pattern
77
/// [`TypedDateTimeNames`]: crate::pattern::TypedDateTimeNames
NEW
78
#[derive(Debug)]
×
79
pub struct DateTimePattern {
NEW
80
    pattern: runtime::Pattern<'static>,
×
81
}
82

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

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

98
    pub(crate) fn iter_items(&self) -> impl Iterator<Item = PatternItem> + '_ {
250✔
99
        self.pattern.items.iter()
250✔
100
    }
250✔
101

102
    pub(crate) fn as_borrowed(&self) -> DateTimePatternBorrowed {
745✔
103
        DateTimePatternBorrowed(&self.pattern)
104
    }
745✔
105
}
106

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

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

122
impl Eq for DateTimePattern {}
123

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

130
impl_display_with_writeable!(DateTimePattern);
131

132
// Not clear if this needs to be public. For now, make it private.
133
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
426✔
134
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

© 2025 Coveralls, Inc