Skip to main content

alint_rules/
io.rs

1//! Shared I/O helpers for content-reading rules.
2
3use std::io::{Read as _, Seek, SeekFrom};
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    read_prefix_n(path, TEXT_INSPECT_LEN)
13}
14
15/// Read up to `n` bytes from the start of `path`. Used by rules that
16/// only need to inspect a leading window — `executable_has_shebang`
17/// (2 bytes for `#!`), `file_starts_with` (`pattern.len()` bytes).
18/// Reads less than `n` if the file is shorter; returns the actual byte
19/// count in the returned `Vec`'s length.
20pub fn read_prefix_n(path: &Path, n: usize) -> std::io::Result<Vec<u8>> {
21    let mut file = std::fs::File::open(path)?;
22    let mut buf = vec![0u8; n];
23    let read = file.read(&mut buf)?;
24    buf.truncate(read);
25    Ok(buf)
26}
27
28/// Read up to `n` bytes from the END of `path`. Used by rules that
29/// only need to inspect the tail — `file_ends_with` (`pattern.len()`
30/// bytes). Returns the actual byte count in the returned `Vec`'s
31/// length; fewer than `n` bytes if the file is shorter. Files smaller
32/// than `n` are read whole.
33pub fn read_suffix_n(path: &Path, n: usize) -> std::io::Result<Vec<u8>> {
34    let mut file = std::fs::File::open(path)?;
35    let len = file.seek(SeekFrom::End(0))?;
36    // 32-bit platforms: `usize::MAX < u64::MAX`, so a > 4 GiB
37    // file would truncate. `try_from` falls back to reading the
38    // requested `n` (which is bounded to a sane caller value)
39    // when the conversion fails.
40    let to_read = usize::try_from(len).unwrap_or(n).min(n);
41    file.seek(SeekFrom::Start(len - to_read as u64))?;
42    let mut buf = vec![0u8; to_read];
43    file.read_exact(&mut buf)?;
44    Ok(buf)
45}
46
47/// Classification of a file's contents. Computed lazily — callers check the
48/// subset they care about.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Classification {
51    Text,
52    Binary,
53}
54
55pub fn classify_bytes(bytes: &[u8]) -> Classification {
56    match content_inspector::inspect(bytes) {
57        content_inspector::ContentType::BINARY => Classification::Binary,
58        _ => Classification::Text,
59    }
60}