Debian Codegraph @

debian/rust-vendor/icu_pattern/src/multi_named.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 [`MultiNamedPlaceholder`] pattern backend.
6
7 #[cfg(feature = "alloc")]
8 use alloc::{borrow::Cow, boxed::Box, collections::BTreeMap, string::String};
9 use core::fmt;
10 #[cfg(feature = "alloc")]
11 use core::str::FromStr;
12 #[cfg(feature = "litemap")]
13 use litemap::LiteMap;
14 use writeable::Writeable;
15
16 use crate::Error;
17 use crate::common::*;
18
19 /// A string wrapper for the [`MultiNamedPlaceholder`] pattern backend.
20 ///
21 /// # Examples
22 ///
23 /// ```
24 /// use core::cmp::Ordering;
25 /// use core::str::FromStr;
26 /// use icu_pattern::MultiNamedPlaceholderKey;
27 /// use icu_pattern::MultiNamedPlaceholderPattern;
28 /// use icu_pattern::PatternItem;
29 ///
30 /// // Parse the string syntax and check the resulting data store:
31 /// let pattern = MultiNamedPlaceholderPattern::try_from_str(
32 /// "Hello, {person0} and {person1}!",
33 /// Default::default(),
34 /// )
35 /// .unwrap();
36 ///
37 /// assert_eq!(
38 /// pattern.iter().cmp(
39 /// [
40 /// PatternItem::Literal("Hello, "),
41 /// PatternItem::Placeholder(MultiNamedPlaceholderKey("person0")),
42 /// PatternItem::Literal(" and "),
43 /// PatternItem::Placeholder(MultiNamedPlaceholderKey("person1")),
44 /// PatternItem::Literal("!")
45 /// ]
46 /// .into_iter()
47 /// ),
48 /// Ordering::Equal
49 /// );
50 /// ```
51 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
52 #[repr(transparent)]
53 #[allow(clippy::exhaustive_structs)] // transparent newtype
54 pub struct MultiNamedPlaceholderKey<'a>(pub &'a str);
55
56 /// Cowable version of [`MultiNamedPlaceholderKey`], used during construction.
57 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
58 #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
59 #[repr(transparent)]
60 #[allow(clippy::exhaustive_structs)] // transparent newtype
61 #[cfg(feature = "alloc")]
62 pub struct MultiNamedPlaceholderKeyCow<'a>(pub Cow<'a, str>);
63
64 #[cfg(feature = "alloc")]
65 impl FromStr for MultiNamedPlaceholderKeyCow<'_> {
66 type Err = Error;
67 fn from_str(s: &str) -> Result<Self, Self::Err> {
68 // Can't borrow the str here unfortunately
69 Ok(MultiNamedPlaceholderKeyCow(Cow::Owned(String::from(s))))
70 }
71 }
72
73 #[derive(Debug, Clone, PartialEq, Eq)]
74 #[non_exhaustive]
75 pub struct MissingNamedPlaceholderError<'a> {
76 pub name: &'a str,
77 }
78
79 impl Writeable for MissingNamedPlaceholderError<'_> {
80 fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
81 sink.write_char('{')?;
82 sink.write_str(self.name)?;
83 sink.write_char('}')?;
84 Ok(())
85 }
86 }
87
88 #[cfg(feature = "alloc")]
89 impl<'k, K, W> PlaceholderValueProvider<MultiNamedPlaceholderKey<'k>> for BTreeMap<K, W>
90 where
91 K: Ord + core::borrow::Borrow<str>,
92 W: Writeable,
93 {
94 type Error = MissingNamedPlaceholderError<'k>;
95
96 type W<'a>
97 = Result<&'a W, Self::Error>
98 where
99 Self: 'a;
100
101 type L<'a, 'l>
102 = &'l str
103 where
104 Self: 'a;
105
106 #[inline]
107 fn value_for<'a>(&'a self, key: MultiNamedPlaceholderKey<'k>) -> Self::W<'a> {
108 match self.get(key.0) {
109 Some(value) => Ok(value),
110 None => Err(MissingNamedPlaceholderError { name: key.0 }),
111 }
112 }
113 #[inline]
114 fn map_literal<'a, 'l>(&'a self, literal: &'l str) -> Self::L<'a, 'l> {
115 literal
116 }
117 }
118
119 #[cfg(feature = "litemap")]
120 impl<'k, K, W, S> PlaceholderValueProvider<MultiNamedPlaceholderKey<'k>> for LiteMap<K, W, S>
121 where
122 K: Ord + core::borrow::Borrow<str>,
123 W: Writeable,
124 S: litemap::store::Store<K, W>,
125 {
126 type Error = MissingNamedPlaceholderError<'k>;
127
128 type W<'a>
129 = Result<&'a W, Self::Error>
130 where
131 Self: 'a;
132
133 type L<'a, 'l>
134 = &'l str
135 where
136 Self: 'a;
137
138 #[inline]
139 fn value_for<'a>(&'a self, key: MultiNamedPlaceholderKey<'k>) -> Self::W<'a> {
140 match self.get(key.0) {
141 Some(value) => Ok(value),
142 None => Err(MissingNamedPlaceholderError { name: key.0 }),
143 }
144 }
145 #[inline]
146 fn map_literal<'a, 'l>(&'a self, literal: &'l str) -> Self::L<'a, 'l> {
147 literal
148 }
149 }
150
151 /// Backend for patterns containing zero or more named placeholders.
152 ///
153 /// This empty type is not constructible.
154 ///
155 /// # Placeholder Keys
156 ///
157 /// The placeholder is [`MultiNamedPlaceholderKey`].
158 ///
159 /// In [`Pattern::interpolate()`], pass a map-like structure. Missing keys will be replaced
160 /// with the Unicode replacement character U+FFFD.
161 ///
162 /// # Encoding Details
163 ///
164 /// The literals and placeholders are stored in context. A placeholder is encoded as a name length
165 /// in octal code points followed by the placeholder name.
166 ///
167 /// For example, consider the pattern: `Hello, {user} and {someone_else}!`
168 ///
169 /// The encoding for this would be:
170 ///
171 /// ```txt
172 /// Hello, \x00\x04user and \x01\x04someone_else!
173 /// ```
174 ///
175 /// where `\x00\x04` and `\x01\x04` are a big-endian octal number representing the lengths of
176 /// their respective placeholder names.
177 ///
178 /// Consequences of this encoding:
179 ///
180 /// 1. The maximum placeholder name length is 64 bytes
181 /// 2. Code points in the range `\x00` through `\x07` are reserved for the placeholder name
182 ///
183 /// # Examples
184 ///
185 /// Example patterns supported by this backend:
186 ///
187 /// ```
188 /// use core::str::FromStr;
189 /// use icu_pattern::MultiNamedPlaceholder;
190 /// use icu_pattern::Pattern;
191 /// use std::collections::BTreeMap;
192 ///
193 /// let placeholder_value_map: BTreeMap<&str, &str> = [
194 /// ("num", "5"),
195 /// ("letter", "X"),
196 /// ("", "empty"),
197 /// ("unused", "unused"),
198 /// ]
199 /// .into_iter()
200 /// .collect();
201 ///
202 /// // Single placeholder:
203 /// assert_eq!(
204 /// Pattern::<MultiNamedPlaceholder>::try_from_str(
205 /// "{num} days ago",
206 /// Default::default()
207 /// )
208 /// .unwrap()
209 /// .try_interpolate_to_string(&placeholder_value_map)
210 /// .unwrap(),
211 /// "5 days ago",
212 /// );
213 ///
214 /// // No placeholder (note, the placeholder value is never accessed):
215 /// assert_eq!(
216 /// Pattern::<MultiNamedPlaceholder>::try_from_str(
217 /// "yesterday",
218 /// Default::default()
219 /// )
220 /// .unwrap()
221 /// .try_interpolate_to_string(&placeholder_value_map)
222 /// .unwrap(),
223 /// "yesterday",
224 /// );
225 ///
226 /// // No literals, only placeholders:
227 /// assert_eq!(
228 /// Pattern::<MultiNamedPlaceholder>::try_from_str(
229 /// "{letter}{num}{}",
230 /// Default::default()
231 /// )
232 /// .unwrap()
233 /// .try_interpolate_to_string(&placeholder_value_map)
234 /// .unwrap(),
235 /// "X5empty",
236 /// );
237 /// ```
238 ///
239 /// Use [`LiteMap`] for alloc-free formatting:
240 ///
241 /// ```
242 /// use core::str::FromStr;
243 /// use icu_pattern::MultiNamedPlaceholderPattern;
244 /// use litemap::LiteMap;
245 /// use writeable::TryWriteable;
246 ///
247 /// static PLACEHOLDER_VALUE_MAP: LiteMap<&str, usize, &[(&str, usize)]> =
248 /// LiteMap::from_sorted_store_unchecked(&[("seven", 11)]);
249 ///
250 /// // Note: String allocates, but this could be a non-allocating sink
251 /// let mut sink = String::new();
252 ///
253 /// MultiNamedPlaceholderPattern::try_from_str("{seven}", Default::default())
254 /// .unwrap()
255 /// .try_interpolate(&PLACEHOLDER_VALUE_MAP)
256 /// .try_write_to(&mut sink)
257 /// .unwrap()
258 /// .unwrap();
259 ///
260 /// assert_eq!(sink, "11");
261 /// ```
262 ///
263 /// Missing placeholder values cause an error result to be returned. However,
264 /// based on the design of [`TryWriteable`], the error can be discarded to get
265 /// a best-effort interpolation with potential replacement characters.
266 ///
267 /// ```should_panic
268 /// use core::str::FromStr;
269 /// use icu_pattern::MultiNamedPlaceholder;
270 /// use icu_pattern::Pattern;
271 /// use std::collections::BTreeMap;
272 ///
273 /// let placeholder_value_map: BTreeMap<&str, &str> =
274 /// [("num", "5"), ("letter", "X")].into_iter().collect();
275 ///
276 /// Pattern::<MultiNamedPlaceholder>::try_from_str(
277 /// "Your name is {your_name}",
278 /// Default::default(),
279 /// )
280 /// .unwrap()
281 /// .try_interpolate_to_string(&placeholder_value_map)
282 /// .unwrap();
283 /// ```
284 ///
285 /// Recover the best-effort lossy string by directly using [`Pattern::try_interpolate()`]:
286 ///
287 /// ```
288 /// use core::str::FromStr;
289 /// use icu_pattern::MissingNamedPlaceholderError;
290 /// use icu_pattern::MultiNamedPlaceholder;
291 /// use icu_pattern::Pattern;
292 /// use std::borrow::Cow;
293 /// use std::collections::BTreeMap;
294 /// use writeable::TryWriteable;
295 ///
296 /// let placeholder_value_map: BTreeMap<&str, &str> =
297 /// [("num", "5"), ("letter", "X")].into_iter().collect();
298 ///
299 /// let pattern = Pattern::<MultiNamedPlaceholder>::try_from_str(
300 /// "Your name is {your_name}",
301 /// Default::default(),
302 /// )
303 /// .unwrap();
304 ///
305 /// let mut buffer = String::new();
306 /// let result = pattern
307 /// .try_interpolate(&placeholder_value_map)
308 /// .try_write_to(&mut buffer)
309 /// .expect("infallible write to String");
310 ///
311 /// assert!(matches!(result, Err(MissingNamedPlaceholderError { .. })));
312 /// assert_eq!(result.unwrap_err().name, "your_name");
313 /// assert_eq!(buffer, "Your name is {your_name}");
314 /// ```
315 ///
316 /// [`Pattern::interpolate()`]: crate::Pattern::interpolate
317 /// [`Pattern::try_interpolate()`]: crate::Pattern::try_interpolate
318 /// [`TryWriteable`]: writeable::TryWriteable
319 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
320 #[allow(clippy::exhaustive_enums)] // Empty Enum
321 pub enum MultiNamedPlaceholder {}
322
323 impl crate::private::Sealed for MultiNamedPlaceholder {}
324
325 impl PatternBackend for MultiNamedPlaceholder {
326 type PlaceholderKey<'a> = MultiNamedPlaceholderKey<'a>;
327 #[cfg(feature = "alloc")]
328 type PlaceholderKeyCow<'a> = MultiNamedPlaceholderKeyCow<'a>;
329 type Store = str;
330 type Iter<'a> = MultiNamedPlaceholderPatternIterator<'a>;
331
332 fn validate_store(store: &Self::Store) -> Result<(), Error> {
333 let mut iter = MultiNamedPlaceholderPatternIterator::new(store);
334 while iter
335 .try_next()
336 .map_err(|e| match e {
337 MultiNamedPlaceholderError::InvalidStore => Error::InvalidPattern,
338 MultiNamedPlaceholderError::Unreachable => {
339 debug_assert!(false, "unreachable");
340 Error::InvalidPattern
341 }
342 })?
343 .is_some()
344 {}
345 Ok(())
346 }
347
348 fn iter_items(store: &Self::Store) -> Self::Iter<'_> {
349 MultiNamedPlaceholderPatternIterator::new(store)
350 }
351
352 #[cfg(feature = "alloc")]
353 fn try_from_items<
354 'cow,
355 'ph,
356 I: Iterator<Item = Result<PatternItemCow<'cow, Self::PlaceholderKeyCow<'ph>>, Error>>,
357 >(
358 items: I,
359 ) -> Result<Box<str>, Error> {
360 let mut string = String::new();
361 for item in items {
362 match item? {
363 PatternItemCow::Literal(s) if s.contains(|x| (x as usize) <= 0x07) => {
364 // TODO: Should this be a different error type?
365 return Err(Error::InvalidPattern);
366 }
367 PatternItemCow::Literal(s) => string.push_str(&s),
368 PatternItemCow::Placeholder(ph_key) => {
369 let name_length = ph_key.0.len();
370 if name_length >= 64 {
371 return Err(Error::InvalidPlaceholder);
372 }
373 let lead = (name_length >> 3) as u8;
374 let trail = (name_length & 0x7) as u8;
375 string.push(char::from(lead));
376 string.push(char::from(trail));
377 string.push_str(&ph_key.0);
378 }
379 }
380 }
381 Ok(string.into_boxed_str())
382 }
383
384 fn empty() -> &'static Self::Store {
385 ""
386 }
387 }
388
389 #[derive(Debug)]
390 pub struct MultiNamedPlaceholderPatternIterator<'a> {
391 store: &'a str,
392 }
393
394 // Note: we don't implement ExactSizeIterator since we don't store that metadata in MultiNamed.
395
396 impl<'a> Iterator for MultiNamedPlaceholderPatternIterator<'a> {
397 type Item = PatternItem<'a, MultiNamedPlaceholderKey<'a>>;
398 fn next(&mut self) -> Option<Self::Item> {
399 match self.try_next() {
400 Ok(next) => next,
401 Err(MultiNamedPlaceholderError::InvalidStore) => {
402 debug_assert!(
403 false,
404 "invalid store with {} bytes remaining",
405 self.store.len()
406 );
407 None
408 }
409 Err(MultiNamedPlaceholderError::Unreachable) => {
410 debug_assert!(false, "unreachable");
411 None
412 }
413 }
414 }
415 }
416
417 enum MultiNamedPlaceholderError {
418 InvalidStore,
419 Unreachable,
420 }
421
422 impl<'a> MultiNamedPlaceholderPatternIterator<'a> {
423 fn new(store: &'a str) -> Self {
424 Self { store }
425 }
426
427 fn try_next(
428 &mut self,
429 ) -> Result<Option<PatternItem<'a, MultiNamedPlaceholderKey<'a>>>, MultiNamedPlaceholderError>
430 {
431 match self.store.find(|x| (x as usize) <= 0x07) {
432 Some(0) => {
433 // Placeholder
434 let Some((&[lead, trail], remainder)) = self
435 .store
436 .split_at_checked(2)
437 .map(|(a, b)| (a.as_bytes(), b))
438 else {
439 return Err(MultiNamedPlaceholderError::InvalidStore);
440 };
441 debug_assert!(lead <= 7);
442 if trail > 7 {
443 return Err(MultiNamedPlaceholderError::InvalidStore);
444 }
445 let placeholder_len = (lead << 3) + trail;
446 let Some((placeholder_name, remainder)) =
447 remainder.split_at_checked(placeholder_len as usize)
448 else {
449 return Err(MultiNamedPlaceholderError::InvalidStore);
450 };
451 self.store = remainder;
452 Ok(Some(PatternItem::Placeholder(MultiNamedPlaceholderKey(
453 placeholder_name,
454 ))))
455 }
456 Some(i) => {
457 // Literal
458 let Some((literal, remainder)) = self.store.split_at_checked(i) else {
459 debug_assert!(false, "should be a perfect slice");
460 return Err(MultiNamedPlaceholderError::Unreachable);
461 };
462 self.store = remainder;
463 Ok(Some(PatternItem::Literal(literal)))
464 }
465 None if self.store.is_empty() => {
466 // End of string
467 Ok(None)
468 }
469 None => {
470 // Closing literal
471 let literal = self.store;
472 self.store = "";
473 Ok(Some(PatternItem::Literal(literal)))
474 }
475 }
476 }
477 }
478
479 #[cfg(test)]
480 mod tests {
481 use super::*;
482 use crate::{MultiNamedPlaceholder, MultiNamedPlaceholderPattern};
483
484 #[test]
485 fn test_invalid() {
486 let long_str = "0123456789".repeat(1000000);
487 let strings = [
488 "{", // invalid syntax
489 "{@}", // placeholder name too long
490 "\x00", // invalid character
491 "\x07", // invalid character
492 ];
493 for string in strings {
494 let string = string.replace('@', &long_str);
495 assert!(
496 MultiNamedPlaceholderPattern::try_from_str(&string, Default::default()).is_err(),
497 "{string:?}"
498 );
499 }
500 let stores = [
501 "\x00", // too short
502 "\x02", // too short
503 "\x00\x02", // no placeholder name
504 "\x00\x02a", // placeholder name too short
505 ];
506 for store in stores {
507 assert!(
508 MultiNamedPlaceholder::validate_store(store).is_err(),
509 "{store:?}"
510 );
511 }
512 }
513 }