### not_yet_decoded example Source: https://docs.rs/iri-string/0.7.14/iri_string/percent_encode/decode/struct.PercentDecodedWhatwgBytes.html Shows how to use the not_yet_decoded method to get the raw input bytes. The example decodes b"hello%20world" and asserts the returned slice equals the original input. ```rust use iri_string::percent_encode::decode::decode_whatwg_bytes; let decoded = decode_whatwg_bytes(b"hello%20world"); assert_eq!(decoded.not_yet_decoded(), &b"hello%20world"[..]); ``` -------------------------------- ### to_bytes example Source: https://docs.rs/iri-string/0.7.14/iri_string/percent_encode/decode/struct.PercentDecodedWhatwgBytes.html Shows how to use the to_bytes method to get decoded bytes without allocation. The example demonstrates that when no allocation is needed, it returns Some, and when allocation is needed, it returns None. ```rust use iri_string::percent_encode::decode::decode_whatwg_bytes; let no_alloc = decode_whatwg_bytes(b"99% unsafe"); assert_eq!(no_alloc.to_bytes(), Some(&b"99% unsafe"[..])); let alloc_needed = decode_whatwg_bytes(b"hello%20world"); assert_eq!(alloc_needed.to_bytes(), None); ``` -------------------------------- ### IriQueryStr::from_prefixed examples Source: https://docs.rs/iri-string/latest/src/iri_string/types/generic/query.rs.html Demonstrates the `from_prefixed` method, which expects the input to start with `?` and strips it before validation. Valid inputs include `?`, `?foo`, and `?query?again`. Invalid inputs include missing `?` prefix, `<`/`>`, broken percent encoding, and `#`. ```rust # use iri_string::types::IriQueryStr; assert!(IriQueryStr::from_prefixed("?").is_ok()); assert!(IriQueryStr::from_prefixed("?foo").is_ok()); assert!(IriQueryStr::from_prefixed("?foo/bar").is_ok()); assert!(IriQueryStr::from_prefixed("?/foo/bar").is_ok()); assert!(IriQueryStr::from_prefixed("?//foo/bar").is_ok()); assert!(IriQueryStr::from_prefixed("?https://user:pass@example.com:8080").is_ok()); assert!(IriQueryStr::from_prefixed("?https://example.com/").is_ok()); // Question sign `?` can appear in an IRI query. assert!(IriQueryStr::from_prefixed("?query?again").is_ok()); // `<` and `>` cannot directly appear in an IRI. assert!(IriQueryStr::from_prefixed("?").is_err()); // Broken percent encoding cannot appear in an IRI. assert!(IriQueryStr::new("?%").is_err()); assert!(IriQueryStr::new("?%GG").is_err()); // `?` prefix is expected. assert!(IriQueryStr::from_prefixed("").is_err()); assert!(IriQueryStr::from_prefixed("foo").is_err()); // Hash sign `#` cannot appear in an IRI query. assert!(IriQueryStr::from_prefixed("?#hash").is_err()); ``` -------------------------------- ### fragment_str returns Some for fragment at start Source: https://docs.rs/iri-string/latest/iri_string/types/struct.RiRelativeStr.html Returns the fragment when it appears at the start of the IRI. This example shows a fragment without a query. ```rust let iri = IriRelativeStr::new("#foo")?; assert_eq!(iri.fragment_str(), Some("foo")); ``` -------------------------------- ### Synopsis Example Source: https://docs.rs/iri-string/latest/iri_string/macro.impl_template_context_naive.html Basic usage syntax for the impl_template_context_naive macro. ```rust impl_template_context_naive! { MyContextType { my_field [ : "var_name" ] [ => fn_visit ] } } ``` -------------------------------- ### Builder usage example Source: https://docs.rs/iri-string/latest/iri_string/build/struct.Builder.html Shows the full workflow: create a builder, set components, normalize, build, and serialize or convert. The example uses `Builder::new()`, `scheme`, `host`, `path`, `normalize`, and `build::()`. The result is serialized with `to_string()` and converted into `IriString`. ```rust use iri_string::build::Builder; use iri_string::types::{IriStr, IriString}; // 1. Create builder. let mut builder = Builder::new(); // 2. Set (or unset) component and normalization mode. builder.scheme("http"); builder.host("example.com"); builder.path("/foo/../"); builder.normalize(); // 3. Validate and create the result. let built = builder.build::()?; // 4a. Serialize by `Display` trait (or `ToString`). let s = built.to_string(); assert_eq!(s, "http://example.com/"); // 4b. Convert into an allocated string types. // Thanks to pre-validation by `.build::()`, this conversion is infallible! let s: IriString = built.into(); assert_eq!(s, "http://example.com/"); ``` -------------------------------- ### fragment returns Some for fragment at start Source: https://docs.rs/iri-string/latest/iri_string/types/struct.RiRelativeStr.html Returns the fragment when it appears at the start of the IRI. This example shows a fragment without a query. ```rust let iri = IriRelativeStr::new("#foo")?; let fragment = IriFragmentStr::new("foo")?; assert_eq!(iri.fragment(), Some(fragment)); ``` -------------------------------- ### Get IRI path Source: https://docs.rs/iri-string/latest/iri_string/types/struct.RiReferenceStr.html Examples of extracting the path component from an IRI reference. ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("http://example.com/pathpath?queryquery#fragfrag")?; assert_eq!(iri.path_str(), "/pathpath"); ``` ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("urn:uuid:10db315b-fcd1-4428-aca8-15babc9a2da2")?; assert_eq!(iri.path_str(), "uuid:10db315b-fcd1-4428-aca8-15babc9a2da2"); ``` ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("foo/bar:baz")?; assert_eq!(iri.path_str(), "foo/bar:baz"); ``` -------------------------------- ### into_bytes example Source: https://docs.rs/iri-string/0.7.14/iri_string/percent_encode/decode/struct.PercentDecodedWhatwgBytes.html Shows how to use the into_bytes method to decode bytes using the WHATWG percent-decode algorithm. The example decodes b"hello%20world" and asserts the result is b"hello world". ```rust use iri_string::percent_encode::decode::decode_whatwg_bytes; let decoded = decode_whatwg_bytes(b"hello%20world"); assert_eq!(decoded.into_bytes(), &b"hello world"[..]); ``` -------------------------------- ### Get query part with IriRelativeStr::query() Source: https://docs.rs/iri-string/0.7.14/src/iri_string/types/generic/relative.rs.html Shows how to use `IriRelativeStr::query()` to get the query part as an `IriQueryStr`. The first example has a non-empty query, the second has an empty query. ```rust let iri = IriRelativeStr::new("//example.com/pathpath?queryquery#fragfrag")?; assert_eq!(iri.query(), Some(query)); # Ok::<_, Error>(()) ``` ```rust let iri = IriRelativeStr::new("foo//bar:baz?")?; let query = IriQueryStr::new("")?; assert_eq!(iri.query(), Some(query)); # Ok::<_, Error>(()) ``` -------------------------------- ### iri_string::template module documentation with custom Context and SimpleContext examples Source: https://docs.rs/iri-string/latest/src/iri_string/template.rs.html The module-level documentation for `iri_string::template` shows how to create a template, prepare a context, expand it, and use the result. It includes two examples: one with a custom `Context` implementation and one using `SimpleContext` (enabled by the `alloc` feature flag). Both examples expand the same template `/users/{username}{?utf8}` and compare the output for `UriSpec` (percent-encoded) and `IriSpec` (raw Unicode). ```rust //! Processor for [RFC 6570] URI Template. //! //! [RFC 6570]: https://www.rfc-editor.org/rfc/rfc6570.html //! //! # Usage //! //! 1. Prepare a template. //! * You can create a template as [`UriTemplateStr`] #![cfg_attr( feature = "alloc", doc = " type (borrowed) or [`UriTemplateString`] type (owned)." )] #![cfg_attr(not(feature = "alloc"), doc = " type.")] //! 2. Prepare a context. //! * Create a value of type that implements [`Context`] trait. #![cfg_attr( feature = "alloc", doc = " * Or, if you use [`SimpleContext`], insert key-value pairs into it." )] //! 3. Expand. //! * Pass the context to [`UriTemplateStr::expand`] method of the template. //! 4. Use the result. //! * Returned [`Expanded`] object can be directly printed since it //! implements [`Display`][`core::fmt::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][`context`]. //! //! ``` //! # use iri_string::template::Error; //! 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( //! &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}")?; //! //! # #[cfg(feature = "alloc")] { //! assert_eq!( //! template.expand::(&context)?.to_string(), //! "/users/foo?utf8=%E2%9C%93" //! ); //! assert_eq!( //! template.expand::(&context)?.to_string(), //! "/users/foo?utf8=\u{2713}" //! ); //! # } //! # Ok::<_, Error>(()) //! ``` //! //! ## `SimpleContext` type (enabled by `alloc` feature flag) //! //! ``` //! # 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("username", "foo"); //! // U+2713 CHECK MARK //! context.insert("utf8", "\u{2713}"); //! //! let template = UriTemplateStr::new("/users/{username}{?utf8}")?; //! //! assert_eq!( //! template.expand::(&context)?.to_string(), //! "/users/foo?utf8=%E2%9C%93" //! ); //! assert_eq!( //! template.expand::(&context)?.to_string(), //! "/users/foo?utf8=\u{2713}" //! ); //! # } //! # Ok::<_, Error>(()) //! ``` //! //! [`SimpleContext`]: `simple_context::SimpleContext` ``` -------------------------------- ### into_string example Source: https://docs.rs/iri-string/0.7.14/iri_string/percent_encode/decode/struct.PercentDecodedWhatwgBytes.html Shows how to use the into_string method to decode bytes into a String. The example decodes b"hello%20world" and asserts the result is Ok("hello world".to_owned()). ```rust use iri_string::percent_encode::decode::decode_whatwg_bytes; let decoded = decode_whatwg_bytes(b"hello%20world"); assert_eq!( decoded.into_string(), Ok("hello world".to_owned()) ); ``` -------------------------------- ### Get query string with IriRelativeStr::query_str() Source: https://docs.rs/iri-string/0.7.14/src/iri_string/types/generic/relative.rs.html Shows how to use `IriRelativeStr::query_str()` to get the query as a raw string slice. The first example has a non-empty query, the second has an empty query. ```rust let iri = IriRelativeStr::new("//example.com/pathpath?queryquery#fragfrag")?; assert_eq!(iri.query_str(), Some("queryquery")); # Ok::<_, Error>(()) ``` ```rust let iri = IriRelativeStr::new("foo//bar:baz?")?; assert_eq!(iri.query_str(), Some("")); # Ok::<_, Error>(()) ``` -------------------------------- ### Apply IDNA conversion to domain name Source: https://docs.rs/iri-string/0.7.14/src/iri_string/types/generic/relative.rs.html Demonstrates how to extract a domain, convert it to IDNA encoding, and update the IRI. ```rust # extern crate alloc; # use alloc::string::String; # use iri_string::types::IriRelativeString; /// Converts the given into IDNA encoding. fn conv_idna(domain: &str) -> String { /* ... */ # if domain == "\u{03B1}.example.com" { # "xn--mxa.example.com".into() # } else { # unimplemented!() # } } // U+03B1: GREEK SMALL LETTER ALPHA let mut iri = IriRelativeString::try_from("//\u{03B1}.example.com/").unwrap(); let old_domain = iri .authority_components() .expect("authority is not empty") .reg_name() .expect("the host is reg-name"); assert_eq!(old_domain, "\u{03B1}.example.com"); // Get the new host by your own. let new_domain: String = conv_idna(old_domain); assert_eq!(new_domain, "xn--mxa.example.com"); let new_host_opt = iri.replace_host(&new_domain); assert_eq!(new_host_opt, Some("xn--mxa.example.com")); assert_eq!(iri.authority_components().unwrap().host(), "xn--mxa.example.com"); assert_eq!(iri, "//xn--mxa.example.com/"); ``` -------------------------------- ### Get the path with FixedBaseResolver::path_str Source: https://docs.rs/iri-string/0.7.14/src/iri_string/resolve.rs.html Shows how to get the path component from a FixedBaseResolver using path_str(). The example uses a base IRI with a path and asserts that the path is "/base/". ```rust # use iri_string::validate::Error; use iri_string::resolve::FixedBaseResolver; use iri_string::types::IriAbsoluteStr; let base = IriAbsoluteStr::new("http://user:pass@example.com/base/?query")?; let resolver = FixedBaseResolver::new(base); assert_eq!(resolver.path_str(), "/base/"); assert_eq!(base.path_str(), "/base/"); # Ok::<_, Error>(()) ``` -------------------------------- ### Builder::scheme example Source: https://docs.rs/iri-string/0.7.14/src/iri_string/build.rs.html Shows how to set the scheme on a Builder and build an IriReferenceStr. The resulting string is "foo:" when the alloc feature is enabled. ```rust # use iri_string::validate::Error; use iri_string::build::Builder; use iri_string::types::IriReferenceStr; let mut builder = Builder::new(); builder.scheme("foo"); let iri = builder.build::()?; # #[cfg(feature = "alloc")] { assert_eq!(iri.to_string(), "foo:"); # } # Ok::<_, Error>(()) ``` -------------------------------- ### SimpleContext example for UriTemplateStr expansion Source: https://docs.rs/iri-string/0.7.14/src/iri_string/template.rs.html Shows how to use SimpleContext to insert key-value pairs and expand a URI template. The example inserts 'username' and 'utf8' values, then asserts expansion results for both UriSpec and IriSpec, demonstrating percent-encoding differences. This example is only available when the 'alloc' feature is enabled. ```rust # 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("username", "foo"); // U+2713 CHECK MARK context.insert("utf8", "\u{2713}"); let template = UriTemplateStr::new("/users/{username}{?utf8}")?; assert_eq!( template.expand::(&context)?.to_string(), "/users/foo?utf8=%E2%9C%93" ); assert_eq!( template.expand::(&context)?.to_string(), "/users/foo?utf8=\u{2713}" ); # } # Ok::<_, Error>(()) ``` -------------------------------- ### Get the scheme with FixedBaseResolver::scheme_str Source: https://docs.rs/iri-string/0.7.14/src/iri_string/resolve.rs.html Shows how to get the scheme component from a FixedBaseResolver using scheme_str(). The example uses a base IRI with a query and asserts that the scheme is "http". ```rust # use iri_string::validate::Error; use iri_string::resolve::FixedBaseResolver; use iri_string::types::IriAbsoluteStr; let base = IriAbsoluteStr::new("http://example.com/base/?query")?; let resolver = FixedBaseResolver::new(base); assert_eq!(resolver.scheme_str(), "http"); assert_eq!(base.scheme_str(), "http"); # Ok::<_, Error>(()) ``` -------------------------------- ### Builder::new example Source: https://docs.rs/iri-string/0.7.14/iri_string/build/struct.Builder.html Creates a new builder with empty data. ```rust use iri_string::build::Builder; use iri_string::types::IriReferenceStr; let builder = Builder::new(); let iri = builder.build::()?; assert_eq!(iri.to_string(), ""); ``` -------------------------------- ### Enable normalization with Builder::normalize Source: https://docs.rs/iri-string/latest/src/iri_string/build.rs.html Demonstrates enabling normalization on a Builder to produce a fully normalized IRI. The example sets scheme, userinfo, host, port, and path, then calls normalize() before building; the result is percent-encoded and case-normalized, and path segments are normalized. ```rust # use iri_string::validate::Error; use iri_string::build::Builder; use iri_string::types::IriReferenceStr; let mut builder = Builder::new(); builder.scheme("http"); // `%75%73%65%72` is "user". builder.userinfo("%75%73%65%72"); builder.host("EXAMPLE.COM"); builder.port(""); builder.path("/foo/../%2e%2e/bar/%2e/baz/."); builder.normalize(); let iri = builder.build::()?; # #[cfg(feature = "alloc")] { assert_eq!(iri.to_string(), "http://user@example.com/bar/baz/"); # } # Ok::<_, Error>(()) ``` ``` -------------------------------- ### Get fragment part with IriRelativeStr::fragment() Source: https://docs.rs/iri-string/0.7.14/src/iri_string/types/generic/relative.rs.html Shows how to use `IriRelativeStr::fragment()` to get the fragment part as an `IriFragmentStr`. The first three examples have a fragment (including an empty one), the last has no fragment and returns `None`. ```rust let iri = IriRelativeStr::new("?foo#bar")?; let fragment = IriFragmentStr::new("bar")?; assert_eq!(iri.fragment(), Some(fragment)); # Ok::<_, Error>(()) ``` ```rust let iri = IriRelativeStr::new("#foo")?; let fragment = IriFragmentStr::new("foo")?; assert_eq!(iri.fragment(), Some(fragment)); # Ok::<_, Error>(()) ``` ```rust let iri = IriRelativeStr::new("#")?; let fragment = IriFragmentStr::new("")?; assert_eq!(iri.fragment(), Some(fragment)); # Ok::<_, Error>(()) ``` ```rust let iri = IriRelativeStr::new("")?; assert_eq!(iri.fragment(), None); # Ok::<_, Error>(()) ``` -------------------------------- ### Get IRI scheme Source: https://docs.rs/iri-string/latest/iri_string/types/struct.RiReferenceStr.html Examples of extracting the scheme component from an IRI reference, noting that the trailing colon is excluded. ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("http://example.com/pathpath?queryquery#fragfrag")?; assert_eq!(iri.scheme_str(), Some("http")); ``` ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("foo/bar:baz")?; assert_eq!(iri.scheme_str(), None); ``` -------------------------------- ### query() examples Source: https://docs.rs/iri-string/0.7.14/iri_string/types/type.IriAbsoluteStr.html Returns the query as an `Option<&RiQueryStr>`, with the leading `?` truncated. The first example shows a query present; the second shows an IRI without a query, yielding `None`. ```rust use iri_string::types::{IriAbsoluteStr, IriQueryStr}; let iri = IriAbsoluteStr::new("http://example.com/pathpath?queryquery")?; let query = IriQueryStr::new("queryquery")?; assert_eq!(iri.query(), Some(query)); ``` ```rust use iri_string::types::IriAbsoluteStr; let iri = IriAbsoluteStr::new("urn:uuid:10db315b-fcd1-4428-aca8-15babc9a2da2")?; assert_eq!(iri.query(), None); ``` -------------------------------- ### Build an IRI with Builder and convert to IriString Source: https://docs.rs/iri-string/0.7.14/src/iri_string/build.rs.html Shows the recommended usage of `Builder` to construct an IRI: create a builder, set components and normalization mode, validate with `build::()`, then serialize via `Display` or convert into `IriString`. The example uses `builder.scheme("http")`, `builder.host("example.com")`, `builder.path("/foo/../")`, and `builder.normalize()`; the resulting string is `"http://example.com/"`. The `alloc` feature gates the `IriString` conversion and the `Display` serialization block. ```rust # use iri_string::validate::Error; use iri_string::build::Builder; # #[cfg(not(feature = "alloc"))] # use iri_string::types::IriStr; # #[cfg(feature = "alloc")] use iri_string::types::{IriStr, IriString}; // 1. Create builder. let mut builder = Builder::new(); // 2. Set (or unset) component and normalization mode. builder.scheme("http"); builder.host("example.com"); builder.path("/foo/../"); builder.normalize(); // 3. Validate and create the result. let built = builder.build::()?; # #[cfg(feature = "alloc")] { // 4a. Serialize by `Display` trait (or `ToString`). let s = built.to_string(); assert_eq!(s, "http://example.com/"); # } # #[cfg(feature = "alloc")] { // 4b. Convert into an allocated string types. // Thanks to pre-validation by `.build::()`, this conversion is infallible! let s: IriString = built.into(); ``` -------------------------------- ### Get IRI authority Source: https://docs.rs/iri-string/latest/iri_string/types/struct.RiReferenceStr.html Examples of extracting the authority component from an IRI reference, noting that the leading double slash is excluded. ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("http://example.com/pathpath?queryquery#fragfrag")?; assert_eq!(iri.authority_str(), Some("example.com")); ``` ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("urn:uuid:10db315b-fcd1-4428-aca8-15babc9a2da2")?; assert_eq!(iri.authority_str(), None); ``` ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("foo/bar:baz")?; assert_eq!(iri.authority_str(), None); ``` -------------------------------- ### Builder example assertion Source: https://docs.rs/iri-string/0.7.14/src/iri_string/build.rs.html Shows the expected output of a builder example: the built IRI string equals "http://example.com/". The code is a doc comment fragment from the source, not a complete example. ```rust /// assert_eq!(s, "http://example.com/"); /// # } /// /// # Ok::<_, Error>(()) /// ``` ``` -------------------------------- ### Get the base from FixedBaseResolver Source: https://docs.rs/iri-string/latest/iri_string/resolve/struct.FixedBaseResolver.html Returns the base IRI as a RiAbsoluteStr. The example shows that resolver.base() returns the same reference as the original base. ```rust use iri_string::resolve::FixedBaseResolver; use iri_string::types::{IriAbsoluteStr, IriReferenceStr}; let base = IriAbsoluteStr::new("http://example.com/base/")?; let resolver = FixedBaseResolver::new(base); assert_eq!(resolver.base(), base); ``` -------------------------------- ### Get scheme when absent Source: https://docs.rs/iri-string/0.7.14/iri_string/types/struct.RiReferenceStr.html Returns None when the IRI reference has no scheme. The string "foo/bar:baz" is not a valid scheme because the colon is not at the start. ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("foo/bar:baz")?; assert_eq!(iri.scheme_str(), None); ``` -------------------------------- ### impl_template_context_naive! struct example with custom visitor Source: https://docs.rs/iri-string/latest/src/iri_string/template/context.rs.html Example for the `impl_template_context_naive!` macro with a struct context. It defines a custom visitor for a slice of key-value pairs and demonstrates expansion of URI templates with custom field names, list expansion, and undefined fields. Requires the `alloc` feature for `.to_string()`. ```rust /// None => visitor.visit_undefined(), /// } /// } /// /// fn my_visit_slice_assoc(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::(&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::(&context)?.to_string(), /// "?tags=user&tags=admin" /// ); /// /// let children_template = UriTemplateStr::new("{?children*}").unwrap(); /// assert_eq!( /// children_template.expand::(&context)?.to_string(), /// "?bar=99&baz=314" /// ); /// /// let ignored_template = UriTemplateStr::new("{?ignored}").unwrap(); /// assert_eq!( /// ignored_template.expand::(&context)?.to_string(), /// "", /// "`ignored` field is not visited so the value is undefined" /// ); /// # /// # } /// # Ok::<(), Error>(()) /// ``` ``` -------------------------------- ### Get authority string from absolute IRI Source: https://docs.rs/iri-string/latest/src/iri_string/types/generic/absolute.rs.html Two examples for `authority_str()`: one with an authority (returns `Some("example.com")`) and one without (returns `None`). ```rust use iri_string::validate::Error; use iri_string::types::IriAbsoluteStr; let iri = IriAbsoluteStr::new("http://example.com/pathpath?queryquery")?; assert_eq!(iri.authority_str(), Some("example.com")); Ok::<_, Error>(()) ``` ```rust use iri_string::validate::Error; use iri_string::types::IriAbsoluteStr; let iri = IriAbsoluteStr::new("urn:uuid:10db315b-fcd1-4428-aca8-15babc9a2da2")?; assert_eq!(iri.authority_str(), None); Ok::<_, Error>(()) ``` -------------------------------- ### Get authority when absent (relative) Source: https://docs.rs/iri-string/0.7.14/iri_string/types/struct.RiReferenceStr.html Returns None when the IRI reference has no authority. The string "foo/bar:baz" does not start with "//". ```rust use iri_string::types::IriReferenceStr; let iri = IriReferenceStr::new("foo/bar:baz")?; assert_eq!(iri.authority_str(), None); ``` -------------------------------- ### Valid IRI examples using IriStr::new Source: https://docs.rs/iri-string/latest/src/iri_string/types/generic/normal.rs.html Shows valid absolute IRI strings that can be parsed by `IriStr::new`. Includes examples with user info, port, path, query, fragment, and various authority forms. ```rust //! Usual absolute IRI (fragment part being allowed). #[cfg(feature = "alloc")] use alloc::collections::TryReserveError; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::String; use crate::components::AuthorityComponents; #[cfg(feature = "alloc")] use crate::mask_password::password_range_to_hide; use crate::mask_password::PasswordMasked; use crate::normalize::{Error, NormalizationInput, Normalized, NormalizednessCheckMode}; use crate::parser::trusted as trusted_parser; #[cfg(feature = "alloc")] use crate::raw; use crate::spec::Spec; use crate::types::{RiAbsoluteStr, RiFragmentStr, RiQueryStr, RiReferenceStr}; #[cfg(feature = "alloc")] use crate::types::{RiAbsoluteString, RiFragmentString, RiReferenceString}; use crate::validate::iri; define_custom_string_slice! { /// A borrowed string of an absolute IRI possibly with fragment part. /// /// This corresponds to [`IRI` rule] in [RFC 3987] (and [`URI` rule] in [RFC 3986]). /// The rule for `IRI` is `scheme ":" ihier-part [ "?" iquery ] [ "#" ifragment ]`. /// In other words, this is [`RiAbsoluteStr`] with fragment part allowed. /// /// # Valid values /// /// This type can have an IRI (which is absolute, and may have fragment part). /// /// ``` /// # use iri_string::types::IriStr; /// assert!(IriStr::new("https://user:pass@example.com:8080").is_ok()); /// assert!(IriStr::new("https://example.com/").is_ok()); /// assert!(IriStr::new("https://example.com/foo?bar=baz").is_ok()); /// assert!(IriStr::new("https://example.com/foo?bar=baz#qux").is_ok()); /// assert!(IriStr::new("foo:bar").is_ok()); /// assert!(IriStr::new("foo:").is_ok()); /// // `foo://.../` below are all allowed. See the crate documentation for detail. /// assert!(IriStr::new("foo:/").is_ok()); /// assert!(IriStr::new("foo://").is_ok()); /// assert!(IriStr::new("foo:///").is_ok()); /// assert!(IriStr::new("foo:////").is_ok()); /// assert!(IriStr::new("foo://///").is_ok()); /// ``` /// /// Relative IRI reference is not allowed. /// /// ``` /// # use iri_string::types::IriStr; /// // This is relative path. /// assert!(IriStr::new("foo/bar").is_err()); /// // `/foo/bar` is an absolute path, but it is authority-relative. /// assert!(IriStr::new("/foo/bar").is_err()); /// // `//foo/bar` is termed "network-path reference", /// // or usually called "protocol-relative reference". /// assert!(IriStr::new("//foo/bar").is_err()); /// // Same-document reference is relative. /// assert!(IriStr::new("#foo").is_err()); /// // Empty string is not a valid absolute IRI. /// assert!(IriStr::new("").is_err()); /// ``` /// /// Some characters and sequences cannot used in an IRI. /// /// ``` /// # use iri_string::types::IriStr; /// // `<` and `>` cannot directly appear in an IRI. /// assert!(IriStr::new("").is_err()); /// // Broken percent encoding cannot appear in an IRI. /// assert!(IriStr::new("%").is_err()); /// assert!(IriStr::new("%GG").is_err()); /// ``` /// /// [RFC 3986]: https://www.rfc-editor.org/rfc/rfc3986.html /// [RFC 3987]: https://www.rfc-editor.org/rfc/rfc3987.html /// [`IRI` rule]: https://www.rfc-editor.org/rfc/rfc3987.html#section-2.2 /// [`URI` rule]: https://www.rfc-editor.org/rfc/rfc3986.html#section-3 /// [`RiAbsoluteStr`]: struct.RiAbsoluteStr.html struct RiStr { validator = iri, expecting_msg = "IRI string", } } #[cfg(feature = "alloc")] define_custom_string_owned! { /// An owned string of an absolute IRI possibly with fragment part. /// /// This corresponds to [`IRI` rule] in [RFC 3987] (and [`URI` rule] in [RFC 3986]). /// The rule for `IRI` is `scheme ":" ihier-part [ "?" iquery ] [ "#" ifragment ]`. /// In other words, this is [`RiAbsoluteString`] with fragment part allowed. /// /// For details, see the document for [`RiStr`]. /// /// Enabled by `alloc` or `std` feature. /// /// [RFC 3986]: https://www.rfc-editor.org/rfc/rfc3986.html /// [RFC 3987]: https://www.rfc-editor.org/rfc/rfc3987.html /// [`IRI` rule]: https://www.rfc-editor.org/rfc/rfc3987.html#section-2.2 /// [`URI` rule]: https://www.rfc-editor.org/rfc/rfc3986.html#section-3 /// [`RiAbsoluteString`]: struct.RiAbsoluteString.html struct RiString { validator = iri, slice = RiStr, expecting_msg = "IRI string", } } impl RiStr { ``` -------------------------------- ### replace_host example Source: https://docs.rs/iri-string/0.7.14/iri_string/types/struct.RiAbsoluteString.html Example for `replace_host` on `UriAbsoluteString`. Replaces the host in-place and returns the new host; the authority is preserved. ```rust let mut iri = UriAbsoluteString::try_from("https://user:pass@example.com:443/").unwrap(); let new_host_opt = iri.replace_host("www.example.com"); assert_eq!(new_host_opt, Some("www.example.com")); assert_eq!(iri.authority_components().unwrap().host(), "www.example.com"); assert_eq!(iri, "https://user:pass@www.example.com:443/"); ``` -------------------------------- ### scheme validation examples Source: https://docs.rs/iri-string/0.7.14/iri_string/validate/fn.scheme.html Example usage of the scheme function. It demonstrates valid schemes (https, file, git+ssh) and invalid ones (with colon, empty, starting with digit or symbol). The comments highlight that a trailing colon is not part of the scheme, the scheme cannot be empty, and the first character must be alphabetic. ```rust use iri_string::validate::scheme; assert!(scheme("https").is_ok()); assert!(scheme("file").is_ok()); assert!(scheme("git+ssh").is_ok()); // Colon is syntactically not part of the scheme. assert!(scheme("colon:").is_err()); // Scheme cannot be empty. assert!(scheme("").is_err()); // The first character should be alphabetic character. assert!(scheme("0abc").is_err()); assert!(scheme("+a").is_err()); assert!(scheme("-a").is_err()); ``` -------------------------------- ### Example usage: validate port with assertions Source: https://docs.rs/iri-string/0.7.14/iri_string/validate/fn.port.html Shows how to call port() with valid and invalid ports. Valid examples include leading zeros and large numbers, while a leading colon is rejected. ```rust use iri_string::validate::port; assert!(port("0").is_ok()); assert!(port("8080").is_ok()); assert!(port("0000080").is_ok()); // URI/IRI syntax itself does not have limit on the port number. assert!(port("999999999").is_ok()); // The leading colon is not a part of the `port`. assert!(port(":443").is_err()); ``` -------------------------------- ### Get path_str() from IriAbsoluteStr Source: https://docs.rs/iri-string/0.7.14/src/iri_string/types/generic/absolute.rs.html Returns the path component of an absolute IRI, with the leading slash removed. The example uses a URN with no authority, so the path is the entire string after the scheme. ```rust let iri = IriAbsoluteStr::new("urn:uuid:10db315b-fcd1-4428-aca8-15babc9a2da2")?; assert_eq!(iri.path_str(), "uuid:10db315b-fcd1-4428-aca8-15babc9a2da2"); ``` -------------------------------- ### Struct Implementation Example Source: https://docs.rs/iri-string/latest/iri_string/macro.impl_template_context_naive.html Implementing the macro for a struct with custom visitor functions and field mappings. ```rust 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, 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(visitor: V, id: &Option) -> 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(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()`). let id_user_template = UriTemplateStr::new("{?user_id,username}").unwrap(); assert_eq!( id_user_template.expand::(&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::(&context)?.to_string(), "?tags=user&tags=admin" ); let children_template = UriTemplateStr::new("{?children*}").unwrap(); assert_eq!( children_template.expand::(&context)?.to_string(), "?bar=99&baz=314" ); let ignored_template = UriTemplateStr::new("{?ignored}").unwrap(); assert_eq!( ignored_template.expand::(&context)?.to_string(), "", "`ignored` field is not visited so the value is undefined" ); ``` -------------------------------- ### len: Get template string length Source: https://docs.rs/iri-string/0.7.14/iri_string/template/struct.UriTemplateString.html Returns the length of the template string. The example creates a UriTemplateStr and asserts that len equals the length of the original string literal. ```rust use iri_string::template::UriTemplateStr; let template = UriTemplateStr::new("/users/{username}")?; assert_eq!(template.len(), "/users/{username}".len()); ```