use fancy_regex::Regex;
use once_cell::sync::Lazy;
use std::{fs, str};
use crate::Data;
use crate::Matches;
static DATA: Lazy<Vec<Data>> = Lazy::new(load_regex);
static REGEXES: Lazy<Vec<Regex>> = Lazy::new(build_regexes);
pub fn what_is(text: &str) -> Vec<Matches> {
if is_file(text) {
analyze_file(text)
} else {
identify_text(text)
}
}
pub fn identify_text(text: &str) -> Vec<Matches> {
let mut all_matches = Vec::<Matches>::new();
for (i, item) in (&*DATA).iter().enumerate() {
if (REGEXES[i]).is_match(text).unwrap() {
all_matches.push(Matches::new(text.to_string(), item.clone()));
}
}
all_matches
}
pub fn analyze_file(filename: &str) -> Vec<Matches> {
let mut all_matches = Vec::<Matches>::new();
let strings = read_file_to_strings(filename);
for text in &strings {
all_matches.extend(identify_text(text));
}
all_matches
}
fn is_file(name: &str) -> bool {
fs::metadata(name).is_ok()
}
fn read_file_to_strings(filename: &str) -> Vec<String> {
let file = fs::read(filename).expect("File not found");
let mut printable_text: Vec<Vec<u8>> = Vec::new();
let mut buffer: Vec<u8> = Vec::new();
let mut current_buffer = false;
for charecter in file {
if charecter.is_ascii_graphic() {
current_buffer = true;
buffer.push(charecter);
} else if current_buffer {
if buffer.len() >= 4 {
printable_text.push(buffer.clone());
}
buffer.clear();
current_buffer = false;
}
}
printable_text.push(buffer);
let mut result: Vec<String> = Vec::new();
for item in &printable_text {
result.push((str::from_utf8(item).unwrap()).to_string())
}
result
}
fn build_regexes() -> Vec<Regex> {
let mut regexes: Vec<Regex> = Vec::new();
for data in &*DATA {
regexes.push(Regex::new(&data.Regex).unwrap());
}
regexes
}
fn load_regex() -> Vec<Data> {
let data = include_str!("../data/regex.json");
serde_json::from_str(data).expect("Failed to parse JSON")
}