Debian Codegraph @

debian/rust-vendor/icu_pattern/src/double.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 [`DoublePlaceholder`] pattern backend.
6
7 use core::convert::Infallible;
8 use core::{cmp::Ordering, str::FromStr};
9 use either::Either;
10 use writeable::adapters::WriteableAsTryWriteableInfallible;
11 use writeable::{TryWriteable, Writeable};
12
13 use crate::Error;
14 use crate::common::*;
15
16 #[cfg(feature = "alloc")]
17 use alloc::{boxed::Box, string::String};
18
19 /// A two-value enum for the [`DoublePlaceholder`] pattern backend.
20 ///
21 /// # Examples
22 ///
23 /// ```
24 /// use core::cmp::Ordering;
25 /// use core::str::FromStr;
26 /// use icu_pattern::DoublePlaceholderKey;
27 /// use icu_pattern::DoublePlaceholderPattern;
28 /// use icu_pattern::PatternItem;
29 ///
30 /// // Parse the string syntax
31 /// let pattern = DoublePlaceholderPattern::try_from_str(
32 /// "Hello, {0} and {1}!",
33 /// Default::default(),
34 /// )
35 /// .unwrap();
36 ///
37 /// assert_eq!(
38 /// pattern.iter().cmp(
39 /// [
40 /// PatternItem::Literal("Hello, "),
41 /// PatternItem::Placeholder(DoublePlaceholderKey::Place0),
42 /// PatternItem::Literal(" and "),
43 /// PatternItem::Placeholder(DoublePlaceholderKey::Place1),
44 /// PatternItem::Literal("!")
45 /// ]
46 /// .into_iter()
47 /// ),
48 /// Ordering::Equal
49 /// );
50 /// ```
51 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
52 #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
53 #[allow(clippy::exhaustive_enums)] // Defined to have two entries
54 pub enum DoublePlaceholderKey {
55 /// The placeholder `{0}`.
56 Place0,
57 /// The placeholder `{1}`.
58 Place1,
59 }
60
61 impl FromStr for DoublePlaceholderKey {
62 type Err = Error;
63 fn from_str(s: &str) -> Result<Self, Self::Err> {
64 match s {
65 "0" => Ok(Self::Place0),
66 "1" => Ok(Self::Place1),
67 _ => Err(Error::InvalidPlaceholder),
68 }
69 }
70 }
71
72 impl<W0, W1> PlaceholderValueProvider<DoublePlaceholderKey> for (W0, W1)
73 where
74 W0: Writeable,
75 W1: Writeable,
76 {
77 type Error = Infallible;
78
79 type W<'a>
80 = WriteableAsTryWriteableInfallible<Either<&'a W0, &'a W1>>
81 where
82 Self: 'a;
83
84 type L<'a, 'l>
85 = &'l str
86 where
87 Self: 'a;
88
89 #[inline]
90 fn value_for(&self, key: DoublePlaceholderKey) -> Self::W<'_> {
91 let writeable = match key {
92 DoublePlaceholderKey::Place0 => Either::Left(&self.0),
93 DoublePlaceholderKey::Place1 => Either::Right(&self.1),
94 };
95 WriteableAsTryWriteableInfallible(writeable)
96 }
97 #[inline]
98 fn map_literal<'a, 'l>(&'a self, literal: &'l str) -> Self::L<'a, 'l> {
99 literal
100 }
101 }
102
103 impl<W> PlaceholderValueProvider<DoublePlaceholderKey> for [W; 2]
104 where
105 W: Writeable,
106 {
107 type Error = Infallible;
108
109 type W<'a>
110 = WriteableAsTryWriteableInfallible<&'a W>
111 where
112 Self: 'a;
113
114 type L<'a, 'l>
115 = &'l str
116 where
117 Self: 'a;
118
119 #[inline]
120 fn value_for(&self, key: DoublePlaceholderKey) -> Self::W<'_> {
121 let [item0, item1] = self;
122 let writeable = match key {
123 DoublePlaceholderKey::Place0 => item0,
124 DoublePlaceholderKey::Place1 => item1,
125 };
126 WriteableAsTryWriteableInfallible(writeable)
127 }
128 #[inline]
129 fn map_literal<'a, 'l>(&'a self, literal: &'l str) -> Self::L<'a, 'l> {
130 literal
131 }
132 }
133
134 impl<W0, W1> PlaceholderValueProvider<DoublePlaceholderKey> for TryWrap<(W0, W1)>
135 where
136 W0: TryWriteable,
137 W1: TryWriteable,
138 {
139 type Error = Either<W0::Error, W1::Error>;
140
141 type W<'a>
142 = Either<&'a W0, &'a W1>
143 where
144 Self: 'a;
145
146 type L<'a, 'l>
147 = &'l str
148 where
149 Self: 'a;
150
151 #[inline]
152 fn value_for(&self, key: DoublePlaceholderKey) -> Self::W<'_> {
153 match key {
154 DoublePlaceholderKey::Place0 => Either::Left(&self.0.0),
155 DoublePlaceholderKey::Place1 => Either::Right(&self.0.1),
156 }
157 }
158 #[inline]
159 fn map_literal<'a, 'l>(&'a self, literal: &'l str) -> Self::L<'a, 'l> {
160 literal
161 }
162 }
163
164 /// Internal representation of a placeholder
165 #[derive(Debug, Copy, Clone)]
166 struct DoublePlaceholderInfo {
167 /// The placeholder key: 0 or 1
168 pub key: DoublePlaceholderKey,
169 /// An offset field. This can take one of two forms:
170 /// - Encoded form: 1 + offset from start of literals
171 /// - Decoded form: offset from start of store
172 pub offset: usize,
173 }
174
175 impl DoublePlaceholderInfo {
176 pub fn from_char(ch: char) -> Self {
177 Self {
178 key: if ((ch as usize) & 0x1) == 0 {
179 DoublePlaceholderKey::Place0
180 } else {
181 DoublePlaceholderKey::Place1
182 },
183 offset: (ch as usize) >> 1,
184 }
185 }
186 #[cfg(feature = "alloc")]
187 pub fn try_to_char(self) -> Result<char, Error> {
188 let usize_val = match self.key {
189 DoublePlaceholderKey::Place0 => 0,
190 DoublePlaceholderKey::Place1 => 1,
191 } | (self.offset << 1);
192 u32::try_from(usize_val)
193 .ok()
194 .and_then(|x| char::try_from(x).ok())
195 .ok_or(Error::InvalidPattern)
196 }
197 /// Creates a [`DoublePlaceholderInfo`] for an empty `Place0`
198 pub fn no_place0() -> Self {
199 Self {
200 key: DoublePlaceholderKey::Place0,
201 offset: 0,
202 }
203 }
204 /// Changes Place0 to Place1 and vice-versa
205 pub fn swap(self) -> Self {
206 Self {
207 key: match self.key {
208 DoublePlaceholderKey::Place0 => DoublePlaceholderKey::Place1,
209 DoublePlaceholderKey::Place1 => DoublePlaceholderKey::Place0,
210 },
211 offset: self.offset,
212 }
213 }
214 /// Sets the offset to 0 (ignored placeholder), retaining the key
215 #[cfg(feature = "alloc")]
216 pub fn clear(self) -> Self {
217 Self {
218 key: self.key,
219 offset: 0,
220 }
221 }
222 }
223
224 /// Backend for patterns containing zero, one, or two placeholders.
225 ///
226 /// This empty type is not constructible.
227 ///
228 /// # Placeholder Keys
229 ///
230 /// The placeholder is either [`DoublePlaceholderKey::Place0`] or [`DoublePlaceholderKey::Place1`].
231 ///
232 /// In [`Pattern::interpolate()`], pass a two-element array or tuple.
233 ///
234 /// # Encoding Details
235 ///
236 /// The first two code points contain the indices of the first and second placeholders with
237 /// the following encoding:
238 ///
239 /// 1. First bit: 0 for [`DoublePlaceholderKey::Place0`], 1 for [`DoublePlaceholderKey::Place1`].
240 /// 2. Second and higher bits: 1 plus the byte offset of the placeholder counting from after
241 /// the placeholder index code points. If zero, skip this placeholder.
242 ///
243 /// # Examples
244 ///
245 /// Parsing a pattern into the encoding:
246 ///
247 /// ```
248 /// use core::str::FromStr;
249 /// use icu_pattern::DoublePlaceholder;
250 /// use icu_pattern::Pattern;
251 ///
252 /// // Parse the string syntax and check the resulting data store:
253 /// let pattern = Pattern::<DoublePlaceholder>::try_from_str(
254 /// "Hello, {0} and {1}!",
255 /// Default::default(),
256 /// )
257 /// .unwrap();
258 ///
259 /// assert_eq!("\x10\x1BHello, and !", &pattern.store);
260 /// ```
261 ///
262 /// Explanation of the lead code points:
263 ///
264 /// 1. `\x10` is placeholder 0 at index 7: ((7 + 1) << 1) | 0
265 /// 2. `\x1B` is placeholder 1 at index 12: ((12 + 1) << 1) | 1
266 ///
267 /// Example patterns supported by this backend:
268 ///
269 /// ```
270 /// use core::str::FromStr;
271 /// use icu_pattern::DoublePlaceholder;
272 /// use icu_pattern::Pattern;
273 /// use icu_pattern::QuoteMode;
274 ///
275 /// // Single numeric placeholder (note, "5" is used):
276 /// assert_eq!(
277 /// Pattern::<DoublePlaceholder>::try_from_str(
278 /// "{0} days ago",
279 /// Default::default()
280 /// )
281 /// .unwrap()
282 /// .interpolate_to_string([5, 7]),
283 /// "5 days ago",
284 /// );
285 ///
286 /// // No placeholder (note, the placeholder value is never accessed):
287 /// assert_eq!(
288 /// Pattern::<DoublePlaceholder>::try_from_str(
289 /// "yesterday",
290 /// Default::default()
291 /// )
292 /// .unwrap()
293 /// .interpolate_to_string(["foo", "bar"]),
294 /// "yesterday",
295 /// );
296 ///
297 /// // Escaped placeholder and a placeholder value 1 (note, "bar" is used):
298 /// assert_eq!(
299 /// Pattern::<DoublePlaceholder>::try_from_str(
300 /// "'{0}' {1}",
301 /// QuoteMode::QuotingSupported.into()
302 /// )
303 /// .unwrap()
304 /// .interpolate_to_string(("foo", "bar")),
305 /// "{0} bar",
306 /// );
307 ///
308 /// // Pattern with the placeholders in the opposite order:
309 /// assert_eq!(
310 /// Pattern::<DoublePlaceholder>::try_from_str(
311 /// "A {1} B {0} C",
312 /// Default::default()
313 /// )
314 /// .unwrap()
315 /// .interpolate_to_string(("D", "E")),
316 /// "A E B D C",
317 /// );
318 ///
319 /// // No literals, only placeholders:
320 /// assert_eq!(
321 /// Pattern::<DoublePlaceholder>::try_from_str(
322 /// "{1}{0}",
323 /// Default::default()
324 /// )
325 /// .unwrap()
326 /// .interpolate_to_string((1, "A")),
327 /// "A1",
328 /// );
329 /// ```
330 ///
331 /// [`Pattern::interpolate()`]: crate::Pattern::interpolate
332 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
333 #[allow(clippy::exhaustive_enums)] // Empty Enum
334 pub enum DoublePlaceholder {}
335
336 impl crate::private::Sealed for DoublePlaceholder {}
337
338 impl PatternBackend for DoublePlaceholder {
339 type PlaceholderKey<'a> = DoublePlaceholderKey;
340 #[cfg(feature = "alloc")]
341 type PlaceholderKeyCow<'a> = DoublePlaceholderKey;
342 type Store = str;
343 type Iter<'a> = DoublePlaceholderPatternIterator<'a>;
344
345 fn validate_store(store: &Self::Store) -> Result<(), Error> {
346 let mut chars = store.chars();
347 let ph_first_char = chars.next().ok_or(Error::InvalidPattern)?;
348 let ph_second_char = chars.next().ok_or(Error::InvalidPattern)?;
349 let initial_offset = ph_first_char.len_utf8() + ph_second_char.len_utf8();
350 let ph_first = DoublePlaceholderInfo::from_char(ph_first_char);
351 let ph_second = DoublePlaceholderInfo::from_char(ph_second_char);
352 if ph_first.key == ph_second.key {
353 return Err(Error::InvalidPattern);
354 }
355 if ph_first.offset > ph_second.offset && ph_second.offset > 0 {
356 return Err(Error::InvalidPattern);
357 }
358 if ph_second.offset > store.len() - initial_offset + 1 {
359 return Err(Error::InvalidPattern);
360 }
361 if (ph_second_char as usize) >= 0xD800 {
362 return Err(Error::InvalidPattern);
363 }
364 Ok(())
365 }
366
367 fn iter_items(store: &Self::Store) -> Self::Iter<'_> {
368 let mut chars = store.chars();
369 let (mut ph_first, ph_first_len) = match chars.next() {
370 Some(ch) => (DoublePlaceholderInfo::from_char(ch), ch.len_utf8()),
371 None => {
372 debug_assert!(false);
373 (DoublePlaceholderInfo::no_place0(), 0)
374 }
375 };
376 let (mut ph_second, ph_second_len) = match chars.next() {
377 Some(ch) => (DoublePlaceholderInfo::from_char(ch), ch.len_utf8()),
378 None => {
379 debug_assert!(false);
380 (ph_first.swap(), ph_first_len)
381 }
382 };
383 let initial_offset = ph_first_len + ph_second_len;
384 ph_first.offset += initial_offset - 1;
385 ph_second.offset += initial_offset - 1;
386 DoublePlaceholderPatternIterator {
387 store,
388 ph_first,
389 ph_second,
390 current_offset: initial_offset,
391 }
392 }
393
394 #[cfg(feature = "alloc")]
395 fn try_from_items<
396 'cow,
397 'ph,
398 I: Iterator<Item = Result<PatternItemCow<'cow, Self::PlaceholderKey<'ph>>, Error>>,
399 >(
400 items: I,
401 ) -> Result<Box<str>, Error> {
402 let mut result = String::new();
403 let mut first_ph = None;
404 let mut second_ph = None;
405 for item in items {
406 match item? {
407 PatternItemCow::Literal(s) => result.push_str(&s),
408 PatternItemCow::Placeholder(ph_key) => {
409 if second_ph.is_some() {
410 return Err(Error::InvalidPattern);
411 }
412 let placeholder_offset = result.len() + 1;
413 if placeholder_offset >= 0xD800 {
414 return Err(Error::InvalidPattern);
415 }
416 let ph_info = DoublePlaceholderInfo {
417 key: ph_key,
418 offset: placeholder_offset,
419 };
420 if first_ph.is_none() {
421 first_ph.replace(ph_info);
422 } else {
423 second_ph.replace(ph_info);
424 }
425 }
426 }
427 }
428 let (first_ph, second_ph) = match (first_ph, second_ph) {
429 (Some(a), Some(b)) => (a, b),
430 (Some(a), None) => (a, a.swap().clear()),
431 (None, None) => (
432 DoublePlaceholderInfo::no_place0(),
433 DoublePlaceholderInfo::no_place0().swap(),
434 ),
435 (None, Some(_)) => unreachable!("first_ph always populated before second_ph"),
436 };
437 if first_ph.key == second_ph.key {
438 return Err(Error::InvalidPattern);
439 }
440
441 result.insert(0, second_ph.try_to_char()?);
442 result.insert(0, first_ph.try_to_char()?);
443
444 Ok(result.into_boxed_str())
445 }
446
447 fn empty() -> &'static Self::Store {
448 "\0\u{1}"
449 }
450 }
451
452 #[cfg(feature = "unstable")]
453 impl ExtractionBackend for DoublePlaceholder {
454 type DecodedMatchesUnstable<'p, 'a> = [Option<&'a str>; 2];
455
456 fn extract_unstable<'p, 'a>(
457 store: &'p Self::Store,
458 input: &'a str,
459 ) -> Option<Self::DecodedMatchesUnstable<'p, 'a>> {
460 let mut prefix = None;
461 let mut first_ph = None;
462 let mut infix = None;
463 let mut second_ph = None;
464 let mut suffix = None;
465
466 // Get the parts from the pattern
467 for item in Self::iter_items(store) {
468 match item {
469 PatternItem::Literal(s) => {
470 if first_ph.is_none() {
471 debug_assert!(prefix.is_none());
472 prefix = Some(s);
473 } else if second_ph.is_none() {
474 debug_assert!(infix.is_none());
475 infix = Some(s);
476 } else {
477 debug_assert!(suffix.is_none());
478 suffix = Some(s);
479 }
480 }
481 PatternItem::Placeholder(ph) => {
482 if first_ph.is_none() {
483 first_ph = Some(ph);
484 } else {
485 debug_assert!(second_ph.is_none());
486 second_ph = Some(ph);
487 }
488 }
489 }
490 }
491
492 // Resolve infix/suffix if there was only 1 placeholder
493 if second_ph.is_none() {
494 debug_assert!(suffix.is_none());
495 suffix = infix;
496 infix = None;
497 }
498
499 // Strip prefix and suffix from input
500 let remaining = input
501 .strip_prefix(prefix.unwrap_or(""))?
502 .strip_suffix(suffix.unwrap_or(""))?;
503
504 // Find placeholder matches
505 let mut matches = [None; 2];
506 match (first_ph, second_ph) {
507 (None, None) => {
508 // 0 placeholders
509 if remaining.is_empty() {
510 Some(matches)
511 } else {
512 None
513 }
514 }
515 (Some(key), None) => {
516 // 1 placeholder
517 let slot = match key {
518 DoublePlaceholderKey::Place0 => &mut matches[0],
519 DoublePlaceholderKey::Place1 => &mut matches[1],
520 };
521 *slot = Some(remaining);
522 Some(matches)
523 }
524 (Some(key_x), Some(key_y)) => {
525 // 2 placeholders
526 let (val_x, val_y) = match infix {
527 Some(inf) => remaining.split_once(inf)?,
528 None => ("", remaining),
529 };
530
531 let slot_x = match key_x {
532 DoublePlaceholderKey::Place0 => &mut matches[0],
533 DoublePlaceholderKey::Place1 => &mut matches[1],
534 };
535 *slot_x = Some(val_x);
536
537 let slot_y = match key_y {
538 DoublePlaceholderKey::Place0 => &mut matches[0],
539 DoublePlaceholderKey::Place1 => &mut matches[1],
540 };
541 *slot_y = Some(val_y);
542
543 Some(matches)
544 }
545 (None, Some(_)) => unreachable!("second_ph populated but first_ph is not"),
546 }
547 }
548
549 fn get_match_unstable<'p, 'b>(
550 store: &Self::DecodedMatchesUnstable<'p, 'b>,
551 key: Self::PlaceholderKey<'_>,
552 ) -> Option<&'b str> {
553 match key {
554 DoublePlaceholderKey::Place0 => store[0],
555 DoublePlaceholderKey::Place1 => store[1],
556 }
557 }
558 }
559
560 #[doc(hidden)] // TODO(#4467): Should be internal
561 #[derive(Debug)]
562 pub struct DoublePlaceholderPatternIterator<'a> {
563 store: &'a str,
564 ph_first: DoublePlaceholderInfo,
565 ph_second: DoublePlaceholderInfo,
566 current_offset: usize,
567 }
568
569 // Note: This impl is not exported via public bounds, but it might be in the
570 // future, and the compiler might be able to find it. The code is also
571 // reachable from `Iterator::size_hint`.
572 impl ExactSizeIterator for DoublePlaceholderPatternIterator<'_> {
573 fn len(&self) -> usize {
574 let mut chars = self.store.chars();
575 let (mut ph_first, ph_first_len) = match chars.next() {
576 Some(ch) => (DoublePlaceholderInfo::from_char(ch), ch.len_utf8()),
577 None => {
578 debug_assert!(false);
579 (DoublePlaceholderInfo::no_place0(), 0)
580 }
581 };
582 let (mut ph_second, ph_second_len) = match chars.next() {
583 Some(ch) => (DoublePlaceholderInfo::from_char(ch), ch.len_utf8()),
584 None => {
585 debug_assert!(false);
586 (ph_first.swap(), ph_first_len)
587 }
588 };
589 let initial_offset = ph_first_len + ph_second_len;
590 ph_first.offset += initial_offset - 1;
591 ph_second.offset += initial_offset - 1;
592 let store_len = self.store.len();
593
594 #[expect(clippy::comparison_chain)]
595 if ph_first.offset < initial_offset {
596 // No placeholders
597 if initial_offset < store_len {
598 // No placeholder, non-empty literal
599 1
600 } else {
601 // No placeholder, empty literal
602 0
603 }
604 } else if ph_first.offset == initial_offset {
605 // At least 1 placeholder, empty prefix
606 if ph_second.offset < initial_offset {
607 // Single placeholder
608 if ph_first.offset < store_len {
609 // Single placeholder, empty prefix, non-empty suffix
610 2
611 } else {
612 // Single placeholder, empty prefix, empty suffix
613 1
614 }
615 } else if ph_second.offset == ph_first.offset {
616 // Two placeholders, empty infix
617 if ph_first.offset < store_len {
618 // Two placeholders, empty prefix, empty infix, non-empty suffix
619 3
620 } else {
621 // Two placeholders, empty prefix, empty infix, empty suffix
622 2
623 }
624 } else if ph_second.offset < store_len {
625 // Two placeholders, empty prefix, non-empty infix, non-empty suffix
626 4
627 } else {
628 // Two placeholders, empty prefix, non-empty infix, empty suffix
629 3
630 }
631 } else {
632 // At least 1 placeholder, non-empty prefix
633 if ph_second.offset < initial_offset {
634 // Single placeholder
635 if ph_first.offset < store_len {
636 // Single placeholder, non-empty prefix, non-empty suffix
637 3
638 } else {
639 // Single placeholder, non-empty prefix, empty suffix
640 2
641 }
642 } else if ph_second.offset == ph_first.offset {
643 // Two placeholders, empty infix
644 if ph_first.offset < store_len {
645 // Two placeholders, non-empty prefix, empty infix, non-empty suffix
646 4
647 } else {
648 // Two placeholders, non-empty prefix, empty infix, empty suffix
649 3
650 }
651 } else if ph_second.offset < store_len {
652 // Two placeholders, non-empty prefix, non-empty infix, non-empty suffix
653 5
654 } else {
655 // Two placeholders, non-empty prefix, non-empty infix, empty suffix
656 4
657 }
658 }
659 }
660 }
661
662 impl<'a> Iterator for DoublePlaceholderPatternIterator<'a> {
663 type Item = PatternItem<'a, DoublePlaceholderKey>;
664 fn next(&mut self) -> Option<Self::Item> {
665 match self.current_offset.cmp(&self.ph_first.offset) {
666 Ordering::Less => {
667 // Prefix
668 let literal_str = match self.store.get(self.current_offset..self.ph_first.offset) {
669 Some(s) => s,
670 None => {
671 debug_assert!(false, "offsets are in range");
672 ""
673 }
674 };
675 self.current_offset = self.ph_first.offset;
676 Some(PatternItem::Literal(literal_str))
677 }
678 Ordering::Equal => {
679 // Placeholder
680 self.ph_first.offset = 0;
681 Some(PatternItem::Placeholder(self.ph_first.key))
682 }
683 Ordering::Greater => match self.current_offset.cmp(&self.ph_second.offset) {
684 Ordering::Less => {
685 // Infix
686 let literal_str =
687 match self.store.get(self.current_offset..self.ph_second.offset) {
688 Some(s) => s,
689 None => {
690 debug_assert!(false, "offsets are in range");
691 ""
692 }
693 };
694 self.current_offset = self.ph_second.offset;
695 Some(PatternItem::Literal(literal_str))
696 }
697 Ordering::Equal => {
698 // Placeholder
699 self.ph_second.offset = 0;
700 Some(PatternItem::Placeholder(self.ph_second.key))
701 }
702 Ordering::Greater => {
703 // Suffix or end of string
704 let literal_str = match self.store.get(self.current_offset..) {
705 Some(s) => s,
706 None => {
707 debug_assert!(false, "offsets are in range");
708 ""
709 }
710 };
711 if literal_str.is_empty() {
712 // End of string
713 None
714 } else {
715 // Suffix
716 self.current_offset = self.store.len();
717 Some(PatternItem::Literal(literal_str))
718 }
719 }
720 },
721 }
722 }
723
724 fn size_hint(&self) -> (usize, Option<usize>) {
725 let len = self.len();
726 (len, Some(len))
727 }
728 }
729
730 #[cfg(test)]
731 mod tests {
732 use super::*;
733 use crate::DoublePlaceholderPattern;
734
735 #[test]
736 fn test_permutations() {
737 #[derive(Debug)]
738 struct TestCase<'a> {
739 pattern: &'a str,
740 store: &'a str,
741 /// Interpolation with 0=apple, 1=orange
742 interpolated: &'a str,
743 }
744 let cases = [
745 TestCase {
746 pattern: "",
747 store: "\x00\x01",
748 interpolated: "",
749 },
750 TestCase {
751 pattern: "{0}",
752 store: "\x02\x01",
753 interpolated: "apple",
754 },
755 TestCase {
756 pattern: "X{0}",
757 store: "\x04\x01X",
758 interpolated: "Xapple",
759 },
760 TestCase {
761 pattern: "{0}Y",
762 store: "\x02\x01Y",
763 interpolated: "appleY",
764 },
765 TestCase {
766 pattern: "X{0}Y",
767 store: "\x04\x01XY",
768 interpolated: "XappleY",
769 },
770 TestCase {
771 pattern: "{1}",
772 store: "\x03\x00",
773 interpolated: "orange",
774 },
775 TestCase {
776 pattern: "X{1}",
777 store: "\x05\x00X",
778 interpolated: "Xorange",
779 },
780 TestCase {
781 pattern: "{1}Y",
782 store: "\x03\x00Y",
783 interpolated: "orangeY",
784 },
785 TestCase {
786 pattern: "X{1}Y",
787 store: "\x05\x00XY",
788 interpolated: "XorangeY",
789 },
790 TestCase {
791 pattern: "{0}{1}",
792 store: "\x02\x03",
793 interpolated: "appleorange",
794 },
795 TestCase {
796 pattern: "X{0}{1}",
797 store: "\x04\x05X",
798 interpolated: "Xappleorange",
799 },
800 TestCase {
801 pattern: "{0}Y{1}",
802 store: "\x02\x05Y",
803 interpolated: "appleYorange",
804 },
805 TestCase {
806 pattern: "{0}{1}Z",
807 store: "\x02\x03Z",
808 interpolated: "appleorangeZ",
809 },
810 TestCase {
811 pattern: "X{0}Y{1}",
812 store: "\x04\x07XY",
813 interpolated: "XappleYorange",
814 },
815 TestCase {
816 pattern: "X{0}{1}Z",
817 store: "\x04\x05XZ",
818 interpolated: "XappleorangeZ",
819 },
820 TestCase {
821 pattern: "{0}Y{1}Z",
822 store: "\x02\x05YZ",
823 interpolated: "appleYorangeZ",
824 },
825 TestCase {
826 pattern: "X{0}Y{1}Z",
827 store: "\x04\x07XYZ",
828 interpolated: "XappleYorangeZ",
829 },
830 TestCase {
831 pattern: "{1}{0}",
832 store: "\x03\x02",
833 interpolated: "orangeapple",
834 },
835 TestCase {
836 pattern: "X{1}{0}",
837 store: "\x05\x04X",
838 interpolated: "Xorangeapple",
839 },
840 TestCase {
841 pattern: "{1}Y{0}",
842 store: "\x03\x04Y",
843 interpolated: "orangeYapple",
844 },
845 TestCase {
846 pattern: "{1}{0}Z",
847 store: "\x03\x02Z",
848 interpolated: "orangeappleZ",
849 },
850 TestCase {
851 pattern: "X{1}Y{0}",
852 store: "\x05\x06XY",
853 interpolated: "XorangeYapple",
854 },
855 TestCase {
856 pattern: "X{1}{0}Z",
857 store: "\x05\x04XZ",
858 interpolated: "XorangeappleZ",
859 },
860 TestCase {
861 pattern: "{1}Y{0}Z",
862 store: "\x03\x04YZ",
863 interpolated: "orangeYappleZ",
864 },
865 TestCase {
866 pattern: "X{1}Y{0}Z",
867 store: "\x05\x06XYZ",
868 interpolated: "XorangeYappleZ",
869 },
870 TestCase {
871 pattern: "01234567890123456789012345678901234567890123456789012345678901234567890123456789{0}Y{1}Z",
872 store: "\u{A2}\u{A5}01234567890123456789012345678901234567890123456789012345678901234567890123456789YZ",
873 interpolated: "01234567890123456789012345678901234567890123456789012345678901234567890123456789appleYorangeZ",
874 },
875 ];
876 for cas in cases {
877 let TestCase {
878 pattern,
879 store,
880 interpolated,
881 } = cas;
882 let parsed =
883 DoublePlaceholderPattern::try_from_str(pattern, Default::default()).unwrap();
884 let actual = parsed
885 .interpolate(["apple", "orange"])
886 .write_to_string()
887 .into_owned();
888 assert_eq!(&parsed.store, store, "{cas:?}");
889 assert_eq!(actual, interpolated, "{cas:?}");
890 }
891 }
892
893 #[test]
894 fn test_invalid() {
895 let cases = [
896 "", // too short
897 "\x00", // too short
898 "\x00\x00", // duplicate placeholders
899 "\x04\x03", // first offset is after second offset
900 "\x04\x05", // second offset out of range (also first offset)
901 "\x04\u{10001}@", // second offset too large for UTF-8
902 ];
903 let long_str = "0123456789".repeat(1000000);
904 for cas in cases {
905 let cas = cas.replace('@', &long_str);
906 assert!(DoublePlaceholder::validate_store(&cas).is_err(), "{cas:?}");
907 }
908 }
909 }