Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

14.2 KB
Raw Blame
// ©AngelaMos | 2026
// naming.rs

pub const SCORE_VERY_HIGH: f64 = 1.0;
pub const SCORE_HIGH: f64 = 0.8;
pub const SCORE_MEDIUM_HIGH: f64 = 0.65;
pub const SCORE_MEDIUM: f64 = 0.5;
pub const SCORE_MEDIUM_LOW: f64 = 0.35;
pub const SCORE_NONE: f64 = 0.0;

pub const ENTRY_PATTERNS: &[(&[&str], Reliability)] = &[
    (&["from", "memory"], Reliability::VeryHigh),
    (&["decode"], Reliability::High),
    (&["parse"], Reliability::High),
    (&["uncompress"], Reliability::High),
    (&["decompress"], Reliability::High),
    (&["inflate"], Reliability::High),
    (&["demux"], Reliability::MediumHigh),
    (&["read"], Reliability::Medium),
    (&["load"], Reliability::Medium),
    (&["open"], Reliability::MediumLow),
];

pub const LIFECYCLE_TOKENS: &[&str] = &[
    "set",
    "init",
    "create",
    "new",
    "alloc",
    "setup",
    "configure",
    "free",
    "destroy",
    "close",
    "cleanup",
    "release",
    "finalize",
    "delete",
    "dealloc",
];

pub const DIAGNOSTIC_TOKENS: &[&str] = &[
    "error",
    "exception",
    "warn",
    "warning",
    "log",
    "debug",
    "print",
    "dump",
];

pub const SCAFFOLD_TOKENS: &[&str] = &["test", "example", "demo", "sample"];

// Checksum and hash primitives are vendored into almost every parser library and
// score well on every signal: byte buffer in, high complexity, no existing harness.
// They are not parser entry points. blake2sp/blake2s reached ranks 7 and 8 on
// libarchive; siphash24 reached 5 on libexpat; XXH64 reached 7 on lz4.
pub const PRIMITIVE_TOKENS: &[&str] = &[
    "blake", "blake2", "blake2b", "blake2s", "blake2sp", "blake2bp", "sha", "sha1", "sha256",
    "sha512", "md5", "crc", "crc32", "crc64", "adler", "adler32", "siphash", "sip", "xxh",
    "xxhash", "murmur", "hmac", "poly1305", "chacha", "aes",
];

pub const PRODUCER_TOKENS: &[&str] = &[
    "write",
    "encode",
    "encoder",
    "compress",
    "deflate",
    "save",
    "emit",
    "serialize",
    "marshal",
    "dest",
];

pub const READ_WORDS: [&str; 9] = [
    "read",
    "decode",
    "decoder",
    "decompress",
    "uncompress",
    "parse",
    "load",
    "inflate",
    "extract",
];

pub const WRITE_WORDS: [&str; 7] = [
    "write", "encode", "encoder", "compress", "save", "deflate", "flush",
];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Polarity {
    Read,
    Write,
}

// Read is tested first and wins outright, because the ambiguity runs one way only: every
// decode word contains an encode word as a suffix (`decompress`, `uncompress`) and no
// encode word contains a decode one. carries_word suffix-matches a lone lowercase
// identifier, so without this zlib's `uncompress` - the DECOMPRESSOR - reads as a writer.
#[must_use]
pub fn polarity_of(name: &str) -> Option<Polarity> {
    if crate::extract::carries_word(name, &READ_WORDS) {
        return Some(Polarity::Read);
    }
    crate::extract::carries_word(name, &WRITE_WORDS).then_some(Polarity::Write)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum Role {
    Entry,
    Lifecycle,
    Diagnostic,
    Scaffold,
    Producer,
    Primitive,
    Neutral,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum Reliability {
    VeryHigh,
    High,
    MediumHigh,
    Medium,
    MediumLow,
    None,
}

impl Reliability {
    #[must_use]
    pub fn score(self) -> f64 {
        match self {
            Reliability::VeryHigh => SCORE_VERY_HIGH,
            Reliability::High => SCORE_HIGH,
            Reliability::MediumHigh => SCORE_MEDIUM_HIGH,
            Reliability::Medium => SCORE_MEDIUM,
            Reliability::MediumLow => SCORE_MEDIUM_LOW,
            Reliability::None => SCORE_NONE,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct NameSignal {
    pub role: Role,
    pub reliability: Reliability,
    pub matched: Option<String>,
}

#[must_use]
pub fn tokenize(name: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    for segment in name.split(['_', '-', '.', ':']) {
        if !segment.is_empty() {
            split_camel(segment, &mut tokens);
        }
    }
    tokens
}

fn split_camel(segment: &str, out: &mut Vec<String>) {
    let chars: Vec<char> = segment.chars().collect();
    let mut start = 0;
    for index in 1..chars.len() {
        let previous = chars[index - 1];
        let current = chars[index];
        let following = chars.get(index + 1).copied();
        let entering_word =
            current.is_uppercase() && (previous.is_lowercase() || previous.is_numeric());
        let leaving_acronym = current.is_uppercase()
            && previous.is_uppercase()
            && following.is_some_and(char::is_lowercase);
        if entering_word || leaving_acronym {
            out.push(
                chars[start..index]
                    .iter()
                    .collect::<String>()
                    .to_lowercase(),
            );
            start = index;
        }
    }
    if start < chars.len() {
        out.push(chars[start..].iter().collect::<String>().to_lowercase());
    }
}

fn contains_sequence(tokens: &[String], pattern: &[&str]) -> bool {
    if pattern.is_empty() || pattern.len() > tokens.len() {
        return false;
    }
    tokens.windows(pattern.len()).any(|window| {
        window
            .iter()
            .zip(pattern)
            .all(|(token, expected)| token == expected)
    })
}

pub const MIN_SUFFIX_MATCH: usize = 5;

// `compress2`, `compress2_z`, `ZSTD_compress2` and `gzwrite` all escaped exact-token
// matching while plain `compress`/`deflate` were correctly excluded. Strip a trailing
// version digit, and let long producer verbs match as a suffix so `gzwrite` and
// `gzfwrite` are seen. Short tokens are exact-only: `dest` as a suffix would catch
// `modest`.
fn stem(token: &str) -> &str {
    token.trim_end_matches(|character: char| character.is_ascii_digit())
}

fn is_entry_verb(stemmed: &str) -> bool {
    ENTRY_PATTERNS
        .iter()
        .any(|(pattern, _)| pattern.len() == 1 && pattern[0] == stemmed)
}

fn matches_token(token: &str, candidate: &str, allow_suffix: bool) -> bool {
    let stemmed = stem(token);
    if stemmed == candidate {
        return true;
    }
    // `decompress` and `uncompress` both END WITH `compress`. A token that is itself a
    // decode verb is never a producer, whatever it happens to end with.
    allow_suffix
        && candidate.len() >= MIN_SUFFIX_MATCH
        && stemmed.len() > candidate.len()
        && stemmed.ends_with(candidate)
        && !is_entry_verb(stemmed)
}

fn first_match<'a>(tokens: &[String], candidates: &[&'a str]) -> Option<&'a str> {
    candidates.iter().copied().find(|candidate| {
        tokens
            .iter()
            .any(|token| matches_token(token, candidate, false))
    })
}

fn first_producer<'a>(tokens: &[String], candidates: &[&'a str]) -> Option<&'a str> {
    candidates.iter().copied().find(|candidate| {
        tokens
            .iter()
            .any(|token| matches_token(token, candidate, true))
    })
}

#[must_use]
pub fn classify(name: &str) -> NameSignal {
    let tokens = tokenize(name);

    if let Some(matched) = first_match(&tokens, SCAFFOLD_TOKENS) {
        return NameSignal {
            role: Role::Scaffold,
            reliability: Reliability::None,
            matched: Some(matched.to_owned()),
        };
    }
    if let Some(matched) = first_match(&tokens, PRIMITIVE_TOKENS) {
        return NameSignal {
            role: Role::Primitive,
            reliability: Reliability::None,
            matched: Some(matched.to_owned()),
        };
    }
    if let Some(matched) = first_producer(&tokens, PRODUCER_TOKENS) {
        return NameSignal {
            role: Role::Producer,
            reliability: Reliability::None,
            matched: Some(matched.to_owned()),
        };
    }
    if let Some(matched) = first_match(&tokens, DIAGNOSTIC_TOKENS) {
        return NameSignal {
            role: Role::Diagnostic,
            reliability: Reliability::None,
            matched: Some(matched.to_owned()),
        };
    }
    if let Some(matched) = first_match(&tokens, LIFECYCLE_TOKENS) {
        return NameSignal {
            role: Role::Lifecycle,
            reliability: Reliability::None,
            matched: Some(matched.to_owned()),
        };
    }

    let strongest = ENTRY_PATTERNS
        .iter()
        .filter(|(pattern, _)| contains_sequence(&tokens, pattern))
        .max_by(|left, right| {
            left.1
                .score()
                .partial_cmp(&right.1.score())
                .unwrap_or(std::cmp::Ordering::Equal)
        });

    match strongest {
        Some((pattern, reliability)) => NameSignal {
            role: Role::Entry,
            reliability: *reliability,
            matched: Some(pattern.join("_")),
        },
        None => NameSignal {
            role: Role::Neutral,
            reliability: Reliability::None,
            matched: None,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_from_memory_suffix_is_the_strongest_entry_name() {
        let signal = classify("png_image_begin_read_from_memory");
        assert_eq!(signal.role, Role::Entry);
        assert_eq!(signal.reliability, Reliability::VeryHigh);
    }

    #[test]
    fn a_constructor_outranks_the_generic_verb_it_contains() {
        let signal = classify("png_create_read_struct");
        assert_eq!(signal.role, Role::Lifecycle);
    }

    #[test]
    fn a_destructor_outranks_the_generic_verb_it_contains() {
        let signal = classify("png_destroy_read_struct");
        assert_eq!(signal.role, Role::Lifecycle);
    }

    #[test]
    fn test_scaffolding_outranks_a_decode_verb() {
        let signal = classify("test_decode_frame");
        assert_eq!(signal.role, Role::Scaffold);
    }

    #[test]
    fn encoder_side_functions_are_excluded_despite_mirroring_reader_names() {
        for name in [
            "png_write_iCCP",
            "png_write_png",
            "png_compress_IDAT",
            "TIFFWriteScanline",
            "archive_write_data",
            "opj_encode",
            "jpeg_mem_dest",
        ] {
            assert_eq!(classify(name).role, Role::Producer, "{name}");
        }
    }

    #[test]
    fn decompression_is_not_mistaken_for_compression() {
        for name in [
            "BZ2_bzDecompress",
            "opj_decompress",
            "zlib_uncompress",
            "ZSTD_decompressStream",
            "LZ4F_decompress",
            "tj3DecompressHeader",
        ] {
            assert_eq!(classify(name).role, Role::Entry, "{name}");
        }
    }

    #[test]
    fn a_version_digit_does_not_smuggle_a_producer_past_the_filter() {
        for name in ["compress2", "ZSTD_compress2", "zlib_compress2_z"] {
            assert_eq!(classify(name).role, Role::Producer, "{name}");
        }
    }

    #[test]
    fn a_prefixed_write_verb_is_still_a_producer() {
        for name in ["gzwrite", "gzfwrite", "mylib_overwrite"] {
            assert_eq!(classify(name).role, Role::Producer, "{name}");
        }
    }

    #[test]
    fn vendored_hash_primitives_are_not_parser_entry_points() {
        for name in [
            "blake2sp_update",
            "blake2s",
            "siphash24",
            "XXH64",
            "crc32_z",
            "sha256_update",
        ] {
            assert_eq!(classify(name).role, Role::Primitive, "{name}");
        }
    }

    #[test]
    fn no_ground_truth_entry_point_is_classified_as_a_producer() {
        for name in [
            "png_read_info",
            "png_image_begin_read_from_memory",
            "png_read_png",
            "png_process_data",
            "TIFFClientOpen",
            "TIFFOpen",
            "TIFFReadDirectory",
            "opj_read_header",
            "opj_decode",
            "archive_read_next_header",
            "archive_read_open_memory",
            "archive_read_data",
            "tj3DecompressHeader",
            "tj3Transform",
            "jpeg_read_header",
        ] {
            let role = classify(name).role;
            assert_ne!(role, Role::Producer, "{name} is a real entry point");
            assert_ne!(role, Role::Scaffold, "{name} is a real entry point");
        }
    }

    #[test]
    fn diagnostic_functions_are_never_entry_points() {
        assert_eq!(classify("png_error").role, Role::Diagnostic);
        assert_eq!(classify("TIFFWarningExt").role, Role::Diagnostic);
    }

    #[test]
    fn camel_case_names_are_tokenized_before_matching() {
        let signal = classify("TIFFReadDirectory");
        assert_eq!(signal.role, Role::Entry);
        assert_eq!(signal.reliability, Reliability::Medium);
    }

    #[test]
    fn tokens_match_whole_words_so_resample_is_not_test_scaffolding() {
        let signal = classify("resample_row");
        assert_eq!(signal.role, Role::Neutral);
    }

    #[test]
    fn a_name_with_no_known_token_is_neutral_not_rejected() {
        let signal = classify("png_get_IHDR");
        assert_eq!(signal.role, Role::Neutral);
        assert_eq!(signal.reliability, Reliability::None);
    }

    #[test]
    fn the_exit_gate_exemplar_is_only_a_weak_name_signal() {
        let signal = classify("TIFFClientOpen");
        assert_eq!(signal.role, Role::Entry);
        assert_eq!(signal.reliability, Reliability::MediumLow);
        assert!(
            signal.reliability.score() < Reliability::High.score(),
            "naming must not be able to carry TIFFClientOpen to the top on its own"
        );
    }

    #[test]
    fn decompression_verbs_are_high_reliability_entry_names() {
        for name in ["BZ2_bzDecompress", "lz4_decompress_safe", "zlib_inflate"] {
            let signal = classify(name);
            assert_eq!(signal.role, Role::Entry, "{name}");
            assert_eq!(signal.reliability, Reliability::High, "{name}");
        }
    }

    #[test]
    fn reliability_scores_are_ordered_by_rank() {
        let ranked = [
            Reliability::VeryHigh,
            Reliability::High,
            Reliability::MediumHigh,
            Reliability::Medium,
            Reliability::MediumLow,
            Reliability::None,
        ];
        for pair in ranked.windows(2) {
            assert!(
                pair[0].score() > pair[1].score(),
                "{:?} must outscore {:?}",
                pair[0],
                pair[1]
            );
        }
    }
}