Debian Codegraph @

debian/rust-vendor/icu_pattern/src/single.rs

raw
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 //! Code for the [`SinglePlaceholder`] pattern backend.
6
7 use core::convert::Infallible;
8 use core::{cmp::Ordering, str::FromStr};
9 use writeable::adapters::WriteableAsTryWriteableInfallible;
10 use writeable::{TryWriteable, Writeable};
11
12 use crate::Error;
13 use crate::common::*;
14
15 #[cfg(feature = "alloc")]
16 use alloc::{boxed::Box, string::String};
17
18 /// A singleton enum for the [`SinglePlaceholder`] pattern backend.
19 ///
20 /// # Examples
21 ///
22 /// ```
23 /// use core::cmp::Ordering;
24 /// use core::str::FromStr;
25 /// use icu_pattern::PatternItem;
26 /// use icu_pattern::SinglePlaceholder;
27 /// use icu_pattern::SinglePlaceholderKey;
28 /// use icu_pattern::SinglePlaceholderPattern;
29 ///
30 /// // Parse the string syntax and check the resulting data store:
31 /// let pattern = SinglePlaceholderPattern::try_from_str(
32 /// "Hello, {0}!",
33 /// Default::default(),
34 /// )
35 /// .unwrap();
36 ///
37 /// assert_eq!(
38 /// pattern.iter().cmp(
39 /// [
40 /// PatternItem::Literal("Hello, "),
41 /// PatternItem::Placeholder(SinglePlaceholderKey::Singleton),
42 /// PatternItem::Literal("!")
43 /// ]
44 /// .into_iter()
45 /// ),
46 /// Ordering::Equal
47 /// );
48 /// ```
49 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
50 #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
51 #[allow(clippy::exhaustive_enums)] // Singleton
52 pub enum SinglePlaceholderKey {
53 Singleton,
54 }
55
56 impl FromStr for SinglePlaceholderKey {
57 type Err = Infallible;
58 fn from_str(_: &str) -> Result<Self, Self::Err> {
59 Ok(Self::Singleton)
60 }
61 }
62
63 impl<W> PlaceholderValueProvider<SinglePlaceholderKey> for (W,)
64 where
65 W: Writeable,
66 {
67 type Error = Infallible;
68
69 type W<'a>
70 = WriteableAsTryWriteableInfallible<&'a W>
71 where
72 Self: 'a;
73
74 type L<'a, 'l>
75 = &'l str
76 where
77 Self: 'a;
78
79 fn value_for(&self, _key: SinglePlaceholderKey) -> Self::W<'_> {
80 WriteableAsTryWriteableInfallible(&self.0)
81 }
82 #[inline]
83 fn map_literal<'a, 'l>(&'a self, literal: &'l str) -> Self::L<'a, 'l> {
84 literal
85 }
86 }
87
88 impl<W> PlaceholderValueProvider<SinglePlaceholderKey> for [W; 1]
89 where
90 W: Writeable,
91 {
92 type Error = Infallible;
93
94 type W<'a>
95 = WriteableAsTryWriteableInfallible<&'a W>
96 where
97 Self: 'a;
98
99 type L<'a, 'l>
100 = &'l str
101 where
102 Self: 'a;
103
104 fn value_for(&self, _key: SinglePlaceholderKey) -> Self::W<'_> {
105 let [value] = self;
106 WriteableAsTryWriteableInfallible(value)
107 }
108 #[inline]
109 fn map_literal<'a, 'l>(&'a self, literal: &'l str) -> Self::L<'a, 'l> {
110 literal
111 }
112 }
113
114 impl<W> PlaceholderValueProvider<SinglePlaceholderKey> for TryWrap<W>
115 where
116 W: TryWriteable,
117 {
118 type Error = W::Error;
119
120 type W<'a>
121 = &'a W
122 where
123 Self: 'a;
124
125 type L<'a, 'l>
126 = &'l str
127 where
128 Self: 'a;
129
130 #[inline]
131 fn value_for(&self, _key: SinglePlaceholderKey) -> Self::W<'_> {
132 &self.0
133 }
134 #[inline]
135 fn map_literal<'a, 'l>(&'a self, literal: &'l str) -> Self::L<'a, 'l> {
136 literal
137 }
138 }
139
140 /// Backend for patterns containing zero or one placeholder.
141 ///
142 /// This empty type is not constructible.
143 ///
144 /// # Placeholder Keys
145 ///
146 /// The placeholder is always [`SinglePlaceholderKey::Singleton`].
147 ///
148 /// In [`Pattern::interpolate()`], pass a single-element array or tuple.
149 ///
150 /// # Encoding Details
151 ///
152 /// The first code point of the string is 1 plus the byte offset of the placeholder counting from
153 /// after that initial code point. If zero, there is no placeholder.
154 ///
155 /// # Examples
156 ///
157 /// Parsing a pattern into the encoding:
158 ///
159 /// ```
160 /// use core::str::FromStr;
161 /// use icu_pattern::Pattern;
162 /// use icu_pattern::SinglePlaceholder;
163 ///
164 /// // Parse the string syntax and check the resulting data store:
165 /// let pattern = Pattern::<SinglePlaceholder>::try_from_str(
166 /// "Hello, {0}!",
167 /// Default::default(),
168 /// )
169 /// .unwrap();
170 ///
171 /// assert_eq!("\u{8}Hello, !", &pattern.store);
172 /// ```
173 ///
174 /// Example patterns supported by this backend:
175 ///
176 /// ```
177 /// use core::str::FromStr;
178 /// use icu_pattern::Pattern;
179 /// use icu_pattern::QuoteMode;
180 /// use icu_pattern::SinglePlaceholder;
181 ///
182 /// // Single numeric placeholder:
183 /// assert_eq!(
184 /// Pattern::<SinglePlaceholder>::try_from_str(
185 /// "{0} days ago",
186 /// Default::default()
187 /// )
188 /// .unwrap()
189 /// .interpolate_to_string([5]),
190 /// "5 days ago",
191 /// );
192 ///
193 /// // Single named placeholder:
194 /// assert_eq!(
195 /// Pattern::<SinglePlaceholder>::try_from_str(
196 /// "{name}",
197 /// Default::default()
198 /// )
199 /// .unwrap()
200 /// .interpolate_to_string(["Alice"]),
201 /// "Alice",
202 /// );
203 ///
204 /// // No placeholder (note, the placeholder value is never accessed):
205 /// assert_eq!(
206 /// Pattern::<SinglePlaceholder>::try_from_str(
207 /// "yesterday",
208 /// Default::default()
209 /// )
210 /// .unwrap()
211 /// .interpolate_to_string(["hi"]),
212 /// "yesterday",
213 /// );
214 ///
215 /// // Escaped placeholder and a real placeholder:
216 /// assert_eq!(
217 /// Pattern::<SinglePlaceholder>::try_from_str(
218 /// "'{0}' {1}",
219 /// QuoteMode::QuotingSupported.into()
220 /// )
221 /// .unwrap()
222 /// .interpolate_to_string(("hi",)),
223 /// "{0} hi",
224 /// );
225 /// ```
226 ///
227 /// [`Pattern::interpolate()`]: crate::Pattern::interpolate
228 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
229 #[allow(clippy::exhaustive_enums)] // Empty Enum
230 pub enum SinglePlaceholder {}
231
232 impl crate::private::Sealed for SinglePlaceholder {}
233
234 impl PatternBackend for SinglePlaceholder {
235 type PlaceholderKey<'a> = SinglePlaceholderKey;
236 #[cfg(feature = "alloc")]
237 type PlaceholderKeyCow<'a> = SinglePlaceholderKey;
238 type Store = str;
239 type Iter<'a> = SinglePlaceholderPatternIterator<'a>;
240
241 fn validate_store(store: &Self::Store) -> Result<(), Error> {
242 let placeholder_offset_char = store.chars().next().ok_or(Error::InvalidPattern)?;
243 let initial_offset = placeholder_offset_char.len_utf8();
244 let placeholder_offset = placeholder_offset_char as usize;
245 if placeholder_offset > store.len() - initial_offset + 1 {
246 return Err(Error::InvalidPattern);
247 }
248 if placeholder_offset >= 0xD800 {
249 return Err(Error::InvalidPattern);
250 }
251 Ok(())
252 }
253
254 fn iter_items(store: &Self::Store) -> Self::Iter<'_> {
255 let placeholder_offset_char = match store.chars().next() {
256 Some(i) => i,
257 None => {
258 debug_assert!(false);
259 '\0'
260 }
261 };
262 let initial_offset = placeholder_offset_char.len_utf8();
263 SinglePlaceholderPatternIterator {
264 store,
265 placeholder_offset: placeholder_offset_char as usize + initial_offset - 1,
266 current_offset: initial_offset,
267 }
268 }
269
270 #[cfg(feature = "alloc")]
271 fn try_from_items<
272 'cow,
273 'ph,
274 I: Iterator<Item = Result<PatternItemCow<'cow, Self::PlaceholderKey<'ph>>, Error>>,
275 >(
276 items: I,
277 ) -> Result<Box<str>, Error> {
278 let mut result = String::new();
279 let mut seen_placeholder = false;
280 for item in items {
281 match item? {
282 PatternItemCow::Literal(s) => result.push_str(&s),
283 PatternItemCow::Placeholder(_) if !seen_placeholder => {
284 seen_placeholder = true;
285 let placeholder_offset =
286 u32::try_from(result.len() + 1).map_err(|_| Error::InvalidPattern)?;
287 if placeholder_offset >= 0xD800 {
288 return Err(Error::InvalidPattern);
289 }
290 let placeholder_offset_char =
291 char::try_from(placeholder_offset).map_err(|_| Error::InvalidPattern)?;
292 result.insert(0, placeholder_offset_char);
293 }
294 PatternItemCow::Placeholder(_) => {
295 return Err(Error::InvalidPattern);
296 }
297 }
298 }
299 if !seen_placeholder {
300 result.insert(0, '\0');
301 }
302 Ok(result.into_boxed_str())
303 }
304
305 fn empty() -> &'static Self::Store {
306 "\0"
307 }
308 }
309
310 #[cfg(feature = "unstable")]
311 impl ExtractionBackend for SinglePlaceholder {
312 type DecodedMatchesUnstable<'p, 'a> = Option<&'a str>;
313
314 fn extract_unstable<'p, 'a>(
315 store: &'p Self::Store,
316 input: &'a str,
317 ) -> Option<Self::DecodedMatchesUnstable<'p, 'a>> {
318 let mut prefix = None;
319 let mut ph = None;
320 let mut suffix = None;
321
322 // Get the parts from the pattern
323 for item in Self::iter_items(store) {
324 match item {
325 PatternItem::Literal(s) => {
326 if ph.is_none() {
327 debug_assert!(prefix.is_none());
328 prefix = Some(s);
329 } else {
330 debug_assert!(suffix.is_none());
331 suffix = Some(s);
332 }
333 }
334 PatternItem::Placeholder(p) => {
335 debug_assert!(ph.is_none());
336 ph = Some(p);
337 }
338 }
339 }
340
341 // Strip prefix and suffix from input
342 let val = input
343 .strip_prefix(prefix.unwrap_or(""))?
344 .strip_suffix(suffix.unwrap_or(""))?;
345
346 // Return the match
347 match ph {
348 Some(_) => Some(Some(val)),
349 None => {
350 if val.is_empty() {
351 Some(None)
352 } else {
353 None
354 }
355 }
356 }
357 }
358
359 fn get_match_unstable<'p, 'b>(
360 store: &Self::DecodedMatchesUnstable<'p, 'b>,
361 _key: Self::PlaceholderKey<'_>,
362 ) -> Option<&'b str> {
363 *store
364 }
365 }
366
367 #[doc(hidden)] // TODO(#4467): Should be internal
368 #[derive(Debug)]
369 pub struct SinglePlaceholderPatternIterator<'a> {
370 store: &'a str,
371 placeholder_offset: usize,
372 current_offset: usize,
373 }
374
375 // Note: This impl is not exported via public bounds, but it might be in the
376 // future, and the compiler might be able to find it. The code is also
377 // reachable from `Iterator::size_hint`.
378 impl ExactSizeIterator for SinglePlaceholderPatternIterator<'_> {
379 fn len(&self) -> usize {
380 let placeholder_offset_char = match self.store.chars().next() {
381 Some(i) => i,
382 None => {
383 debug_assert!(false);
384 '\0'
385 }
386 };
387 let initial_offset = placeholder_offset_char.len_utf8();
388 let placeholder_offset = placeholder_offset_char as usize + initial_offset - 1;
389 let store_len = self.store.len();
390 if placeholder_offset < initial_offset {
391 // No placeholder
392 if initial_offset < store_len {
393 // No placeholder, non-empty literal
394 1
395 } else {
396 // No placeholder, empty literal
397 0
398 }
399 } else if placeholder_offset == initial_offset {
400 // Has placeholder, empty prefix
401 if initial_offset < store_len {
402 // Has placeholder, empty prefix, non-empty suffix
403 2
404 } else {
405 // Has placeholder, empty prefix, empty suffix
406 1
407 }
408 } else if placeholder_offset < store_len {
409 // Has placeholder, non-empty prefix, non-empty suffix
410 3
411 } else {
412 // Has placeholder, non-empty prefix, empty suffix
413 2
414 }
415 }
416 }
417
418 impl<'a> Iterator for SinglePlaceholderPatternIterator<'a> {
419 type Item = PatternItem<'a, SinglePlaceholderKey>;
420 fn next(&mut self) -> Option<Self::Item> {
421 match self.current_offset.cmp(&self.placeholder_offset) {
422 Ordering::Less => {
423 // Prefix
424 let literal_str = match self.store.get(self.current_offset..self.placeholder_offset)
425 {
426 Some(s) => s,
427 None => {
428 debug_assert!(false, "offsets are in range");
429 ""
430 }
431 };
432 self.current_offset = self.placeholder_offset;
433 Some(PatternItem::Literal(literal_str))
434 }
435 Ordering::Equal => {
436 // Placeholder
437 self.placeholder_offset = 0;
438 Some(PatternItem::Placeholder(SinglePlaceholderKey::Singleton))
439 }
440 Ordering::Greater => {
441 // Suffix or end of string
442 let literal_str = match self.store.get(self.current_offset..) {
443 Some(s) => s,
444 None => {
445 debug_assert!(false, "offsets are in range");
446 ""
447 }
448 };
449 if literal_str.is_empty() {
450 // End of string
451 None
452 } else {
453 // Suffix
454 self.current_offset = self.store.len();
455 Some(PatternItem::Literal(literal_str))
456 }
457 }
458 }
459 }
460
461 fn size_hint(&self) -> (usize, Option<usize>) {
462 let len = self.len();
463 (len, Some(len))
464 }
465 }
466
467 // TODO(#1668): Add more tests