aboutsummaryrefslogtreecommitdiff
path: root/src/text/mod.rs
blob: ac474bc6d8e177b75ad7af0a703c4649ac1ff7ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use lazy_static::lazy_static;
use std::ffi::OsStr;
use std::path::Path;
use std::collections::HashMap;

mod txt;
mod docx;
mod xlsx;
mod pptx;
mod odt;
mod odp;
mod pdf;

fn empty_extractor(_ : &str) -> String {
    "".to_string()
}

macro_rules! ext {
    ($f:ident) => {(stringify!($f), $f::get_text as ExtFn)}
}

type ExtFn = fn(&str) -> String;

lazy_static! {
    static ref EXT: HashMap<&'static str, ExtFn> = {
        HashMap::from([
            ext!(txt),
            ext!(docx),
            ext!(xlsx),
            ext!(pptx),
            ext!(odt),
            ext!(odp),
            ext!(pdf),
        ])
    };
}


/// Extract text from files if there is an extractor.
/// If there is an error like `permission denied` or there
/// is no extractor this function returns a empty string.
pub fn extract_text(path : &str) -> String {
    let p = Path::new(&path);
    let extenstion = p.extension().unwrap_or_else(|| OsStr::new("")).to_str().unwrap();
    EXT.get(extenstion).unwrap_or(&(empty_extractor as ExtFn))(path)
}

pub fn is_supported(path : &str) -> bool {
    let p = Path::new(&path);
    let extenstion = p.extension().unwrap_or_else(|| OsStr::new("")).to_str().unwrap();
    EXT.get(extenstion).is_some()
}