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 384 385 386 387 388 389 390 391 392 393 394 395
// 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 ).
#[cfg(feature = "databake")]
mod databake;
#[cfg(feature = "serde")]
pub(crate) mod serde;
use crate::common::*;
#[cfg(feature = "alloc")]
use crate::Error;
#[cfg(feature = "alloc")]
use crate::Parser;
#[cfg(feature = "alloc")]
use crate::ParserOptions;
#[cfg(feature = "alloc")]
use alloc::{borrow::ToOwned, boxed::Box, str::FromStr, string::String};
use core::{
convert::Infallible,
fmt::{self, Write},
marker::PhantomData,
};
use writeable::{adapters::TryWriteableInfallibleAsWriteable, PartsWrite, TryWriteable, Writeable};
/// A string pattern with placeholders.
///
/// There are 2 generic parameters: `Backend` and `Store`.
///
/// # Backend
///
/// This determines the nature of placeholders and serialized encoding of the pattern.
///
/// The following backends are available:
///
/// - [`SinglePlaceholder`] for patterns with up to one placeholder: `"{0} days ago"`
/// - [`DoublePlaceholder`] for patterns with up to two placeholders: `"{0} days, {1} hours ago"`
/// - [`MultiNamedPlaceholder`] for patterns with named placeholders: `"{name} sent you a message"`
///
/// # Format to Parts
///
/// [`Pattern`] supports interpolating with [writeable::Part]s, annotations for whether the
/// substring was a placeholder or a literal.
///
/// By default, the substrings are annotated with [`PATTERN_LITERAL_PART`] and
/// [`PATTERN_PLACEHOLDER_PART`]. This can be customized with [`PlaceholderValueProvider`].
///
/// # Examples
///
/// Interpolating a [`SinglePlaceholder`] pattern with parts:
///
/// ```
/// use core::str::FromStr;
/// use icu_pattern::Pattern;
/// use icu_pattern::SinglePlaceholder;
/// use writeable::assert_writeable_parts_eq;
///
/// let pattern =
/// Pattern::<SinglePlaceholder>::try_from_str("Hello, {0}!", Default::default()).unwrap();
///
/// assert_writeable_parts_eq!(
/// pattern.interpolate(["Alice"]),
/// "Hello, Alice!",
/// [
/// (0, 7, icu_pattern::PATTERN_LITERAL_PART),
/// (7, 12, icu_pattern::PATTERN_PLACEHOLDER_PART),
/// (12, 13, icu_pattern::PATTERN_LITERAL_PART),
/// ]
/// );
/// ```
///
/// [`SinglePlaceholder`]: crate::SinglePlaceholder
/// [`DoublePlaceholder`]: crate::DoublePlaceholder
/// [`MultiNamedPlaceholder`]: crate::MultiNamedPlaceholder
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[repr(transparent)]
pub struct Pattern<B: PatternBackend> {
_backend: PhantomData<B>,
/// The encoded storage
pub store: B::Store,
}
impl<B: PatternBackend> PartialEq for Pattern<B> {
fn eq(&self, other: &Self) -> bool {
self.store == other.store
}
}
impl<B: PatternBackend> core::fmt::Debug for Pattern<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pattern")
.field("_backend", &self._backend)
.field("store", &&self.store)
.finish()
}
}
impl<B: PatternBackend> Default for &'static Pattern<B> {
fn default() -> Self {
Pattern::from_ref_store_unchecked(B::empty())
}
}
#[cfg(feature = "alloc")]
impl<B: PatternBackend> Default for Box<Pattern<B>>
where
Box<B::Store>: From<&'static B::Store>,
{
fn default() -> Self {
Pattern::from_boxed_store_unchecked(Box::from(B::empty()))
}
}
#[test]
fn test_defaults() {
assert_eq!(
Box::<Pattern::<crate::SinglePlaceholder>>::default(),
Pattern::try_from_items(core::iter::empty()).unwrap()
);
assert_eq!(
Box::<Pattern::<crate::DoublePlaceholder>>::default(),
Pattern::try_from_items(core::iter::empty()).unwrap()
);
assert_eq!(
Box::<Pattern::<crate::MultiNamedPlaceholder>>::default(),
Pattern::try_from_items(core::iter::empty()).unwrap()
);
}
#[cfg(feature = "alloc")]
impl<B: PatternBackend> ToOwned for Pattern<B>
where
Box<B::Store>: for<'a> From<&'a B::Store>,
{
type Owned = Box<Pattern<B>>;
fn to_owned(&self) -> Self::Owned {
Self::from_boxed_store_unchecked(Box::from(&self.store))
}
}
#[cfg(feature = "alloc")]
impl<B: PatternBackend> Clone for Box<Pattern<B>>
where
Box<B::Store>: for<'a> From<&'a B::Store>,
{
fn clone(&self) -> Self {
Pattern::from_boxed_store_unchecked(Box::from(&self.store))
}
}
impl<B: PatternBackend> Pattern<B> {
#[cfg(feature = "alloc")]
pub(crate) const fn from_boxed_store_unchecked(store: Box<B::Store>) -> Box<Self> {
// Safety: Pattern's layout is the same as B::Store's
unsafe { core::mem::transmute(store) }
}
#[doc(hidden)] // databake
pub const fn from_ref_store_unchecked(store: &B::Store) -> &Self {
// Safety: Pattern's layout is the same as B::Store's
unsafe { &*(store as *const B::Store as *const Self) }
}
}
#[cfg(feature = "alloc")]
impl<B> Pattern<B>
where
B: PatternBackend,
{
/// Creates a pattern from an iterator of pattern items.
///
/// ✨ *Enabled with the `alloc` Cargo feature.*
///
/// # Examples
///
/// ```
/// use icu_pattern::Pattern;
/// use icu_pattern::PatternItemCow;
/// use icu_pattern::SinglePlaceholder;
/// use icu_pattern::SinglePlaceholderKey;
/// use std::borrow::Cow;
///
/// Pattern::<SinglePlaceholder>::try_from_items(
/// [
/// PatternItemCow::Placeholder(SinglePlaceholderKey::Singleton),
/// PatternItemCow::Literal(Cow::Borrowed(" days")),
/// ]
/// .into_iter(),
/// )
/// .expect("valid pattern items");
/// ```
pub fn try_from_items<'a, I>(items: I) -> Result<Box<Self>, Error>
where
I: Iterator<Item = PatternItemCow<'a, B::PlaceholderKeyCow<'a>>>,
{
let store = B::try_from_items(items.map(Ok))?;
#[cfg(debug_assertions)]
match B::validate_store(core::borrow::Borrow::borrow(&store)) {
Ok(()) => (),
Err(e) => {
debug_assert!(false, "{:?}", e);
}
};
Ok(Self::from_boxed_store_unchecked(store))
}
}
#[cfg(feature = "alloc")]
impl<'a, B> Pattern<B>
where
B: PatternBackend,
B::PlaceholderKeyCow<'a>: FromStr,
<B::PlaceholderKeyCow<'a> as FromStr>::Err: fmt::Debug,
{
/// Creates a pattern by parsing a syntax string.
///
/// ✨ *Enabled with the `alloc` Cargo feature.*
///
/// # Examples
///
/// ```
/// use icu_pattern::Pattern;
/// use icu_pattern::SinglePlaceholder;
///
/// // Create a pattern from a valid string:
/// Pattern::<SinglePlaceholder>::try_from_str("{0} days", Default::default())
/// .expect("valid pattern");
///
/// // Error on an invalid pattern:
/// Pattern::<SinglePlaceholder>::try_from_str("{0 days", Default::default())
/// .expect_err("mismatched braces");
/// ```
pub fn try_from_str(pattern: &str, options: ParserOptions) -> Result<Box<Self>, Error> {
let parser = Parser::new(pattern, options);
let store = B::try_from_items(parser)?;
#[cfg(debug_assertions)]
match B::validate_store(core::borrow::Borrow::borrow(&store)) {
Ok(()) => (),
Err(e) => {
debug_assert!(false, "{:?} for pattern {:?}", e, pattern);
}
};
Ok(Self::from_boxed_store_unchecked(store))
}
}
impl<B> Pattern<B>
where
B: PatternBackend,
{
/// Returns an iterator over the [`PatternItem`]s in this pattern.
pub fn iter(&self) -> impl Iterator<Item = PatternItem<B::PlaceholderKey<'_>>> + '_ {
B::iter_items(&self.store)
}
/// Returns a [`TryWriteable`] that interpolates items from the given replacement provider
/// into this pattern string.
pub fn try_interpolate<'a, P>(
&'a self,
value_provider: P,
) -> impl TryWriteable<Error = B::Error<'a>> + fmt::Display + 'a
where
P: PlaceholderValueProvider<B::PlaceholderKey<'a>, Error = B::Error<'a>> + 'a,
{
WriteablePattern::<B, P> {
store: &self.store,
value_provider,
}
}
#[cfg(feature = "alloc")]
/// Interpolates the pattern directly to a string, returning the string or an error.
///
/// In addition to the error, the lossy fallback string is returned in the failure case.
///
/// ✨ *Enabled with the `alloc` Cargo feature.*
pub fn try_interpolate_to_string<'a, P>(
&'a self,
value_provider: P,
) -> Result<String, (B::Error<'a>, String)>
where
P: PlaceholderValueProvider<B::PlaceholderKey<'a>, Error = B::Error<'a>> + 'a,
{
self.try_interpolate(value_provider)
.try_write_to_string()
.map(|s| s.into_owned())
.map_err(|(e, s)| (e, s.into_owned()))
}
}
impl<B> Pattern<B>
where
for<'b> B: PatternBackend<Error<'b> = Infallible>,
{
/// Returns a [`Writeable`] that interpolates items from the given replacement provider
/// into this pattern string.
pub fn interpolate<'a, P>(&'a self, value_provider: P) -> impl Writeable + fmt::Display + 'a
where
P: PlaceholderValueProvider<B::PlaceholderKey<'a>, Error = B::Error<'a>> + 'a,
{
TryWriteableInfallibleAsWriteable(WriteablePattern::<B, P> {
store: &self.store,
value_provider,
})
}
#[cfg(feature = "alloc")]
/// Interpolates the pattern directly to a string.
///
/// ✨ *Enabled with the `alloc` Cargo feature.*
pub fn interpolate_to_string<'a, P>(&'a self, value_provider: P) -> String
where
P: PlaceholderValueProvider<B::PlaceholderKey<'a>, Error = B::Error<'a>> + 'a,
{
self.interpolate(value_provider)
.write_to_string()
.into_owned()
}
}
struct WriteablePattern<'a, B: PatternBackend, P> {
store: &'a B::Store,
value_provider: P,
}
impl<'a, B, P> TryWriteable for WriteablePattern<'a, B, P>
where
B: PatternBackend,
P: PlaceholderValueProvider<B::PlaceholderKey<'a>, Error = B::Error<'a>>,
{
type Error = B::Error<'a>;
fn try_write_to_parts<S: PartsWrite + ?Sized>(
&self,
sink: &mut S,
) -> Result<Result<(), Self::Error>, fmt::Error> {
let mut error = None;
let it = B::iter_items(self.store);
#[cfg(debug_assertions)]
let (size_hint, mut actual_len) = (it.size_hint(), 0);
for item in it {
match item {
PatternItem::Literal(s) => {
sink.with_part(P::LITERAL_PART, |sink| sink.write_str(s))?;
}
PatternItem::Placeholder(key) => {
let (element_writeable, part) = self.value_provider.value_for(key);
sink.with_part(part, |sink| {
if let Err(e) = element_writeable.try_write_to_parts(sink)? {
// Keep the first error if there was one
error.get_or_insert(e);
}
Ok(())
})?;
}
}
#[cfg(debug_assertions)]
{
actual_len += 1;
}
}
#[cfg(debug_assertions)]
{
debug_assert!(actual_len >= size_hint.0);
if let Some(max_len) = size_hint.1 {
debug_assert!(actual_len <= max_len);
}
}
if let Some(e) = error {
Ok(Err(e))
} else {
Ok(Ok(()))
}
}
}
impl<'a, B, P> fmt::Display for WriteablePattern<'a, B, P>
where
B: PatternBackend,
P: PlaceholderValueProvider<B::PlaceholderKey<'a>, Error = B::Error<'a>>,
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Discard the TryWriteable error (lossy mode)
self.try_write_to(f).map(|_| ())
}
}
#[test]
fn test_try_from_str_inference() {
use crate::SinglePlaceholder;
let _: Box<Pattern<SinglePlaceholder>> =
Pattern::try_from_str("{0} days", Default::default()).unwrap();
let _ = Pattern::<SinglePlaceholder>::try_from_str("{0} days", Default::default()).unwrap();
}