Skip to content

Commit

Permalink
Make the regex cache work #56
Browse files Browse the repository at this point in the history
  • Loading branch information
mverleg committed May 18, 2018
1 parent 90bfe6b commit c6ec834
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
4 changes: 2 additions & 2 deletions src/mango/io/fortest/fromstr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ impl Reader for StringReader {
false
}

fn matches(&mut self, subpattern: String) -> Option<String> {
fn matches(&mut self, subpattern: &str) -> Option<String> {
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
}
Expand Down
4 changes: 1 addition & 3 deletions src/mango/io/typ.rs
Original file line number Diff line number Diff line change
@@ -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<String>;
fn matches(&mut self, subpattern: &str) -> Option<String>;
}

pub trait Writer {
Expand Down
11 changes: 10 additions & 1 deletion src/mango/io/util.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use regex::Error;
use regex::Regex;
use std::cell::RefCell;
use std::collections::HashMap;
Expand All @@ -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! {
Expand Down

0 comments on commit c6ec834

Please sign in to comment.