Skip to content

Implement VariableMap for Vec<AsRef<str>> #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,4 +370,19 @@ mod test {
r" ^^^", "\n",
));
}

#[test]
fn test_vec_map() {
let test_vec = vec!["xxxx", "foo", "bar"];
let test_slice = &test_vec[..];
let_assert!(Err(e) = substitute("${99}", &test_slice));
assert!(e.to_string() == "No such variable: $99");
assert_eq!(Ok("foo bar"), substitute("${*}", &test_slice).as_deref());
assert_eq!(Ok("xxxx"), substitute("${0}", &test_slice).as_deref());
assert_eq!(Ok("foo"), substitute("${1}", &test_slice).as_deref());
assert_eq!(Ok("bar"), substitute("${2}", &test_slice).as_deref());
assert_eq!(Ok("foo bar"), substitute("$*", &test_slice).as_deref());
assert_eq!(Ok("foo"), substitute("$1", &test_slice).as_deref());
assert_eq!(Ok("bar"), substitute("$2", &test_slice).as_deref());
}
}
25 changes: 25 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::hash::BuildHasher;

Expand Down Expand Up @@ -101,3 +102,27 @@ impl<'a, V: 'a, S: BuildHasher> VariableMap<'a> for HashMap<String, V, S> {
self.get(key)
}
}

impl<'a, T: AsRef<str>> VariableMap<'a> for &[T] {
type Value = Cow<'a, str>;

#[inline]
fn get(&'a self, key: &str) -> Option<Self::Value> {
if key == "*" {
let mut s = String::new();
for (n, val) in self.iter().skip(1).enumerate() {
if n > 0 {
s.push(' ');
}
s.push_str(val.as_ref());
}
Some(Cow::from(s))
} else {
str::parse::<usize>(key)
.ok()
.filter(|index| *index < self.len())
.map(|index| &self[index])
.map(|s| Cow::from(s.as_ref()))
}
}
}
21 changes: 18 additions & 3 deletions src/template/raw/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ impl Variable {
}
if source[finger + 1] == b'{' {
Self::parse_braced(source, finger)
} else if source[finger + 1] == b'*' {
let name_end = finger + 2;
let variable = Variable {
name: finger + 1..name_end,
default: None,
};
Ok((variable, name_end))
} else {
let name_end = match source[finger + 1..]
.iter()
Expand Down Expand Up @@ -101,7 +108,7 @@ impl Variable {
// Get the first sequence of alphanumeric characters and underscores for the variable name.
let name_end = match source[name_start..]
.iter()
.position(|&c| !c.is_ascii_alphanumeric() && c != b'_')
.position(|&c| !c.is_ascii_alphanumeric() && c != b'_' && c != b'*')
{
Some(0) => {
return Err(error::MissingVariableName {
Expand All @@ -119,6 +126,14 @@ impl Variable {
return Err(error::MissingClosingBrace { position: finger + 1 }.into());
}

if name_end - name_start > 1 && source[name_start..name_end].contains(&b'*') {
return Err(error::MissingVariableName {
position: finger,
len: name_end - name_start,
}
.into());
}

// If there is a closing brace after the name, there is no default value and we're done.
if source[name_end] == b'}' {
let variable = Variable {
Expand All @@ -140,8 +155,8 @@ impl Variable {
}

// If there is no matching un-escaped closing brace, it's missing.
let end = finger + find_closing_brace(&source[finger..])
.ok_or(error::MissingClosingBrace { position: finger + 1 })?;
let end = finger
+ find_closing_brace(&source[finger..]).ok_or(error::MissingClosingBrace { position: finger + 1 })?;

let variable = Variable {
name: name_start..name_end,
Expand Down
Loading