rlua-searcher 0.1.0

Require Lua modules by name
Documentation
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::{BufReader, Cursor, Read};
use std::path::{Path, PathBuf};
use std::string::String;

pub type CatBox = Box<dyn Cat + Send + Sync>;
pub type CatMap<K> = HashMap<K, CatBox>;

pub trait Cat {
    fn cat(&self) -> io::Result<String>;
}

impl Cat for PathBuf {
    fn cat(&self) -> io::Result<String> {
        self.as_path().cat()
    }
}

impl Cat for &Path {
    fn cat(&self) -> io::Result<String> {
        let mut input = File::open(self)?;
        read_to_string(&mut input)
    }
}

impl Cat for Cow<'_, Path> {
    fn cat(&self) -> io::Result<String> {
        self.as_ref().cat()
    }
}

impl Cat for String {
    fn cat(&self) -> io::Result<String> {
        self.as_str().cat()
    }
}

impl Cat for &str {
    fn cat(&self) -> io::Result<String> {
        let mut input = Cursor::new(self);
        read_to_string(&mut input)
    }
}

impl Cat for Cow<'_, str> {
    fn cat(&self) -> io::Result<String> {
        self.as_ref().cat()
    }
}

fn read_to_string<R>(input: &mut R) -> io::Result<String>
where
    R: Read,
{
    let mut text = String::new();
    let mut reader = BufReader::new(input);
    reader.read_to_string(&mut text)?;
    Ok(text)
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;
    use std::env;
    use std::path::Path;

    use super::CatMap;

    #[test]
    fn it_works() {
        const ENV_VAR_OS_CARGO_MANIFEST_DIR: &str =
            "Unexpectedly could not read `CARGO_MANIFEST_DIR` environment variable";
        let mut cat_map: CatMap<Cow<'static, str>> = CatMap::new();
        cat_map.insert(Cow::from("Apr"), Box::new("Showers"));
        cat_map.insert(
            Cow::from("May"),
            Box::new(
                Path::new(&env::var_os("CARGO_MANIFEST_DIR").expect(ENV_VAR_OS_CARGO_MANIFEST_DIR))
                    .join("testdata")
                    .join("may.txt"),
            ),
        );
        assert_eq!(
            cat_map.get(&Cow::from("Apr")).unwrap().cat().unwrap(),
            String::from("Showers")
        );
        assert_eq!(
            cat_map
                .get(&Cow::from("May"))
                .unwrap()
                .cat()
                .unwrap()
                .trim_end(),
            String::from("Flowers")
        );
    }
}