mod alignment;
mod entity_set;
mod fasta;
mod intervals;
mod knowledge_graph;
mod molecule_ranking;
mod molecule_set;
mod ranked_list;
mod reads;
mod report;
mod variants;
use std::fmt;
use std::io;
use std::path::Path;
use crate::hash::ContentHash;
use crate::types::DataKind;
pub use crate::note::Note;
pub const CANON_VERSION: u32 = 1;
const DOMAIN: &str = "ligase.canonical";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Form {
Canonical,
Raw,
}
impl Form {
#[must_use]
pub fn parse(name: &str) -> Option<Self> {
match name {
"canonical" => Some(Self::Canonical),
"raw" => Some(Self::Raw),
_ => None,
}
}
}
impl fmt::Display for Form {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Canonical => "canonical",
Self::Raw => "raw",
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Canonical {
pub hash: ContentHash,
pub form: Form,
pub notes: Vec<Note>,
}
pub fn hash(kind: DataKind, path: &Path, raw: ContentHash) -> io::Result<Canonical> {
let mut digest = Digest::new(kind, Form::Canonical);
match canonicalise(kind, path, &mut digest) {
Ok(()) => {
let notes = std::mem::take(&mut digest.notes);
Ok(Canonical {
hash: digest.finish(),
form: Form::Canonical,
notes,
})
}
Err(_) => {
let mut fallback = Digest::new(kind, Form::Raw);
fallback.field("bytes", raw.as_bytes());
Ok(Canonical {
hash: fallback.finish(),
form: Form::Raw,
notes: Vec::new(),
})
}
}
}
fn canonicalise(kind: DataKind, path: &Path, digest: &mut Digest) -> Result<(), String> {
match kind {
DataKind::Reads => reads::canonicalise(path, digest),
DataKind::Reference => fasta::canonicalise(path, digest),
DataKind::Alignment => alignment::canonicalise(path, digest),
DataKind::Variants => variants::canonicalise(path, digest),
DataKind::Intervals => intervals::canonicalise(path, digest),
DataKind::ResistanceReport => report::canonicalise(path, digest),
DataKind::EntitySet => entity_set::canonicalise(path, digest),
DataKind::RankedList => ranked_list::canonicalise(path, digest),
DataKind::KnowledgeGraph => knowledge_graph::canonicalise(path, digest),
DataKind::MoleculeSet => molecule_set::canonicalise(path, digest),
DataKind::MoleculeRanking => molecule_ranking::canonicalise(path, digest),
}
}
#[must_use]
pub const fn describe(kind: DataKind) -> Option<&'static str> {
Some(match kind {
DataKind::Reads => {
"reads sorted; the description after a read's name, and the `+` line's repeat of it, \
dropped"
}
DataKind::Reference => {
"contigs in order, sequences uppercased and unwrapped; descriptions dropped"
}
DataKind::Alignment => {
"records sorted; `@SQ` in order, `@RG` by sample; `@HD`, `@PG` and `@CO` dropped"
}
DataKind::Variants => {
"records sorted, QUAL to a tolerance, INFO and FILTER keys sorted; dates, sources, \
`##reference` paths and tool command lines dropped"
}
DataKind::Intervals => "intervals sorted; `track`, `browser` and comment lines dropped",
DataKind::ResistanceReport => "the header row kept, the rows below it sorted",
DataKind::EntitySet => {
"the header row kept, the rows below it compared as a set, so their order says \
nothing"
}
DataKind::RankedList => {
"the header row kept, the rows below it compared in order, because the order is \
the ranking"
}
DataKind::KnowledgeGraph => {
"nodes sorted by id and edges by source, target and type, with each node's and \
edge's own id and source lists sorted inside it; the keys a server writes about \
itself dropped from the top level"
}
DataKind::MoleculeSet => {
"the representation line and the header kept, the rows below them compared as a \
set, so their order says nothing"
}
DataKind::MoleculeRanking => {
"the representation line and the header kept, the rows below them compared in \
order, because the order is the ranking"
}
})
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tolerance(f64);
impl Tolerance {
#[must_use]
pub fn new(width: f64) -> Option<Self> {
(width.is_finite() && width > 0.0).then_some(Self(width))
}
#[must_use]
pub fn bucket(self, value: f64) -> Option<i64> {
let scaled = (value / self.0).round();
(scaled.is_finite() && scaled.abs() < 9.0e18).then_some(scaled as i64)
}
#[must_use]
pub const fn width(self) -> f64 {
self.0
}
}
#[must_use]
pub fn tolerance(kind: DataKind, field: &str) -> Option<Tolerance> {
match (kind, field) {
(DataKind::Variants, "QUAL") => Tolerance::new(0.1),
_ => None,
}
}
pub(crate) struct Digest {
hasher: blake3::Hasher,
records: Vec<[u8; 32]>,
notes: Vec<Note>,
}
impl Digest {
fn new(kind: DataKind, form: Form) -> Self {
let mut digest = Self {
hasher: blake3::Hasher::new(),
records: Vec::new(),
notes: Vec::new(),
};
digest.field("domain", DOMAIN.as_bytes());
digest.field("canon-version", &CANON_VERSION.to_le_bytes());
digest.field("kind", kind.name().as_bytes());
digest.field("form", form.to_string().as_bytes());
digest
}
pub(crate) fn field(&mut self, label: &str, value: &[u8]) {
write(&mut self.hasher, label.as_bytes());
write(&mut self.hasher, value);
}
pub(crate) fn text(&mut self, label: &str, value: &str) {
self.field(label, value.as_bytes());
}
pub(crate) fn note(&mut self, note: Note) {
if !self.notes.contains(¬e) {
self.notes.push(note);
}
}
pub(crate) fn record(&mut self, parts: &[&[u8]]) {
let mut hasher = blake3::Hasher::new();
for part in parts {
write(&mut hasher, part);
}
self.records.push(*hasher.finalize().as_bytes());
}
pub(crate) fn ordered_record(&mut self, parts: &[&[u8]]) {
let mut hasher = blake3::Hasher::new();
for part in parts {
write(&mut hasher, part);
}
self.field("ranked", hasher.finalize().as_bytes());
}
fn finish(mut self) -> ContentHash {
self.records.sort_unstable();
write(&mut self.hasher, b"records");
write(&mut self.hasher, &(self.records.len() as u64).to_le_bytes());
for record in &self.records {
self.hasher.update(record);
}
ContentHash::from_bytes(*self.hasher.finalize().as_bytes())
}
}
fn write(hasher: &mut blake3::Hasher, bytes: &[u8]) {
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn the_order_records_arrive_in_does_not_change_the_hash() {
let mut forwards = Digest::new(DataKind::Alignment, Form::Canonical);
forwards.record(&[b"one"]);
forwards.record(&[b"two"]);
let mut backwards = Digest::new(DataKind::Alignment, Form::Canonical);
backwards.record(&[b"two"]);
backwards.record(&[b"one"]);
assert_eq!(forwards.finish(), backwards.finish());
}
#[test]
fn the_order_fields_arrive_in_does_change_the_hash() {
let mut forwards = Digest::new(DataKind::Reference, Form::Canonical);
forwards.text("contig", "1");
forwards.text("contig", "2");
let mut backwards = Digest::new(DataKind::Reference, Form::Canonical);
backwards.text("contig", "2");
backwards.text("contig", "1");
assert_ne!(forwards.finish(), backwards.finish());
}
#[test]
fn the_order_ordered_records_arrive_in_does_change_the_hash() {
let mut forwards = Digest::new(DataKind::RankedList, Form::Canonical);
forwards.ordered_record(&[b"one"]);
forwards.ordered_record(&[b"two"]);
let mut backwards = Digest::new(DataKind::RankedList, Form::Canonical);
backwards.ordered_record(&[b"two"]);
backwards.ordered_record(&[b"one"]);
assert_ne!(forwards.finish(), backwards.finish());
}
#[test]
fn an_ordered_record_is_not_the_record_beside_it() {
let mut apart = Digest::new(DataKind::RankedList, Form::Canonical);
apart.ordered_record(&[b"one"]);
apart.ordered_record(&[b"two"]);
let mut together = Digest::new(DataKind::RankedList, Form::Canonical);
together.ordered_record(&[b"onetwo"]);
assert_ne!(apart.finish(), together.finish());
}
#[test]
fn a_repeated_record_is_not_the_same_as_one_record() {
let mut once = Digest::new(DataKind::Alignment, Form::Canonical);
once.record(&[b"one"]);
let mut twice = Digest::new(DataKind::Alignment, Form::Canonical);
twice.record(&[b"one"]);
twice.record(&[b"one"]);
assert_ne!(once.finish(), twice.finish());
}
#[test]
fn a_field_cannot_be_confused_with_the_one_beside_it() {
let mut left = Digest::new(DataKind::Reference, Form::Canonical);
left.text("x", "yz");
let mut right = Digest::new(DataKind::Reference, Form::Canonical);
right.text("xy", "z");
assert_ne!(left.finish(), right.finish());
}
#[test]
fn a_form_round_trips_through_its_name() {
for form in [Form::Canonical, Form::Raw] {
assert_eq!(Form::parse(&form.to_string()), Some(form));
}
assert_eq!(Form::parse("something-else"), None);
}
#[test]
fn a_tolerance_buckets_by_its_width() {
let whole = Tolerance::new(1.0).unwrap();
assert_eq!(whole.bucket(10.4), Some(10));
assert_eq!(whole.bucket(10.6), Some(11));
assert_eq!(whole.bucket(-10.4), Some(-10));
}
#[test]
fn a_value_too_large_to_bucket_is_left_alone() {
let tenth = Tolerance::new(0.1).unwrap();
assert_eq!(tenth.bucket(f64::MAX), None);
assert_eq!(tenth.bucket(f64::NAN), None);
}
}