use std::{fmt, io, iter};
use crate::{alignment::record::cigar::Op, io::reader::record_buf::cigar::op};
#[derive(Eq, PartialEq)]
pub struct Cigar<'a>(&'a [u8]);
impl<'a> Cigar<'a> {
pub fn new(src: &'a [u8]) -> Self {
Self(src)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = Result<Op, op::ParseError>> + '_ {
use crate::io::reader::record_buf::cigar::op::parse_op;
let mut src = self.0;
iter::from_fn(move || {
if src.is_empty() {
None
} else {
Some(parse_op(&mut src))
}
})
}
}
impl fmt::Debug for Cigar<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl crate::alignment::record::Cigar for Cigar<'_> {
fn is_empty(&self) -> bool {
self.is_empty()
}
fn len(&self) -> usize {
self.as_ref()
.iter()
.filter(|&b| {
matches!(
b,
b'M' | b'I' | b'D' | b'N' | b'S' | b'H' | b'P' | b'=' | b'X'
)
})
.count()
}
fn iter(&self) -> Box<dyn Iterator<Item = io::Result<Op>> + '_> {
Box::new(self.iter().map(|result| {
result
.map(|op| Op::new(op.kind(), op.len()))
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}))
}
}
impl AsRef<[u8]> for Cigar<'_> {
fn as_ref(&self) -> &[u8] {
self.0
}
}
impl<'a> TryFrom<Cigar<'a>> for crate::alignment::record_buf::Cigar {
type Error = io::Error;
fn try_from(cigar: Cigar<'a>) -> Result<Self, Self::Error> {
cigar
.iter()
.map(|result| result.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::alignment::record::Cigar as _;
#[test]
fn test_len() {
let cigar = Cigar::new(b"");
assert_eq!(cigar.len(), 0);
let cigar = Cigar::new(b"8M");
assert_eq!(cigar.len(), 1);
let cigar = Cigar::new(b"8M13N");
assert_eq!(cigar.len(), 2);
}
}