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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// 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 ).

//! This module provides functionality for querying of sets of Unicode code points and strings.
//!
//! It depends on [`CodePointInversionList`] to efficiently represent Unicode code points, while
//! it also maintains a list of strings in the set.
//!
//! It is an implementation of the existing [ICU4C UnicodeSet API](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classicu_1_1UnicodeSet.html).

use crate::codepointinvlist::{
    CodePointInversionList, CodePointInversionListBuilder, CodePointInversionListError,
    CodePointInversionListULE,
};
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use displaydoc::Display;
use yoke::Yokeable;
use zerofrom::ZeroFrom;
use zerovec::{VarZeroSlice, VarZeroVec};

/// A data structure providing a concrete implementation of a `UnicodeSet`
/// (which represents a set of code points and strings) using an inversion list for the code points and a simple
/// list-like structure to store and iterate over the strings.
#[zerovec::make_varule(CodePointInversionListAndStringListULE)]
#[zerovec::skip_derive(Ord)]
#[zerovec::derive(Debug)]
#[derive(Debug, Eq, PartialEq, Clone, Yokeable, ZeroFrom)]
// Valid to auto-derive Deserialize because the invariants are weakly held
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", zerovec::derive(Serialize, Deserialize, Debug))]
pub struct CodePointInversionListAndStringList<'data> {
    #[cfg_attr(feature = "serde", serde(borrow))]
    #[zerovec::varule(CodePointInversionListULE)]
    cp_inv_list: CodePointInversionList<'data>,
    // Invariants (weakly held):
    //   - no input string is length 1 (a length 1 string should be a single code point)
    //   - the string list is sorted
    //   - the elements in the string list are unique
    #[cfg_attr(feature = "serde", serde(borrow))]
    str_list: VarZeroVec<'data, str>,
}

#[cfg(feature = "databake")]
impl databake::Bake for CodePointInversionListAndStringList<'_> {
    fn bake(&self, env: &databake::CrateEnv) -> databake::TokenStream {
        env.insert("icu_collections");
        let cp_inv_list = self.cp_inv_list.bake(env);
        let str_list = self.str_list.bake(env);
        // Safe because our parts are safe.
        databake::quote! {
            icu_collections::codepointinvliststringlist::CodePointInversionListAndStringList::from_parts_unchecked(#cp_inv_list, #str_list)
        }
    }
}

impl<'data> CodePointInversionListAndStringList<'data> {
    /// Returns a new [`CodePointInversionListAndStringList`] from both a [`CodePointInversionList`] for the
    /// code points and a [`VarZeroVec`]`<`[`str`]`>` of strings.
    pub fn try_from(
        cp_inv_list: CodePointInversionList<'data>,
        str_list: VarZeroVec<'data, str>,
    ) -> Result<Self, CodePointInversionListAndStringListError> {
        // Verify invariants:
        // Do so by using the equivalent of str_list.iter().windows(2) to get
        // overlapping windows of size 2. The above putative code is not possible
        // because `.windows()` exists on a slice, but VarZeroVec cannot return a slice
        // because the non-fixed size elements necessitate at least some type
        // of allocation.
        {
            let mut it = str_list.iter();
            if let Some(mut x) = it.next() {
                if x.len() == 1 {
                    return Err(
                        CodePointInversionListAndStringListError::InvalidStringLength(
                            x.to_string(),
                        ),
                    );
                }
                for y in it {
                    if x.len() == 1 {
                        return Err(
                            CodePointInversionListAndStringListError::InvalidStringLength(
                                x.to_string(),
                            ),
                        );
                    } else if x == y {
                        return Err(
                            CodePointInversionListAndStringListError::StringListNotUnique(
                                x.to_string(),
                            ),
                        );
                    } else if x > y {
                        return Err(
                            CodePointInversionListAndStringListError::StringListNotSorted(
                                x.to_string(),
                                y.to_string(),
                            ),
                        );
                    }

                    // Next window begins. Update `x` here, `y` will be updated in next loop iteration.
                    x = y;
                }
            }
        }

        Ok(CodePointInversionListAndStringList {
            cp_inv_list,
            str_list,
        })
    }

    #[doc(hidden)]
    pub const fn from_parts_unchecked(
        cp_inv_list: CodePointInversionList<'data>,
        str_list: VarZeroVec<'data, str>,
    ) -> Self {
        CodePointInversionListAndStringList {
            cp_inv_list,
            str_list,
        }
    }

    /// Returns the number of elements in this set (its cardinality).
    /// Note than the elements of a set may include both individual
    /// codepoints and strings.
    pub fn size(&self) -> usize {
        self.cp_inv_list.size() + self.str_list.len()
    }

    /// Return true if this set contains multi-code point strings or the empty string.
    pub fn has_strings(&self) -> bool {
        !self.str_list.is_empty()
    }

    ///
    /// # Examples
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionList;
    /// use icu::collections::codepointinvliststringlist::CodePointInversionListAndStringList;
    /// use zerovec::VarZeroVec;
    ///
    /// let cp_slice = &[0, 0x1_0000, 0x10_FFFF, 0x11_0000];
    /// let cp_list =
    ///    CodePointInversionList::try_clone_from_inversion_list_slice(cp_slice).unwrap();
    /// let str_slice = &["", "bmp_max", "unicode_max", "zero"];
    /// let str_list = VarZeroVec::<str>::from(str_slice);
    ///
    /// let cpilsl = CodePointInversionListAndStringList::try_from(cp_list, str_list).unwrap();
    ///
    /// assert!(cpilsl.contains("bmp_max"));
    /// assert!(cpilsl.contains(""));
    /// assert!(cpilsl.contains("A"));
    /// assert!(cpilsl.contains("ቔ"));  // U+1254 ETHIOPIC SYLLABLE QHEE
    /// assert!(!cpilsl.contains("bazinga!"));
    /// ```
    pub fn contains(&self, s: &str) -> bool {
        let mut chars = s.chars();
        if let Some(first_char) = chars.next() {
            if chars.next().is_none() {
                return self.contains_char(first_char);
            }
        }
        self.str_list.binary_search(s).is_ok()
    }

    ///
    /// # Examples
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionList;
    /// use icu::collections::codepointinvliststringlist::CodePointInversionListAndStringList;
    /// use zerovec::VarZeroVec;
    ///
    /// let cp_slice = &[0, 0x80, 0xFFFF, 0x1_0000, 0x10_FFFF, 0x11_0000];
    /// let cp_list =
    ///     CodePointInversionList::try_clone_from_inversion_list_slice(cp_slice).unwrap();
    /// let str_slice = &["", "ascii_max", "bmp_max", "unicode_max", "zero"];
    /// let str_list = VarZeroVec::<str>::from(str_slice);
    ///
    /// let cpilsl = CodePointInversionListAndStringList::try_from(cp_list, str_list).unwrap();
    ///
    /// assert!(cpilsl.contains32(0));
    /// assert!(cpilsl.contains32(0x0042));
    /// assert!(!cpilsl.contains32(0x0080));
    /// ```
    pub fn contains32(&self, cp: u32) -> bool {
        self.cp_inv_list.contains32(cp)
    }

    ///
    /// # Examples
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionList;
    /// use icu::collections::codepointinvliststringlist::CodePointInversionListAndStringList;
    /// use zerovec::VarZeroVec;
    ///
    /// let cp_slice = &[0, 0x1_0000, 0x10_FFFF, 0x11_0000];
    /// let cp_list =
    ///    CodePointInversionList::try_clone_from_inversion_list_slice(cp_slice).unwrap();
    /// let str_slice = &["", "bmp_max", "unicode_max", "zero"];
    /// let str_list = VarZeroVec::<str>::from(str_slice);
    ///
    /// let cpilsl = CodePointInversionListAndStringList::try_from(cp_list, str_list).unwrap();
    ///
    /// assert!(cpilsl.contains_char('A'));
    /// assert!(cpilsl.contains_char('ቔ'));  // U+1254 ETHIOPIC SYLLABLE QHEE
    /// assert!(!cpilsl.contains_char('\u{1_0000}'));
    /// assert!(!cpilsl.contains_char('🨫'));  // U+1FA2B NEUTRAL CHESS TURNED QUEEN
    pub fn contains_char(&self, ch: char) -> bool {
        self.contains32(ch as u32)
    }

    /// Access the underlying [`CodePointInversionList`].
    pub fn code_points(&self) -> &CodePointInversionList<'data> {
        &self.cp_inv_list
    }

    /// Access the contained strings.
    pub fn strings(&self) -> &VarZeroSlice<str> {
        &self.str_list
    }
}

impl<'a> FromIterator<&'a str> for CodePointInversionListAndStringList<'_> {
    fn from_iter<I>(it: I) -> Self
    where
        I: IntoIterator<Item = &'a str>,
    {
        let mut builder = CodePointInversionListBuilder::new();
        let mut strings = Vec::<&str>::new();
        for s in it {
            let mut chars = s.chars();
            if let Some(first_char) = chars.next() {
                if chars.next().is_none() {
                    builder.add_char(first_char);
                    continue;
                }
            }
            strings.push(s);
        }

        // Ensure that the string list is sorted. If not, the binary search that
        // is used for `.contains(&str)` will return garbase otuput.
        strings.sort_unstable();
        strings.dedup();

        let cp_inv_list = builder.build();
        let str_list = VarZeroVec::<str>::from(&strings);

        CodePointInversionListAndStringList {
            cp_inv_list,
            str_list,
        }
    }
}

/// Custom Errors for [`CodePointInversionListAndStringList`].
///
/// Re-exported as [`Error`].
#[derive(Display, Debug)]
pub enum CodePointInversionListAndStringListError {
    /// An invalid CodePointInversionList was constructed
    #[displaydoc("Invalid code point inversion list: {0:?}")]
    InvalidCodePointInversionList(CodePointInversionListError),
    /// A string in the string list had an invalid length
    #[displaydoc("Invalid string length for string: {0}")]
    InvalidStringLength(String),
    /// A string in the string list appears more than once
    #[displaydoc("String list has duplicate: {0}")]
    StringListNotUnique(String),
    /// Two strings in the string list compare to each other opposite of sorted order
    #[displaydoc("Strings in string list not in sorted order: ({0}, {1})")]
    StringListNotSorted(String, String),
}

#[doc(no_inline)]
pub use CodePointInversionListAndStringListError as Error;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_size_has_strings() {
        let cp_slice = &[0, 1, 0x7F, 0x80, 0xFFFF, 0x1_0000, 0x10_FFFF, 0x11_0000];
        let cp_list =
            CodePointInversionList::try_clone_from_inversion_list_slice(cp_slice).unwrap();
        let str_slice = &["ascii_max", "bmp_max", "unicode_max", "zero"];
        let str_list = VarZeroVec::<str>::from(str_slice);

        let cpilsl = CodePointInversionListAndStringList::try_from(cp_list, str_list).unwrap();

        assert!(cpilsl.has_strings());
        assert_eq!(8, cpilsl.size());
    }

    #[test]
    fn test_empty_string_allowed() {
        let cp_slice = &[0, 1, 0x7F, 0x80, 0xFFFF, 0x1_0000, 0x10_FFFF, 0x11_0000];
        let cp_list =
            CodePointInversionList::try_clone_from_inversion_list_slice(cp_slice).unwrap();
        let str_slice = &["", "ascii_max", "bmp_max", "unicode_max", "zero"];
        let str_list = VarZeroVec::<str>::from(str_slice);

        let cpilsl = CodePointInversionListAndStringList::try_from(cp_list, str_list).unwrap();

        assert!(cpilsl.has_strings());
        assert_eq!(9, cpilsl.size());
    }

    #[test]
    fn test_invalid_string() {
        let cp_slice = &[0, 1];
        let cp_list =
            CodePointInversionList::try_clone_from_inversion_list_slice(cp_slice).unwrap();
        let str_slice = &["a"];
        let str_list = VarZeroVec::<str>::from(str_slice);

        let cpilsl = CodePointInversionListAndStringList::try_from(cp_list, str_list);

        assert!(matches!(
            cpilsl,
            Err(CodePointInversionListAndStringListError::InvalidStringLength(_))
        ));
    }

    #[test]
    fn test_invalid_string_list_has_duplicate() {
        let cp_slice = &[0, 1];
        let cp_list =
            CodePointInversionList::try_clone_from_inversion_list_slice(cp_slice).unwrap();
        let str_slice = &["abc", "abc"];
        let str_list = VarZeroVec::<str>::from(str_slice);

        let cpilsl = CodePointInversionListAndStringList::try_from(cp_list, str_list);

        assert!(matches!(
            cpilsl,
            Err(CodePointInversionListAndStringListError::StringListNotUnique(_))
        ));
    }

    #[test]
    fn test_invalid_string_list_not_sorted() {
        let cp_slice = &[0, 1];
        let cp_list =
            CodePointInversionList::try_clone_from_inversion_list_slice(cp_slice).unwrap();
        let str_slice = &["xyz", "abc"];
        let str_list = VarZeroVec::<str>::from(str_slice);

        let cpilsl = CodePointInversionListAndStringList::try_from(cp_list, str_list);

        assert!(matches!(
            cpilsl,
            Err(CodePointInversionListAndStringListError::StringListNotSorted(_, _))
        ));
    }

    #[test]
    fn test_from_iter_invariants() {
        let in_strs_1 = ["a", "abc", "xyz", "abc"];
        let in_strs_2 = ["xyz", "abc", "a", "abc"];

        let cpilsl_1 = CodePointInversionListAndStringList::from_iter(in_strs_1);
        let cpilsl_2 = CodePointInversionListAndStringList::from_iter(in_strs_2);

        assert_eq!(cpilsl_1, cpilsl_2);

        assert!(cpilsl_1.has_strings());
        assert!(cpilsl_1.contains("abc"));
        assert!(cpilsl_1.contains("xyz"));
        assert!(!cpilsl_1.contains("def"));

        assert_eq!(1, cpilsl_1.cp_inv_list.size());
        assert!(cpilsl_1.contains_char('a'));
        assert!(!cpilsl_1.contains_char('0'));
        assert!(!cpilsl_1.contains_char('q'));

        assert_eq!(3, cpilsl_1.size());
    }
}