path2regex/
try_into_with.rs1use anyhow::Result;
4
5use crate::{
6 parser::parse_str_with_options,
7 re::{regex_to_path_regex, string_to_path_regex},
8 ParserOptions, PathRegex, PathRegexOptions, Token,
9};
10
11pub trait TryIntoWith<T, O>: Clone {
13 fn try_into_with(self, options: &O) -> Result<T>;
15}
16
17impl TryIntoWith<Vec<Token>, ParserOptions> for Vec<Token> {
18 fn try_into_with(self, _: &ParserOptions) -> Result<Vec<Token>> {
19 Ok(self)
20 }
21}
22
23impl TryIntoWith<Vec<Token>, ParserOptions> for String {
24 fn try_into_with(self, options: &ParserOptions) -> Result<Vec<Token>> {
25 (&*self).try_into_with(options)
26 }
27}
28
29impl TryIntoWith<Vec<Token>, ParserOptions> for &str {
30 fn try_into_with(self, options: &ParserOptions) -> Result<Vec<Token>> {
31 parse_str_with_options(self, options)
32 }
33}
34
35impl TryIntoWith<PathRegex, PathRegexOptions> for regex::Regex {
36 fn try_into_with(self, _: &PathRegexOptions) -> Result<PathRegex> {
37 let mut keys = vec![];
38 let re = regex_to_path_regex(self, &mut keys)?;
39 Ok(PathRegex { re, keys })
40 }
41}
42
43impl TryIntoWith<PathRegex, PathRegexOptions> for String {
44 fn try_into_with(self, options: &PathRegexOptions) -> Result<PathRegex> {
45 (&*self).try_into_with(options)
46 }
47}
48
49impl<'a> TryIntoWith<PathRegex, PathRegexOptions> for &'a str {
50 fn try_into_with(self, options: &PathRegexOptions) -> Result<PathRegex> {
51 string_to_path_regex(self, options)
52 }
53}
54
55impl<T> TryIntoWith<PathRegex, PathRegexOptions> for Vec<T>
56where
57 T: TryIntoWith<PathRegex, PathRegexOptions>,
58{
59 fn try_into_with(self, options: &PathRegexOptions) -> Result<PathRegex> {
60 let mut keys = vec![];
61 let mut parts = vec![];
62 for source in self.into_iter() {
63 let mut re = source.try_into_with(options)?;
64 keys.append(&mut re.keys);
65 parts.push(re.to_string());
66 }
67 let re = regex::Regex::new(&format!("(?:{})", parts.join("|")))?;
68 Ok(PathRegex { re, keys })
69 }
70}