From c6ec834990332d3d162ca84c8217f35d593fa5aa Mon Sep 17 00:00:00 2001 From: Mark Date: Fri, 18 May 2018 22:08:46 +0200 Subject: [PATCH] Make the regex cache work #56 --- src/mango/io/fortest/fromstr.rs | 4 ++-- src/mango/io/typ.rs | 4 +--- src/mango/io/util.rs | 11 ++++++++++- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/mango/io/fortest/fromstr.rs b/src/mango/io/fortest/fromstr.rs index 7c70c0d2..0afaf280 100644 --- a/src/mango/io/fortest/fromstr.rs +++ b/src/mango/io/fortest/fromstr.rs @@ -23,10 +23,10 @@ impl Reader for StringReader { false } - fn matches(&mut self, subpattern: String) -> Option { + fn matches(&mut self, subpattern: &str) -> Option { REXCACHE.with(|rl| { let mut rexlib = rl.borrow_mut(); - // let rex = rexlib.make_or_get(subpattern); + let rex = rexlib.make_or_get(subpattern); }); Option::None // TODO } diff --git a/src/mango/io/typ.rs b/src/mango/io/typ.rs index a50008ce..62667ad8 100644 --- a/src/mango/io/typ.rs +++ b/src/mango/io/typ.rs @@ -1,12 +1,10 @@ -use regex::Regex; - /// A reader represents a source 'file', which may be a file, webpage, string, ... pub trait Reader { /// Checks whether the `text` is found starting from the current position. fn equals(&mut self, text: &str) -> bool; /// Checks whether the code from the current position matches a regex pattern. - fn matches(&mut self, subpattern: String) -> Option; + fn matches(&mut self, subpattern: &str) -> Option; } pub trait Writer { diff --git a/src/mango/io/util.rs b/src/mango/io/util.rs index e847d602..66e1053d 100644 --- a/src/mango/io/util.rs +++ b/src/mango/io/util.rs @@ -1,3 +1,4 @@ +use regex::Error; use regex::Regex; use std::cell::RefCell; use std::collections::HashMap; @@ -8,11 +9,19 @@ pub struct RegexCache { impl RegexCache { // Not public to prevent having more than one instance. - pub fn new() -> Self { + fn new() -> Self { RegexCache { cache: HashMap::new(), } } + + pub fn make_or_get(&mut self, subpattern: &str) -> Result<&Regex, Error> { + if !self.cache.contains_key(subpattern) { + let regex = Regex::new(&format!("^ *{}", subpattern))?; + self.cache.insert(subpattern.to_owned(), regex); + } + Result::Ok(self.cache.get(subpattern).unwrap()) + } } thread_local! {