summaryrefslogtreecommitdiff
path: root/src/bindings.rs
diff options
context:
space:
mode:
authorDaniel Silverstone <dsilvers@digital-scurf.org>2020-12-15 12:30:26 +0000
committerDaniel Silverstone <dsilvers@digital-scurf.org>2020-12-18 17:50:19 +0000
commitd5d02d4296ed6cb07bb3e6f4438752c7b877bcaa (patch)
tree3e7c59d50de8e2b690a15dd820e28abc6719a495 /src/bindings.rs
parentc0462f2d49a42da8309087441926b5112605c3a0 (diff)
downloadsubplot-d5d02d4296ed6cb07bb3e6f4438752c7b877bcaa.tar.gz
bindings: Refactor kinds into a lazy static for reuse
We want to use kind patterns elsewhere so refactoring them into a lazy static seemed sensible. Signed-off-by: Daniel Silverstone <dsilvers@digital-scurf.org>
Diffstat (limited to 'src/bindings.rs')
-rw-r--r--src/bindings.rs37
1 files changed, 23 insertions, 14 deletions
diff --git a/src/bindings.rs b/src/bindings.rs
index 9b9a119..3d321ec 100644
--- a/src/bindings.rs
+++ b/src/bindings.rs
@@ -12,6 +12,7 @@ use std::fs::File;
use std::io::Read;
use std::path::Path;
+use lazy_static::lazy_static;
use regex::{escape, Regex, RegexBuilder};
/// A binding of a scenario step to its implementation.
@@ -679,20 +680,28 @@ mod test_bindings {
}
}
-fn regex_from_simple_pattern(pattern: &str, explicit_plain: bool) -> Result<String> {
- let kinds = vec![
- ("word", r"\S+"),
- ("text", r".*"),
- ("int", r"-?\d+"),
- ("uint", r"\d+"),
- ("number", r"-?\d+(\.\d+)?"),
- ];
- let mut regexes: HashMap<String, Regex> = HashMap::new();
- for (k, v) in kinds.iter() {
- let r = Regex::new(&v).unwrap();
- regexes.insert((*k).to_string(), r);
- }
+lazy_static! {
+ static ref KIND_PATTERNS: HashMap<&'static str, (&'static str, Regex)> = {
+ let mut map = HashMap::new();
+ for (tyname, pattern) in (&[
+ ("file", r"\S+"),
+ ("word", r"\S+"),
+ ("text", r".*"),
+ ("int", r"-?\d+"),
+ ("uint", r"\d+"),
+ ("number", r"-?\d+(\.\d+)?"),
+ ]).iter().copied() {
+ // This Unwrap is okay because we shouldn't have any bugs in the
+ // regular expressions here, and if we did, it'd be bad for everyone
+ // and caught in the test suite anyway.
+ let rx = Regex::new(&format!("^{}$", pattern)).unwrap();
+ map.insert(tyname, (pattern, rx));
+ }
+ map
+ };
+}
+fn regex_from_simple_pattern(pattern: &str, explicit_plain: bool) -> Result<String> {
let pat = Regex::new(r"\{[^\s\{\}]+\}").unwrap();
let mut r = String::new();
let mut end = 0;
@@ -717,7 +726,7 @@ fn regex_from_simple_pattern(pattern: &str, explicit_plain: bool) -> Result<Stri
(name, "word")
};
- if let Some(regex) = regexes.get(kind) {
+ if let Some((regex, _)) = KIND_PATTERNS.get(kind) {
r.push_str(&format!(r"(?P<{}>{})", name, regex));
} else {
return Err(SubplotError::UnknownSimplePatternKind(kind.to_string()));