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
// Enable all clippy lints and enforce, and opt out of individual lints
#![cfg_attr(feature = "cargo-clippy", warn(clippy::cargo, clippy::pedantic, clippy::nursery))]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::module_name_repetitions, clippy::non_ascii_literal))]

//! To use this library, instantiate an [`UriTemplate`] with a relevant string. From here, the result can be "discarded"
//! if only validation of the input string is needed, or a list of contained expressions or variables can be retrieved
//! with [`expressions()`] or [`variables()`]. Finally, the URI template can be expanded by called [`expand()`] with a
//! [`HashMap<&str, &str>`] of variables and values.
//!
//! ```rust
//! use rfc6570_level_2::UriTemplate;
//!
//! # fn main() -> anyhow::Result<()> {
//! let template = UriTemplate::new("https://example.com/{resource}/{+id}{#field}")?;
//!
//! // What variables are available?
//! let variables: Vec<&str> = template.variables().collect();
//! assert_eq!(variables, vec!["resource", "id", "field"]);
//!
//! let var_map = [
//!     ("resource", "user"),
//!     ("id", "5"),
//!     ("field", "email"),
//! ].iter().cloned().collect();
//!
//! // Expand the template
//! let uri = template.expand(&var_map);
//! assert_eq!(uri, "https://example.com/user/5#email");
//! # Ok(())
//! # }
//! ```
//!
//! [`UriTemplate`]: struct.UriTemplate.html
//! [`expressions()`]: struct.UriTemplate.html#method.expressions
//! [`variables()`]: struct.UriTemplate.html#method.variables
//! [`expand()`]: struct.UriTemplate.html#method.expand
//! [`HashMap<&str, &str>`]: https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html

use anyhow::anyhow;
use itertools::Itertools;
use percent_encoding::NON_ALPHANUMERIC;
use percent_encoding::{utf8_percent_encode, AsciiSet};
use std::collections::HashMap;

mod combinators;
mod parsers;

/// A template URI validated against [RFC6570] Level 2.
///
/// [RFC6570]: https://tools.ietf.org/html/rfc6570
pub struct UriTemplate(String);

impl UriTemplate {
    /// Validates a string against [RFC6570] Level 2; if valid, returns a URI template that can later be expanded.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rfc6570_level_2::UriTemplate;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let template = UriTemplate::new("https://example.com/{resource}/{+id}{#field}")?;
    /// assert_eq!(template.uri(), "https://example.com/{resource}/{+id}{#field}");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// An error describing the offending component will be returned in case of a validation failure.
    ///
    /// [RFC6570]: https://tools.ietf.org/html/rfc6570
    pub fn new(uri: &str) -> anyhow::Result<Self> {
        match crate::parsers::uri_template(uri) {
            Ok(_) => Ok(Self(uri.to_owned())),
            Err(error) => Err(anyhow!(error.map(|mut e| e.input = uri))),
        }
    }

    /// Returns a reference to the string backing the URI template.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rfc6570_level_2::UriTemplate;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let template = UriTemplate::new("https://example.com/{resource}/{+id}{#field}")?;
    /// assert_eq!(template.uri(), "https://example.com/{resource}/{+id}{#field}");
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn uri(&self) -> &str {
        &self.0
    }

    /// Returns an iterator over the expressions contained within the URI template.
    ///
    /// # Examples
    /// ```rust
    /// use rfc6570_level_2::UriTemplate;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let template = UriTemplate::new("https://example.com/{resource}/{+id}{#field}")?;
    /// let expressions: Vec<&str> = template.expressions().collect();
    /// assert_eq!(expressions, vec!["{resource}", "{+id}", "{#field}"]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn expressions(&self) -> impl Iterator<Item = &str> {
        let var_starts = self.0.match_indices('{');
        let var_ends = self.0.match_indices('}');

        var_starts.zip(var_ends).map(move |((start, _), (end, _))| &self.0[start..=end])
    }

    /// Returns an iterator over the variable definitions contained within the URI template.
    ///
    /// # Examples
    /// ```rust
    /// use rfc6570_level_2::UriTemplate;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let template = UriTemplate::new("https://example.com/{resource}/{+id}{#field}")?;
    /// let variables: Vec<&str> = template.variables().collect();
    /// assert_eq!(variables, vec!["resource", "id", "field"]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn variables(&self) -> impl Iterator<Item = &str> {
        self.expressions().map(|e| e.var())
    }

    /// Returns a copy of the URI template string, with all expressions expanded based on the given variable map.
    ///
    /// # Examples
    /// ```rust
    /// use rfc6570_level_2::UriTemplate;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let template = UriTemplate::new("https://example.com/{resource}/{+id}{#field}")?;
    /// let var_map = [
    ///     ("resource", "user"),
    ///     ("id", "5"),
    ///     ("field", "email"),
    /// ].iter().cloned().collect();
    /// let uri = template.expand(&var_map);
    /// assert_eq!(uri, "https://example.com/user/5#email");
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn expand(&self, variables: &HashMap<&str, &str>) -> String {
        const LEVEL_1_ASCII_SET: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');
        const LEVEL_2_ASCII_SET: &AsciiSet = &LEVEL_1_ASCII_SET
            .remove(b':')
            .remove(b'/')
            .remove(b'?')
            .remove(b'#')
            .remove(b'[')
            .remove(b']')
            .remove(b'@')
            .remove(b'!')
            .remove(b'$')
            .remove(b'&')
            .remove(b'\'')
            .remove(b'(')
            .remove(b')')
            .remove(b'*')
            .remove(b'+')
            .remove(b',')
            .remove(b';')
            .remove(b'=');

        let mut uri = self.0.clone();

        for expression in self.expressions().unique() {
            uri = match expression.op() {
                "+" => uri.replace(
                    expression,
                    &utf8_percent_encode(variables.get(expression.var()).unwrap_or(&""), LEVEL_2_ASCII_SET).to_string(),
                ),
                "#" => uri.replace(
                    expression,
                    &match variables.get(expression.var()) {
                        Some(val) => format!("#{}", utf8_percent_encode(val, LEVEL_2_ASCII_SET)),
                        None => String::new(),
                    },
                ),
                _ => uri.replace(
                    expression,
                    &utf8_percent_encode(variables.get(expression.var()).unwrap_or(&""), LEVEL_1_ASCII_SET).to_string(),
                ),
            }
        }

        uri
    }
}

trait Expression {
    fn op(&self) -> &str;
    fn var(&self) -> &str;
}

impl Expression for str {
    fn op(&self) -> &str {
        &self[1..2]
    }

    fn var(&self) -> &str {
        self[1..self.len() - 1].trim_start_matches(|c| matches!(c, '+' | '#'))
    }
}

#[cfg(test)]
mod uri_template_expansion {
    use crate::UriTemplate;
    use anyhow::Context;

    include!(concat!(env!("OUT_DIR"), "/uri_template_expansion_tests.rs"));
}