1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use crate::lazy_automaton::LazyAutomaton;
use crate::provider::*;
#[cfg(feature = "datagen")]
use alloc::borrow::Cow;
#[cfg(feature = "datagen")]
use icu_provider::DataError;
use writeable::{LengthHint, Writeable};

impl ListFormatterPatternsV2<'_> {
    /// Creates a new [`ListFormatterPatternsV2`] from the given patterns. Fails if any pattern is invalid.
    #[cfg(feature = "datagen")]
    pub fn try_new(start: &str, middle: &str, end: &str, pair: &str) -> Result<Self, DataError> {
        let err = DataError::custom("Invalid list pattern");
        Ok(Self {
            start: ListJoinerPattern::try_from_str(start, true, false)?,
            middle: middle
                .strip_prefix("{0}")
                .ok_or(err)?
                .strip_suffix("{1}")
                .ok_or(err)?
                .to_string()
                .into(),
            end: ListJoinerPattern::try_from_str(end, false, true)?.into(),
            pair: if end != pair {
                Some(ListJoinerPattern::try_from_str(pair, true, true)?.into())
            } else {
                None
            },
        })
    }

    /// The range of the number of bytes required by the list literals to join a
    /// list of length `len`. If none of the patterns are conditional, this is exact.
    pub(crate) fn length_hint(&self, len: usize) -> LengthHint {
        match len {
            0 | 1 => LengthHint::exact(0),
            2 => self.pair.as_ref().unwrap_or(&self.end).size_hint(),
            n => {
                self.start.size_hint()
                    + self.middle.writeable_length_hint() * (n - 3)
                    + self.end.size_hint()
            }
        }
    }
}

type PatternParts<'a> = (&'a str, &'a str, &'a str);

impl<'a> ConditionalListJoinerPattern<'a> {
    pub(crate) fn parts<'b, W: Writeable + ?Sized>(
        &'a self,
        following_value: &'b W,
    ) -> PatternParts<'a> {
        match &self.special_case {
            Some(SpecialCasePattern { condition, pattern })
                if condition.deref().matches_earliest_fwd_lazy(following_value) =>
            {
                pattern.parts()
            }
            _ => self.default.parts(),
        }
    }

    /// The expected length of this pattern
    fn size_hint(&'a self) -> LengthHint {
        let mut hint = self.default.size_hint();
        if let Some(special_case) = &self.special_case {
            hint |= special_case.pattern.size_hint()
        }
        hint
    }
}

impl<'data> ListJoinerPattern<'data> {
    #[cfg(feature = "datagen")]
    /// TODO
    pub fn try_from_str(
        pattern: &str,
        allow_prefix: bool,
        allow_suffix: bool,
    ) -> Result<Self, DataError> {
        match (pattern.find("{0}"), pattern.find("{1}")) {
            (Some(index_0), Some(index_1))
                if index_0 < index_1
                    && (allow_prefix || index_0 == 0)
                    && (allow_suffix || index_1 == pattern.len() - 3) =>
            {
                if (index_0 > 0 && !cfg!(test)) || index_1 - 3 >= 256 {
                    return Err(DataError::custom(
                        "Found valid pattern that cannot be stored in ListFormatterPatternsV2",
                    )
                    .with_debug_context(pattern));
                }
                #[allow(clippy::indexing_slicing)] // find
                Ok(ListJoinerPattern {
                    string: Cow::Owned(alloc::format!(
                        "{}{}{}",
                        &pattern[0..index_0],
                        &pattern[index_0 + 3..index_1],
                        &pattern[index_1 + 3..]
                    )),
                    index_0: index_0 as u8,
                    index_1: (index_1 - 3) as u8,
                })
            }
            _ => Err(DataError::custom("Invalid list pattern").with_debug_context(pattern)),
        }
    }

    pub(crate) fn parts(&'data self) -> PatternParts<'data> {
        #![allow(clippy::indexing_slicing)] // by invariant
        let index_0 = self.index_0 as usize;
        let index_1 = self.index_1 as usize;
        (
            &self.string[0..index_0],
            &self.string[index_0..index_1],
            &self.string[index_1..],
        )
    }

    fn size_hint(&self) -> LengthHint {
        LengthHint::exact(self.string.len())
    }
}

#[cfg(feature = "datagen")]
impl<'data> From<ListJoinerPattern<'data>> for ConditionalListJoinerPattern<'data> {
    fn from(default: ListJoinerPattern<'data>) -> Self {
        Self {
            default,
            special_case: None,
        }
    }
}

#[cfg(all(test, feature = "datagen"))]
pub mod test {
    use super::*;

    pub fn test_patterns_general() -> ListFormatterPatternsV2<'static> {
        ListFormatterPatternsV2::try_new("@{0}:{1}", "{0},{1}", "{0}.{1}!", "${0};{1}+").unwrap()
    }

    pub fn test_patterns_lengths() -> ListFormatterPatternsV2<'static> {
        ListFormatterPatternsV2::try_new("{0}1{1}", "{0}12{1}", "{0}12{1}34", "{0}123{1}456")
            .unwrap()
    }

    pub fn test_patterns_conditional() -> ListFormatterPatternsV2<'static> {
        let mut patterns =
            ListFormatterPatternsV2::try_new("{0}: {1}", "{0}, {1}", "{0}. {1}", "{0}. {1}")
                .unwrap();
        patterns.end.special_case = Some(SpecialCasePattern {
            condition: SerdeDFA::new(Cow::Borrowed("^a")).unwrap(),
            pattern: ListJoinerPattern::try_from_str("{0} :o {1}", false, false).unwrap(),
        });
        patterns
    }

    #[test]
    fn rejects_bad_patterns() {
        assert!(ListJoinerPattern::try_from_str("{0} and", true, true).is_err());
        assert!(ListJoinerPattern::try_from_str("and {1}", true, true).is_err());
        assert!(ListJoinerPattern::try_from_str("{1} and {0}", true, true).is_err());
        assert!(ListJoinerPattern::try_from_str("{1{0}}", true, true).is_err());
        assert!(ListJoinerPattern::try_from_str("{0\u{202e}} and {1}", true, true).is_err());
        assert!(ListJoinerPattern::try_from_str("{{0}} {{1}}", true, true).is_ok());

        assert!(ListJoinerPattern::try_from_str("{0} and {1} ", true, true).is_ok());
        assert!(ListJoinerPattern::try_from_str("{0} and {1} ", true, false).is_err());
        assert!(ListJoinerPattern::try_from_str(" {0} and {1}", true, true).is_ok());
        assert!(ListJoinerPattern::try_from_str(" {0} and {1}", false, true).is_err());
    }

    #[test]
    fn produces_correct_parts() {
        assert_eq!(
            test_patterns_general().pair.unwrap().parts(""),
            ("$", ";", "+")
        );
    }

    #[test]
    fn produces_correct_parts_conditionally() {
        assert_eq!(test_patterns_conditional().end.parts("a"), ("", " :o ", ""));
        assert_eq!(
            test_patterns_conditional().end.parts("ab"),
            ("", " :o ", "")
        );
        assert_eq!(test_patterns_conditional().end.parts("b"), ("", ". ", ""));
        assert_eq!(test_patterns_conditional().end.parts("ba"), ("", ". ", ""));
    }

    #[test]
    fn size_hint_works() {
        let pattern = test_patterns_lengths();

        assert_eq!(pattern.length_hint(0), LengthHint::exact(0));
        assert_eq!(pattern.length_hint(1), LengthHint::exact(0));

        // pair pattern "{0}123{1}456"
        assert_eq!(pattern.length_hint(2), LengthHint::exact(6));

        // patterns "{0}1{1}", "{0}12{1}" (x197), and "{0}12{1}34"
        assert_eq!(pattern.length_hint(200), LengthHint::exact(1 + 2 * 197 + 4));

        let pattern = test_patterns_conditional();

        // patterns "{0}: {1}", "{0}, {1}" (x197), and "{0} :o {1}" or "{0}. {1}"
        assert_eq!(
            pattern.length_hint(200),
            LengthHint::exact(2 + 197 * 2) + LengthHint::between(2, 4)
        );
    }
}