nameme_core 0.2.3

Library to find the actual type of files based on their magic number.
mod data;
pub mod sig;
pub mod stats;

pub use data::head::HEADERS;
pub use data::head::MAX_HEADER_BYTES;
//pub use data::prex::PREFIXES;
pub use data::sigs::SIGNATURES;

use crate::sig::Signature;
use log::debug;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::time::Instant;

/// Find the signature matching the header given as argument.
pub fn find_sigs<'a>(bytes: Vec<u8>) -> Option<Signature<'a>> {
    debug!("searching signature for {:?}", bytes);

    let mut retval = None;
    let now = Instant::now();

    for i in 1..bytes.len() {
        let sub = bytes[0..bytes.len() - i].to_vec().clone();
        let mut s = DefaultHasher::new();
        sub.hash(&mut s);
        let hash = s.finish();
        debug!("searching signature for sub {:?} with hash {hash}", sub);

        HEADERS.with(|headers| {
            if headers.contains_key(&hash) {
                let sig = headers.get(&hash).unwrap();
                SIGNATURES.with(|signatures| {
                    retval = Some(signatures[*sig].clone());
                });
            }
        });
        if let Some(_) = retval {
            break;
        }
    }
    stats::add_find_header_time(now.elapsed());
    retval
}