use std::path::Path;
#[cfg(test)]
mod tests;
pub const MAX_HITS: usize = 2000;
const MAX_FILE_BYTES: u64 = 1_000_000;
#[derive(Debug, PartialEq)]
pub struct Hit {
pub file: String,
pub x: usize,
pub y: usize,
pub text: String,
}
pub fn in_files(root: &Path, files: &[String], query: &str) -> Vec<Hit> {
let mut hits = Vec::new();
for file in files {
let path = root.join(file);
if std::fs::metadata(&path).is_ok_and(|data| data.len() > MAX_FILE_BYTES) {
continue;
}
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
for (y, line) in text.lines().enumerate() {
if let Some(x) = matches(line, query).first() {
hits.push(Hit {
file: file.clone(),
x: *x,
y,
text: line.trim().to_string(),
});
if hits.len() == MAX_HITS {
return hits;
}
}
}
}
hits
}
pub fn matches(line: &str, query: &str) -> Vec<usize> {
let exact = query.chars().any(char::is_uppercase);
let key = |c: char| {
if exact {
c
} else {
c.to_lowercase().next().unwrap_or(c)
}
};
let needle: Vec<char> = query.chars().map(key).collect();
let hay: Vec<char> = line.chars().map(key).collect();
let mut found = Vec::new();
let mut x = 0;
while !needle.is_empty() && x + needle.len() <= hay.len() {
if hay[x..x + needle.len()] == needle[..] {
found.push(x);
x += needle.len();
} else {
x += 1;
}
}
found
}
pub fn find(
lines: &[String],
query: &str,
from: (usize, usize),
forward: bool,
inclusive: bool,
) -> Option<(usize, usize)> {
let count = lines.len();
if count == 0 {
return None;
}
let (x, y) = from;
for step in 0..=count {
let line = if forward { (y + step) % count } else { (y + count - step) % count };
let found = matches(&lines[line], query);
let hit = match (forward, step) {
(true, 0) => found.into_iter().find(|start| *start > x || (inclusive && *start == x)),
(true, _) => found.into_iter().next(),
(false, 0) => found.into_iter().rfind(|start| *start < x),
(false, _) => found.into_iter().next_back(),
};
if let Some(start) = hit {
return Some((start, line));
}
}
None
}