icu_datetime/provider/pattern/reference/
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#[cfg(any(feature = "serde", test))]
6use super::super::runtime;
7use super::{
8    super::{PatternError, PatternItem, TimeGranularity},
9    Parser,
10};
11use alloc::vec::Vec;
12use core::str::FromStr;
13
14/// A fully-owned, non-zero-copy type corresponding to [`Pattern`](super::super::runtime::Pattern).
15///
16/// <div class="stab unstable">
17/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
18/// including in SemVer minor releases. While the serde representation of data structs is guaranteed
19/// to be stable, their Rust representation might not be. Use with caution.
20/// </div>
21#[derive(Debug, Default, Clone, PartialEq)]
22pub struct Pattern {
23    pub(crate) items: Vec<PatternItem>,
24    pub(crate) time_granularity: TimeGranularity,
25}
26
27impl Pattern {
28    /// Convert a [`Pattern`] to a vector of pattern items.
29    ///
30    /// The [`Pattern`] can be restored via the `From` impl.
31    pub fn into_items(self) -> Vec<PatternItem> {
32        self.items
33    }
34
35    #[cfg(feature = "datagen")]
36    pub(crate) fn items(&self) -> &[PatternItem] {
37        &self.items
38    }
39
40    #[cfg(feature = "datagen")]
41    pub(crate) fn items_mut(&mut self) -> &mut [PatternItem] {
42        &mut self.items
43    }
44
45    #[cfg(any(feature = "serde", test))]
46    pub(crate) fn to_runtime_pattern(&self) -> runtime::Pattern<'static> {
47        runtime::Pattern::from(self)
48    }
49}
50
51impl From<Vec<PatternItem>> for Pattern {
52    fn from(items: Vec<PatternItem>) -> Self {
53        Self {
54            time_granularity: items
55                .iter()
56                .copied()
57                .map(Into::into)
58                .max()
59                .unwrap_or_default(),
60            items,
61        }
62    }
63}
64
65impl From<&str> for Pattern {
66    fn from(items: &str) -> Self {
67        Self {
68            time_granularity: TimeGranularity::default(),
69            items: items.chars().map(|ch| ch.into()).collect(),
70        }
71    }
72}
73
74impl FromStr for Pattern {
75    type Err = PatternError;
76
77    fn from_str(s: &str) -> Result<Self, Self::Err> {
78        Parser::new(s).parse().map(Self::from)
79    }
80}