use super::*;
pub(super) const BARCODE_TAG: [u8; 2] = *b"bi";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BarcodeSpan {
Absent,
Spans {
front: Option<(usize, usize)>,
rear: Option<(usize, usize)>,
},
Malformed,
}
pub(super) fn barcode_position(value: f32) -> Option<i64> {
value.is_finite().then_some(value as i64)
}
pub(super) fn barcode_interval(
front_start: f32,
front_len: f32,
rear_end: f32,
rear_len: f32,
seq_len: usize,
) -> BarcodeSpan {
let (Some(front_start), Some(front_len), Some(rear_end), Some(rear_len)) = (
barcode_position(front_start),
barcode_position(front_len),
barcode_position(rear_end),
barcode_position(rear_len),
) else {
return BarcodeSpan::Malformed;
};
let len = i64::try_from(seq_len).unwrap_or(i64::MAX);
let front = (front_start >= 0).then(|| {
(
front_start,
front_start.saturating_add(front_len).saturating_add(1),
)
});
let rear = (rear_end >= 0).then(|| (rear_end.saturating_sub(rear_len), rear_end));
let start = front.map_or(0, |(_, end)| end);
let end = rear.map_or(len, |(start, _)| start);
let valid = |(s, e): (i64, i64)| s >= 0 && s < e && e <= len;
if start >= end || !front.is_none_or(valid) || !rear.is_none_or(valid) {
return BarcodeSpan::Malformed;
}
let cast = |(s, e): (i64, i64)| (s as usize, e as usize);
BarcodeSpan::Spans {
front: front.map(cast),
rear: rear.map(cast),
}
}
pub(super) fn barcode_call(rec: &RecordBuf) -> Option<&[u8]> {
match rec.data().get(&Tag::new(b'B', b'C'))? {
Value::String(value) => Some(value.as_ref()),
_ => None,
}
}
pub(super) fn verified_barcode_window(
rec: &RecordBuf,
seq: &[u8],
adapters: &crate::adapter::AdapterConfig,
front: Option<(usize, usize)>,
rear: Option<(usize, usize)>,
) -> (Option<(usize, usize)>, bool) {
let call = barcode_call(rec);
let verify = |span: Option<(usize, usize)>| {
span.map(|(s, e)| (s, e, adapters.barcode_span_verified(seq, s, e, call)))
};
let (front, rear) = (verify(front), verify(rear));
let unverified = front.is_some_and(|(_, _, ok)| !ok) || rear.is_some_and(|(_, _, ok)| !ok);
let start = front.filter(|f| f.2).map_or(0, |(_, e, _)| e);
let end = rear.filter(|r| r.2).map_or(seq.len(), |(s, _, _)| s);
(
(start < end && (start > 0 || end < seq.len())).then_some((start, end)),
unverified,
)
}
pub(crate) fn barcode_window(rec: &RecordBuf, seq_len: usize) -> BarcodeSpan {
let Some(value) = rec.data().get(&Tag::new(BARCODE_TAG[0], BARCODE_TAG[1])) else {
return BarcodeSpan::Absent;
};
let Value::Array(Array::Float(values)) = value else {
return BarcodeSpan::Malformed;
};
let &[
_score,
front_start,
front_len,
_front_score,
rear_end,
rear_len,
_rear_score,
] = values.as_slice()
else {
return BarcodeSpan::Malformed;
};
barcode_interval(front_start, front_len, rear_end, rear_len, seq_len)
}