Struct UriTemplateStr

struct UriTemplateStr { ... }

A borrowed slice of a URI template.

URI Template is defined by RFC 6570.

Note that "URI Template" can also be used for IRI.

Valid values

This type can have a URI template string.

Applied errata

Errata ID 6937 is applied, so single quotes are allowed to appear in an URI template.

# use iri_string::template::Error;
use iri_string::template::UriTemplateStr;

let template = UriTemplateStr::new("'quoted'")?;
# Ok::<_, Error>(())

Implementations

impl UriTemplateStr

fn new(s: &str) -> Result<&Self, Error>

Creates a new string.

Examples

# use iri_string::template::Error;
use iri_string::template::UriTemplateStr;

let template = UriTemplateStr::new("/users/{username}")?;
# Ok::<_, Error>(())
unsafe fn new_unchecked(s: &str) -> &Self

Creates a new string without validation.

This does not validate the given string, so it is caller's responsibility to ensure the given string is valid.

Safety

The given string must be syntactically valid as Self type. If not, any use of the returned value or the call of this function itself may result in undefined behavior.

fn as_str(self: &Self) -> &str

Returns the template as a plain &str.

Examples

# use iri_string::template::Error;
use iri_string::template::UriTemplateStr;

let template = UriTemplateStr::new("/users/{username}")?;
assert_eq!(template.as_str(), "/users/{username}");
# Ok::<_, Error>(())
fn len(self: &Self) -> usize

Returns the template string length.

Examples

# use iri_string::template::Error;
use iri_string::template::UriTemplateStr;

let template = UriTemplateStr::new("/users/{username}")?;
assert_eq!(template.len(), "/users/{username}".len());
# Ok::<_, Error>(())
fn is_empty(self: &Self) -> bool

Returns whether the string is empty.

Examples

# use iri_string::template::Error;
use iri_string::template::UriTemplateStr;

let template = UriTemplateStr::new("/users/{username}")?;
assert!(!template.is_empty());

let empty = UriTemplateStr::new("")?;
assert!(empty.is_empty());
# Ok::<_, Error>(())

impl UriTemplateStr

fn expand<'a, S: Spec, C: Context>(self: &'a Self, context: &'a C) -> Result<Expanded<'a, S, C>, Error>

Expands the template with the given context.

Examples

# use iri_string::template::Error;
# #[cfg(feature = "alloc")] {
use iri_string::spec::UriSpec;
use iri_string::template::UriTemplateStr;
use iri_string::template::simple_context::SimpleContext;

let mut context = SimpleContext::new();
context.insert("username", "foo");

let template = UriTemplateStr::new("/users/{username}")?;
let expanded = template.expand::<UriSpec, _>(&context)?;

assert_eq!(
    expanded.to_string(),
    "/users/foo"
);
# }
# Ok::<_, Error>(())

You can control allowed characters in the output by changing spec type.

# use iri_string::template::Error;
# #[cfg(feature = "alloc")] {
use iri_string::spec::{IriSpec, UriSpec};
use iri_string::template::UriTemplateStr;
use iri_string::template::simple_context::SimpleContext;

let mut context = SimpleContext::new();
context.insert("alpha", "\u{03B1}");

let template = UriTemplateStr::new("{?alpha}")?;

assert_eq!(
    template.expand::<UriSpec, _>(&context)?.to_string(),
    "?alpha=%CE%B1",
    "a URI cannot contain Unicode alpha (U+03B1), so it should be escaped"
);
assert_eq!(
    template.expand::<IriSpec, _>(&context)?.to_string(),
    "?alpha=\u{03B1}",
    "an IRI can contain Unicode alpha (U+03B1), so it written as is"
);
# }
# Ok::<_, Error>(())
fn expand_dynamic<S: Spec, W: fmt::Write, C: DynamicContext>(self: &Self, writer: &mut W, context: &mut C) -> Result<(), Error>

Expands the template with the given dynamic context.

If you need the allocated String, use[expand_dynamic_to_string]Self::expand_dynamic_to_string.

See the documentation for DynamicContext for usage.

fn expand_dynamic_to_string<S: Spec, C: DynamicContext>(self: &Self, context: &mut C) -> Result<String, Error>

Expands the template into a string, with the given dynamic context.

This is basically [expand_dynamic]Self::expand_dynamic method that returns an owned string instead of writing to the given writer.

See the documentation for DynamicContext for usage.

Examples

# #[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> {
    // See the documentation for `DynamicContext`.
#     /// 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,
};

// No access to the variable `username`.
let template = UriTemplateStr::new("{+target}{?username}")?;
let s = template.expand_dynamic_to_string::<UriSpec, _>(&mut context)?;
assert_eq!(s, "/posts/1?username=the_admin");
assert!(context.username_visited);
# }
# Ok::<_, Error>(())
fn variables(self: &Self) -> UriTemplateVariables<'_>

Returns an iterator of variables in the template.

Examples

# use iri_string::template::Error;
use iri_string::template::UriTemplateStr;

let template = UriTemplateStr::new("foo{/bar*,baz:4}{?qux}{&bar*}")?;
let mut vars = template.variables();
assert_eq!(vars.next().map(|var| var.as_str()), Some("bar"));
assert_eq!(vars.next().map(|var| var.as_str()), Some("baz"));
assert_eq!(vars.next().map(|var| var.as_str()), Some("qux"));
assert_eq!(vars.next().map(|var| var.as_str()), Some("bar"));
# Ok::<_, Error>(())

impl AsRef for UriTemplateStr

fn as_ref(self: &Self) -> &UriTemplateStr

impl AsRef for UriTemplateStr

fn as_ref(self: &Self) -> &str

impl Debug for UriTemplateStr

fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result

impl Display for UriTemplateStr

fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result

impl Eq for UriTemplateStr

impl Freeze for UriTemplateStr

impl Hash for UriTemplateStr

fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H)

impl Ord for UriTemplateStr

fn cmp(self: &Self, other: &UriTemplateStr) -> Ordering

impl PartialEq for UriTemplateStr

fn eq(self: &Self, o: &Cow<'_, str>) -> bool

impl PartialEq for UriTemplateStr

fn eq(self: &Self, o: &&str) -> bool

impl PartialEq for UriTemplateStr

fn eq(self: &Self, o: &str) -> bool

impl PartialEq for UriTemplateStr

fn eq(self: &Self, other: &UriTemplateStr) -> bool

impl PartialOrd for UriTemplateStr

fn partial_cmp(self: &Self, other: &UriTemplateStr) -> Option<Ordering>

impl PartialOrd for UriTemplateStr

fn partial_cmp(self: &Self, o: &Cow<'_, str>) -> Option<Ordering>

impl PartialOrd for UriTemplateStr

fn partial_cmp(self: &Self, o: &&str) -> Option<Ordering>

impl PartialOrd for UriTemplateStr

fn partial_cmp(self: &Self, o: &str) -> Option<Ordering>

impl RefUnwindSafe for UriTemplateStr

impl Send for UriTemplateStr

impl Sized for UriTemplateStr

impl StructuralPartialEq for UriTemplateStr

impl Sync for UriTemplateStr

impl ToOwned for UriTemplateStr

fn to_owned(self: &Self) -> <Self as >::Owned

impl Unpin for UriTemplateStr

impl UnsafeUnpin for UriTemplateStr

impl UnwindSafe for UriTemplateStr

impl<T> Any for UriTemplateStr

fn type_id(self: &Self) -> TypeId

impl<T> Borrow for UriTemplateStr

fn borrow(self: &Self) -> &T

impl<T> BorrowMut for UriTemplateStr

fn borrow_mut(self: &mut Self) -> &mut T

impl<T> ToString for UriTemplateStr

fn to_string(self: &Self) -> String