Skip to content

Commit

Permalink
Create a trait to avoid an unnecessary Result
Browse files Browse the repository at this point in the history
  • Loading branch information
triarius committed Jan 9, 2024
1 parent d874ddd commit 9e3b24b
Showing 1 changed file with 30 additions and 16 deletions.
46 changes: 30 additions & 16 deletions src/words.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,39 @@ lazy_static! {

pub(crate) fn list(path: Option<impl AsRef<Path>>) -> Result<Vec<String>> {
match path {
Some(path) => words_from_file(path),
None => words_from_fixture(),
Some(path) => WordsFromFile { path }.words(),
None => WordsFromFixture {}.words(),
}
}

fn words_from_fixture() -> Result<Vec<String>> {
let bytes = include_bytes!("fixtures/words");
Ok(String::from_utf8_lossy(bytes)
.split('\n')
.filter(|w| RE.is_match(w))
.map(|l| l.to_owned())
.collect())
trait Words {
fn words(&self) -> Result<Vec<String>>;
}

fn words_from_file(path: impl AsRef<Path>) -> Result<Vec<String>> {
let file = File::open(path)?;
Ok(BufReader::new(file)
.lines()
.map_while(|l| l.ok())
.filter(|w| RE.is_match(w))
.collect())
struct WordsFromFixture;

impl Words for WordsFromFixture {
fn words(&self) -> Result<Vec<String>> {
let bytes = include_bytes!("fixtures/words");
Ok(String::from_utf8_lossy(bytes)
.split('\n')
.filter(|w| RE.is_match(w))
.map(std::borrow::ToOwned::to_owned)
.collect())
}
}

struct WordsFromFile<P: AsRef<Path>> {
path: P,
}

impl<P: AsRef<Path>> Words for WordsFromFile<P> {
fn words(&self) -> Result<Vec<String>> {
let file = File::open(&self.path)?;
Ok(BufReader::new(file)
.lines()
.map_while(std::result::Result::ok)
.filter(|w| RE.is_match(w))
.collect())
}
}

0 comments on commit 9e3b24b

Please sign in to comment.