use crate::{AnalysisError, Config, InputFormat};
use sha2::{Digest, Sha256};
use std::ops::Range;
#[derive(Debug, Clone)]
pub enum FormatData {
Markdown,
Text,
}
#[derive(Debug, Clone)]
pub struct Prepared {
pub sha256: String,
pub original_len: usize,
pub bom_stripped: bool,
pub mixed_line_endings: bool,
pub text: String,
pub format: FormatData,
}
pub fn sha256_hex(bytes: &[u8]) -> String {
let mut h = Sha256::new();
h.update(bytes);
format!("{:x}", h.finalize())
}
pub fn prepare(input: &[u8], config: &Config) -> Result<Prepared, AnalysisError> {
if input.len() > config.limits.max_bytes {
return Err(AnalysisError::UnsupportedInput(format!(
"input is {} bytes, over the {} byte limit",
input.len(),
config.limits.max_bytes
)));
}
let sha256 = sha256_hex(input);
let (payload, bom_stripped) = match input.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
Some(rest) => (rest, true),
None => (input, false),
};
let text = std::str::from_utf8(payload)
.map_err(|e| {
AnalysisError::UnsupportedInput(format!("invalid utf-8 at byte {}", e.valid_up_to()))
})?
.to_string();
let has_crlf = text.contains("\r\n");
let bare_lf = text
.as_bytes()
.iter()
.enumerate()
.any(|(i, &b)| b == b'\n' && (i == 0 || text.as_bytes()[i - 1] != b'\r'));
let mixed_line_endings = has_crlf && bare_lf;
let format = match config.input_format {
InputFormat::Markdown => FormatData::Markdown,
InputFormat::Text => FormatData::Text,
};
Ok(Prepared {
sha256,
original_len: input.len(),
bom_stripped,
mixed_line_endings,
text,
format,
})
}
const SOURCE_GUARD_MIN_LINES: usize = 8;
const SOURCE_GUARD_MIN_PCT: usize = 35;
pub fn source_shape(text: &str, code_blocks: &[Range<usize>]) -> Option<(usize, usize)> {
let (code_lines, nonblank) = source_line_counts(text, code_blocks);
if code_lines >= SOURCE_GUARD_MIN_LINES && code_lines * 100 >= SOURCE_GUARD_MIN_PCT * nonblank {
Some((code_lines, nonblank))
} else {
None
}
}
pub fn source_line_counts(text: &str, code_blocks: &[Range<usize>]) -> (usize, usize) {
let mut code_lines = 0usize;
let mut nonblank = 0usize;
for lr in line_ranges(text) {
let t = text[lr.clone()].trim();
if t.is_empty() {
continue;
}
if code_blocks
.iter()
.any(|c| c.start < lr.end && lr.start < c.end)
{
continue;
}
nonblank += 1;
if code_shaped_line(t) {
code_lines += 1;
}
}
(code_lines, nonblank)
}
fn code_shaped_line(t: &str) -> bool {
if t.starts_with("#[") || t.starts_with("#![") || t.starts_with("//") {
return true;
}
if t.chars()
.all(|c| matches!(c, '{' | '}' | '(' | ')' | '[' | ']' | ';' | ','))
{
return true;
}
if !t.ends_with(['{', '}', ';', '(', ')', ',', ']']) {
return false;
}
const KEYWORDS: &[&str] = &[
"fn", "struct", "enum", "impl", "trait", "mod", "use", "const", "static", "type", "let",
"match", "extern",
];
const MODIFIERS: &[&str] = &["pub", "pub(crate)", "async", "unsafe"];
let mut words = t.split_whitespace();
let mut head = words.next().unwrap_or("");
if MODIFIERS.contains(&head) {
head = words.next().unwrap_or("");
}
let head_word: &str = head
.split(|c: char| !c.is_alphanumeric() && c != '_')
.next()
.unwrap_or("");
KEYWORDS.contains(&head_word)
|| t.contains("::")
|| t.contains("->")
|| t.contains("=>")
|| field_line(t)
}
fn field_line(t: &str) -> bool {
let Some(body) = t.strip_suffix(',') else {
return false;
};
let body = body
.strip_prefix("pub(crate) ")
.or_else(|| body.strip_prefix("pub "))
.unwrap_or(body)
.trim();
let Some((name, ty)) = body.split_once(':') else {
return false;
};
if name.ends_with(':') || ty.starts_with(':') {
return false;
}
let name = name.trim();
if name.is_empty()
|| !name.chars().all(|c| c.is_alphanumeric() || c == '_')
|| !name
.chars()
.next()
.is_some_and(|c| c.is_alphabetic() || c == '_')
{
return false;
}
let ty = ty.trim();
if ty.is_empty() {
return false;
}
let compact: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
let spaced_words = ty.split_whitespace().count();
let syntactic = compact.contains(['<', '&', ':']);
if spaced_words > 1 && !syntactic {
return false;
}
compact.chars().all(|c| {
c.is_alphanumeric()
|| matches!(
c,
'_' | ':' | '<' | '>' | '&' | '\'' | ',' | '[' | ']' | '(' | ')'
)
}) && compact
.chars()
.next()
.is_some_and(|c| c.is_alphabetic() || matches!(c, '_' | '&' | '(' | '['))
}
pub fn line_ranges(text: &str) -> Vec<Range<usize>> {
let mut out = Vec::new();
let mut start = 0usize;
let bytes = text.as_bytes();
for (i, &b) in bytes.iter().enumerate() {
if b == b'\n' {
let mut end = i;
if end > start && bytes[end - 1] == b'\r' {
end -= 1;
}
out.push(start..end);
start = i + 1;
}
}
if start <= text.len() {
out.push(start..text.len());
}
out
}