Skip to main content

alint_rules/
io.rs

1//! Shared I/O helpers for content-reading rules.
2
3use std::io::Read as _;
4use std::path::Path;
5
6/// How much of a file to sample when classifying text vs. binary.
7pub const TEXT_INSPECT_LEN: usize = 8 * 1024;
8
9/// Read up to `TEXT_INSPECT_LEN` bytes from the start of a file. Returned
10/// `Ok(None)` means the file was empty; `Err` is propagated I/O error.
11pub fn read_prefix(path: &Path) -> std::io::Result<Vec<u8>> {
12    let mut file = std::fs::File::open(path)?;
13    let mut buf = vec![0u8; TEXT_INSPECT_LEN];
14    let n = file.read(&mut buf)?;
15    buf.truncate(n);
16    Ok(buf)
17}
18
19/// Classification of a file's contents. Computed lazily — callers check the
20/// subset they care about.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum Classification {
23    Text,
24    Binary,
25}
26
27pub fn classify_bytes(bytes: &[u8]) -> Classification {
28    match content_inspector::inspect(bytes) {
29        content_inspector::ContentType::BINARY => Classification::Binary,
30        _ => Classification::Text,
31    }
32}