iri_string

Module template

source
Expand description

Processor for RFC 6570 URI Template.

§Usage

  1. Prepare a template.
  2. Prepare a context.
    • Create a value of type that implements Context trait.
    • Or, if you use SimpleContext, insert key-value pairs into it.
  3. Expand.
  4. Use the result.
    • Returned Expanded object can be directly printed since it implements Display trait. Or, you can call .to_string() method of the alloc::string::ToString trait to convert it to a String.

§Examples

§Custom context type

For details, see the documentation of context module.

use core::fmt;
use iri_string::spec::{IriSpec, Spec, UriSpec};
use iri_string::template::UriTemplateStr;
use iri_string::template::context::{Context, VarName, Visitor};

struct UserInfo {
    username: &'static str,
    utf8_available: bool,
}

impl Context for UserInfo {
    fn visit<V: Visitor>(
        &self,
        visitor: V,
    ) -> V::Result {
        match visitor.var_name().as_str() {
            "username" => visitor.visit_string(self.username),
            "utf8" => {
                if self.utf8_available {
                    // U+2713 CHECK MARK
                    visitor.visit_string("\u{2713}")
                } else {
                    visitor.visit_undefined()
                }
            }
            _ => visitor.visit_undefined()
        }
    }
}

let context = UserInfo {
    username: "foo",
    utf8_available: true,
};

let template = UriTemplateStr::new("/users/{username}{?utf8}")?;

assert_eq!(
    template.expand::<UriSpec, _>(&context)?.to_string(),
    "/users/foo?utf8=%E2%9C%93"
);
assert_eq!(
    template.expand::<IriSpec, _>(&context)?.to_string(),
    "/users/foo?utf8=\u{2713}"
);

§SimpleContext type (enabled by alloc feature flag)

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("username", "foo");
// U+2713 CHECK MARK
context.insert("utf8", "\u{2713}");

let template = UriTemplateStr::new("/users/{username}{?utf8}")?;

assert_eq!(
    template.expand::<UriSpec, _>(&context)?.to_string(),
    "/users/foo?utf8=%E2%9C%93"
);
assert_eq!(
    template.expand::<IriSpec, _>(&context)?.to_string(),
    "/users/foo?utf8=\u{2713}"
);

Re-exports§

Modules§

Structs§

Type Aliases§