iri-string 0.7.12

IRI as string types
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Template expansion context.
//!
//! # Examples
//!
//! 1. Define your context type.
//! 2. Implement [`Context`] trait (and [`Context::visit`] method) for the type.
//!     1. Get variable name by [`Visitor::var_name`] method.
//!     2. Feed the corresponding value(s) by one of `Visitor::visit_*` methods.
//!
//! Note that contexts should return consistent result across multiple visits for
//! the same variable. In other words, `Context::visit` should return the same
//! result for the same `Visitor::var_name()` during the context is borrowed.
//! If this condition is violated, the URI template processor can return
//! invalid result or panic at worst.
//!
//! ```
//! use iri_string::template::context::{Context, Visitor, ListVisitor, AssocVisitor};
//!
//! struct MyContext {
//!     name: &'static str,
//!     id: u64,
//!     tags: &'static [&'static str],
//!     children: &'static [(&'static str, usize)],
//! }
//!
//! impl Context for MyContext {
//!     fn visit<V: Visitor>(&self, visitor: V) -> V::Result {
//!         let name = visitor.var_name().as_str();
//!         match name {
//!             "name" => visitor.visit_string(self.name),
//!             "id" => visitor.visit_string(self.id),
//!             "tags" => visitor.visit_list().visit_items_and_finish(self.tags),
//!             "children" => visitor
//!                 .visit_assoc()
//!                 .visit_entries_and_finish(self.children.iter().copied()),
//!             _ => visitor.visit_undefined(),
//!         }
//!    }
//! }
//! ```
//!
//! Also check [`impl_template_context_naive!`] macro if your visitor
//! implementation will be straight-forward and most of field types are simple
//! standard types. The macro might reduce boilerplate.
//!
//! [`impl_template_context_naive!`]: `crate::impl_template_context_naive!`
//
// # Developers note
//
// Visitor types **should not** be cloneable in order to enforce just one
// visitor is used to visit a variable. If visitors are cloneable, it can make
// the wrong usage to be available, i.e. storing cloned visitors somewhere and
// using the wrong one.
//
// However, if visitors are made cloneable by any chance, it does not indicate
// the whole implementation will be broken. Users can only use the visitors
// through visitor traits (and their API do not allow cloning), so the logic
// would work as expected if the internal usage of the visitors are correct.
// Making visitors noncloneable is an optional safety guard (with no overhead).

/// Implement [`VisitValueNaive`] for the type.
///
/// # Synopsis
///
/// ```text
/// impl_template_context_naive! {
///     MyContextType {
///         my_field [ : "var_name" ] [ => fn_visit ]
///     }
/// }
/// ```
///
/// * `my_field` is the field name of `MyContextType`.
///     + If the context type is tuple, use the index like `0` and `1`.
/// * `"var_name"` is a `&str` literal for a variable name.
///     + If omitted, `my_field` is used as a variable name.
/// * `fn_visit` is an expression of a visitor function for the field.
///     + If omitted, [`template::context::visit_value_naive`][`visit_value_naive`]
///       function will be used.
///     + The signature should be <code>fn fn_visit<V: [Visitor][`Visitor`]>(visitor: V,
///       my_field_value: &MyFieldType)</code>
///     + Note that this function cannot be a closure, because it should be
///       generic over `V: Visitor` parameter and the current Rust (as of Rust
///       1.94) does not allow closures to be generic.
///
/// # Examples
///
/// ```
/// # use iri_string::template::Error;
/// use iri_string::impl_template_context_naive;
/// use iri_string::spec::UriSpec;
/// use iri_string::template::UriTemplateStr;
/// use iri_string::template::context::Visitor;
///
/// struct MyContext {
///     id: Option<u64>,
///     name: &'static str,
///     tags: &'static [&'static str],
///     children: &'static [(&'static str, usize)],
///     ignored: i32,
/// }
///
/// impl_template_context_naive! {
///     MyContext {
///         // custom styling and custom field name.
///         id: "user_id" => my_visit_user_id,
///         // custom field name.
///         name: "username",
///         // default styling and default field name.
///         tags,
///         // custom styling.
///         children => my_visit_slice_assoc,
///     }
/// }
///
/// fn my_visit_user_id<V>(visitor: V, id: &Option<u64>) -> V::Result
/// where
///     V: Visitor,
/// {
///     match id {
///         Some(v) => visitor.visit_string(format_args!("{v:04}")),
///         None => visitor.visit_undefined(),
///     }
/// }
///
/// fn my_visit_slice_assoc<V, K, T>(visitor: V, entries: &[(K, T)]) -> V::Result
/// where
///     V: Visitor,
///     K: core::fmt::Display,
///     T: core::fmt::Display,
/// {
///     visitor.visit_assoc_direct(entries.iter().map(|(k, v)| (k, v)))
/// }
///
/// let context = MyContext {
///     id: Some(42),
///     name: "foo",
///     tags: &["user", "admin"],
///     children: &[("bar", 99), ("baz", 314)],
///     ignored: 12345,
/// };
///
/// // The examples below requires `alloc` feature
/// // to be enabled (for `.to_string()`).
/// # #[cfg(feature = "alloc")] {
/// #
/// let id_user_template = UriTemplateStr::new("{?user_id,username}").unwrap();
/// assert_eq!(
///     id_user_template.expand::<UriSpec, _>(&context)?.to_string(),
///     "?user_id=0042&username=foo",
///     "custom styling and custom field name is used"
/// );
///
/// let tags_template = UriTemplateStr::new("{?tags*}").unwrap();
/// assert_eq!(
///     tags_template.expand::<UriSpec, _>(&context)?.to_string(),
///     "?tags=user&tags=admin"
/// );
///
/// let children_template = UriTemplateStr::new("{?children*}").unwrap();
/// assert_eq!(
///     children_template.expand::<UriSpec, _>(&context)?.to_string(),
///     "?bar=99&baz=314"
/// );
///
/// let ignored_template = UriTemplateStr::new("{?ignored}").unwrap();
/// assert_eq!(
///     ignored_template.expand::<UriSpec, _>(&context)?.to_string(),
///     "",
///     "`ignored` field is not visited so the value is undefined"
/// );
/// #
/// # }
/// # Ok::<(), Error>(())
/// ```
///
/// For tuple struct:
///
/// ```
/// # use iri_string::template::Error;
/// use iri_string::impl_template_context_naive;
/// use iri_string::spec::UriSpec;
/// use iri_string::template::UriTemplateStr;
/// use iri_string::template::context::Visitor;
///
/// struct Utf8Check(bool);
///
/// impl_template_context_naive! {
///     Utf8Check {
///         0: "utf8" => my_visit_utf8_bool,
///     }
/// }
///
/// fn my_visit_utf8_bool<V>(visitor: V, checked: &bool) -> V::Result
/// where
///     V: Visitor,
/// {
///     if *checked {
///         // U+2713 CHECK MARK
///         visitor.visit_string("\u{2713}")
///     } else {
///         visitor.visit_undefined()
///     }
/// }
///
/// let checked_ctx = Utf8Check(true);
/// let unchecked_ctx = Utf8Check(false);
///
/// // The examples below requires `alloc` feature
/// // to be enabled (for `.to_string()`).
/// # #[cfg(feature = "alloc")] {
/// #
/// let utf8_template = UriTemplateStr::new("{?utf8}").unwrap();
/// assert_eq!(
///     utf8_template.expand::<UriSpec, _>(&checked_ctx)?.to_string(),
///     "?utf8=%E2%9C%93"
/// );
/// assert_eq!(
///     utf8_template.expand::<UriSpec, _>(&unchecked_ctx)?.to_string(),
///     ""
/// );
/// #
/// # }
/// # Ok::<(), Error>(())
/// ```
#[macro_export]
macro_rules! impl_template_context_naive {
    ($ty:ty {
        $(
            $field:tt
            $(: $var_name:literal)?
            $(=> $fn_visit:expr)?
        ),*
        $(,)?
    }) => {
        impl $crate::template::context::Context for $ty {
            fn visit<V>(&self, visitor: V) -> V::Result
            where
                V: $crate::template::context::Visitor,
            {
                match visitor.var_name().as_str() {
                    $(
                        $crate::impl_template_context_naive!(@ var_name $field, $([ $var_name ])?)
                            => {
                            let fn_visit = $crate::impl_template_context_naive!(@ fn_visit $($fn_visit)?);
                            fn_visit(visitor, &self.$field)
                        },
                    )*
                    _ => visitor.visit_undefined(),
                }
            }
        }
    };
    (@ var_name $field:tt,) => {
        stringify!($field)
    };
    (@ var_name $field:tt, [ $var_name:literal ]) => {
        $var_name
    };
    (@ fn_visit $fn_visit:expr) => {
        $fn_visit
    };
    (@ fn_visit) => {
        $crate::template::context::visit_value_naive
    };
}

use core::fmt;
use core::ops::ControlFlow;

pub use crate::template::components::VarName;
pub use crate::template::value::{visit_value_naive, VisitValueNaive};

/// A trait for types that can behave as a static URI template expansion context.
///
/// This type is for use with [`UriTemplateStr::expand`] method.
///
/// See [the module documentation][`crate::template`] for usage.
///
/// [`UriTemplateStr::expand`]: `crate::template::UriTemplateStr::expand`
pub trait Context: Sized {
    /// Visits a variable.
    ///
    /// To get variable name, use [`Visitor::var_name()`].
    #[must_use]
    fn visit<V: Visitor>(&self, visitor: V) -> V::Result;
}

/// A trait for types that can behave as a dynamic (mutable) URI template expansion context.
///
/// This type is for use with [`UriTemplateStr::expand_dynamic`] method and its
/// family.
///
/// Note that "dynamic" here does not mean that the value of variables can
/// change during a template expansion. The value should be fixed and consistent
/// during each expansion, but the context is allowed to mutate itself if it
/// does not break this rule.
///
/// # Exmaples
///
/// ```
/// # #[cfg(feature = "alloc")]
/// # extern crate alloc;
/// # use iri_string::template::Error;
/// # #[cfg(feature = "alloc")] {
/// # use alloc::string::String;
/// use iri_string::template::UriTemplateStr;
/// use iri_string::template::context::{DynamicContext, Visitor, VisitPurpose};
/// use iri_string::spec::UriSpec;
///
/// struct MyContext<'a> {
///     /// Target path.
///     target: &'a str,
///     /// Username.
///     username: Option<&'a str>,
///     /// A flag to remember whether the URI template
///     /// attempted to use `username` variable.
///     username_visited: bool,
/// }
///
/// impl DynamicContext for MyContext<'_> {
///     fn on_expansion_start(&mut self) {
///         // Reset the state.
///         self.username_visited = false;
///     }
///     fn visit_dynamic<V: Visitor>(&mut self, visitor: V) -> V::Result {
///         match visitor.var_name().as_str() {
///             "target" => visitor.visit_string(self.target),
///             "username" => {
///                 if visitor.purpose() == VisitPurpose::Expand {
///                     // The variable `username` is being used
///                     // on the template expansion.
///                     // Don't care whether `username` is defined or not.
///                     self.username_visited = true;
///                 }
///                 if let Some(username) = &self.username {
///                     visitor.visit_string(username)
///                 } else {
///                     visitor.visit_undefined()
///                 }
///             }
///             _ => visitor.visit_undefined(),
///         }
///     }
/// }
///
/// let mut context = MyContext {
///     target: "/posts/1",
///     username: Some("the_admin"),
///     username_visited: false,
/// };
/// let mut buf = String::new();
///
/// // No access to the variable `username`.
/// let template1 = UriTemplateStr::new("{+target}")?;
/// template1.expand_dynamic::<UriSpec, _, _>(&mut buf, &mut context)?;
/// assert_eq!(buf, "/posts/1");
/// assert!(!context.username_visited);
///
/// buf.clear();
/// // Will access to the variable `username`.
/// let template2 = UriTemplateStr::new("{+target}{?username}")?;
/// template2.expand_dynamic::<UriSpec, _, _>(&mut buf, &mut context)?;
/// assert_eq!(buf, "/posts/1?username=the_admin");
/// assert!(context.username_visited);
///
/// buf.clear();
/// context.username = None;
/// // Will access to the variable `username` but it is undefined.
/// template2.expand_dynamic::<UriSpec, _, _>(&mut buf, &mut context)?;
/// assert_eq!(buf, "/posts/1");
/// assert!(
///     context.username_visited,
///     "`MyContext` can know and remember whether `visit_dynamic()` is called
///      for `username`, even if its value is undefined"
/// );
/// # }
/// # Ok::<_, Error>(())
/// ```
///
/// [`UriTemplateStr::expand_dynamic`]: `crate::template::UriTemplateStr::expand_dynamic`
pub trait DynamicContext: Sized {
    /// Visits a variable.
    ///
    /// To get variable name, use [`Visitor::var_name()`].
    ///
    /// # Restriction
    ///
    /// The visit results should be consistent and unchanged between the last
    /// time [`on_expansion_start`][`Self::on_expansion_start`] was called and
    /// the next time [`on_expansion_end`][`Self::on_expansion_end`] will be
    /// called. If this condition is violated, template expansion will produce
    /// wrong result or may panic at worst.
    #[must_use]
    fn visit_dynamic<V: Visitor>(&mut self, visitor: V) -> V::Result;

    /// A callback that is called before the expansion of a URI template.
    #[inline]
    fn on_expansion_start(&mut self) {}

    /// A callback that is called after the expansion of a URI template.
    #[inline]
    fn on_expansion_end(&mut self) {}
}

impl<C: Context> DynamicContext for C {
    #[inline]
    fn visit_dynamic<V: Visitor>(&mut self, visitor: V) -> V::Result {
        self.visit(visitor)
    }
}

/// A purpose of a visit.
///
/// This enum is nonexhaustive since this partially exposes the internal
/// implementation of the template expansion, and thus this is subject to
/// change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum VisitPurpose {
    /// A visit for type checking.
    Typecheck,
    /// A visit for template expansion to retrieve the value.
    Expand,
}

/// Variable visitor.
///
/// See [the module documentation][self] for usage.
// NOTE (internal): Visitor types **should not** be cloneable.
pub trait Visitor: Sized + private::Sealed {
    /// Result of the visit.
    type Result;
    /// List visitor.
    type ListVisitor: ListVisitor<Result = Self::Result>;
    /// Associative array visitor.
    type AssocVisitor: AssocVisitor<Result = Self::Result>;

    /// Returns the name of the variable to visit.
    #[must_use]
    fn var_name(&self) -> VarName<'_>;
    /// Returns the purpose of the visit.
    ///
    /// The template expansion algorithm checks the types for some variables
    /// depending on its usage. To get the usage count correctly, you should
    /// only count visits with [`VisitPurpose::Expand`].
    ///
    /// If you need to know whether the variable is accessed and does not
    /// need dynamic context generation or access counts, consider using
    /// [`UriTemplateStr::variables`] method to iterate the variables in the
    /// URI template.
    ///
    /// [`UriTemplateStr::variables`]: `crate::template::UriTemplateStr::variables`
    #[must_use]
    fn purpose(&self) -> VisitPurpose;
    /// Visits an undefined variable, i.e. indicates that the requested variable is unavailable.
    #[must_use]
    fn visit_undefined(self) -> Self::Result;
    /// Visits a string variable.
    #[must_use]
    fn visit_string<T: fmt::Display>(self, v: T) -> Self::Result;
    /// Visits a list variable.
    ///
    /// If all the items are in a single iterable value, you can use
    /// [`visit_list_direct`][`Self::visit_list_direct`] instead for convenience.
    #[must_use]
    fn visit_list(self) -> Self::ListVisitor;
    /// Visits an associative array variable.
    ///
    /// If all the entries are in a single iterable value, you can use
    /// [`visit_assoc_direct`][`Self::visit_assoc_direct`] instead for convenience.
    #[must_use]
    fn visit_assoc(self) -> Self::AssocVisitor;

    /// Visits just a single list and finishes the visit right away.
    fn visit_list_direct<I, T>(self, items: I) -> Self::Result
    where
        I: IntoIterator<Item = T>,
        T: fmt::Display,
    {
        self.visit_list().visit_items_and_finish(items)
    }

    /// Visits just a single associative array and finishes the visit right away.
    fn visit_assoc_direct<I, K, T>(self, entries: I) -> Self::Result
    where
        I: IntoIterator<Item = (K, T)>,
        K: fmt::Display,
        T: fmt::Display,
    {
        self.visit_assoc().visit_entries_and_finish(entries)
    }
}

/// List visitor.
///
/// See [the module documentation][self] for usage.
// NOTE (internal): Visitor types **should not** be cloneable.
pub trait ListVisitor: Sized + private::Sealed {
    /// Result of the visit.
    type Result;

    /// Visits an item.
    ///
    /// If this returned `ControlFlow::Break(v)`, [`Context::visit`] should also
    /// return this `v`.
    ///
    /// To feed multiple items at once, do
    /// `items.into_iter().try_for_each(|item| self.visit_item(item))` for example.
    fn visit_item<T: fmt::Display>(&mut self, item: T) -> ControlFlow<Self::Result>;
    /// Finishes visiting the list.
    #[must_use]
    fn finish(self) -> Self::Result;

    /// Visits items and finish.
    #[must_use]
    fn visit_items_and_finish<T, I>(mut self, items: I) -> Self::Result
    where
        T: fmt::Display,
        I: IntoIterator<Item = T>,
    {
        match items.into_iter().try_for_each(|item| self.visit_item(item)) {
            ControlFlow::Break(v) => v,
            ControlFlow::Continue(()) => self.finish(),
        }
    }
}

/// Associative array visitor.
///
/// See [the module documentation][self] for usage.
// NOTE (internal): Visitor types **should not** be cloneable.
pub trait AssocVisitor: Sized + private::Sealed {
    /// Result of the visit.
    type Result;

    /// Visits an entry.
    ///
    /// If this returned `ControlFlow::Break(v)`, [`Context::visit`] should also
    /// return this `v`.
    ///
    /// To feed multiple items at once, do
    /// `entries.into_iter().try_for_each(|(key, value)| self.visit_entry(key, value))`
    /// for example.
    fn visit_entry<K: fmt::Display, V: fmt::Display>(
        &mut self,
        key: K,
        value: V,
    ) -> ControlFlow<Self::Result>;
    /// Finishes visiting the associative array.
    #[must_use]
    fn finish(self) -> Self::Result;

    /// Visits entries and finish.
    #[must_use]
    fn visit_entries_and_finish<K, V, I>(mut self, entries: I) -> Self::Result
    where
        K: fmt::Display,
        V: fmt::Display,
        I: IntoIterator<Item = (K, V)>,
    {
        match entries
            .into_iter()
            .try_for_each(|(key, value)| self.visit_entry(key, value))
        {
            ControlFlow::Break(v) => v,
            ControlFlow::Continue(()) => self.finish(),
        }
    }
}

/// Private module to put the trait to seal.
pub(super) mod private {
    /// A trait for visitor types of variables in a context.
    pub trait Sealed {}
}