use std::io::BufRead;
use std::path::Path;
use super::Digest;
use crate::load::open;
pub(super) fn canonicalise(path: &Path, digest: &mut Digest) -> Result<(), String> {
let mut reader = open(path).map_err(|error| error.to_string())?;
let mut line = Vec::new();
let mut sequence: Option<blake3::Hasher> = None;
loop {
line.clear();
if reader
.read_until(b'\n', &mut line)
.map_err(|error| error.to_string())?
== 0
{
break;
}
let text = trim(&line);
if text.is_empty() {
continue;
}
if text[0] == b'>' {
if let Some(hasher) = sequence.take() {
digest.field("sequence", hasher.finalize().as_bytes());
}
let name = text[1..]
.split(|byte| byte.is_ascii_whitespace())
.next()
.unwrap_or_default();
if name.is_empty() {
return Err("a `>` line with no contig name".to_owned());
}
digest.field("contig", name);
sequence = Some(blake3::Hasher::new());
} else {
let Some(hasher) = sequence.as_mut() else {
return Err("sequence before the first `>` line".to_owned());
};
hasher.update(&text.to_ascii_uppercase());
}
}
match sequence {
Some(hasher) => digest.field("sequence", hasher.finalize().as_bytes()),
None => return Err("no `>` lines at all".to_owned()),
}
Ok(())
}
fn trim(line: &[u8]) -> &[u8] {
let mut end = line.len();
while end > 0 && line[end - 1].is_ascii_whitespace() {
end -= 1;
}
&line[..end]
}