noodles_sam/record/
cigar.rs

1use std::{fmt, io, iter};
2
3use crate::{alignment::record::cigar::Op, io::reader::record_buf::cigar::op};
4
5/// Raw SAM record CIGAR operations.
6#[derive(Eq, PartialEq)]
7pub struct Cigar<'a>(&'a [u8]);
8
9impl<'a> Cigar<'a> {
10    /// Creates SAM record CIGAR operations.
11    ///
12    /// # Examples
13    ///
14    /// ```
15    /// use noodles_sam::record::Cigar;
16    /// let cigar = Cigar::new(b"8M13N");
17    /// ```
18    pub fn new(src: &'a [u8]) -> Self {
19        Self(src)
20    }
21
22    /// Returns whether there are any CIGAR operations.
23    ///
24    /// # Examples
25    ///
26    /// ```
27    /// use noodles_sam::record::Cigar;
28    ///
29    /// let cigar = Cigar::new(b"");
30    /// assert!(cigar.is_empty());
31    ///
32    /// let cigar = Cigar::new(b"8M13N");
33    /// assert!(!cigar.is_empty());
34    /// ```
35    pub fn is_empty(&self) -> bool {
36        self.0.is_empty()
37    }
38
39    /// Returns an iterator over CIGAR operations.
40    ///
41    /// # Examples
42    ///
43    /// ```
44    /// use noodles_sam::{
45    ///     alignment::record::cigar::{op::Kind, Op},
46    ///     record::Cigar,
47    /// };
48    ///
49    /// let cigar = Cigar::new(b"");
50    /// assert!(cigar.iter().next().is_none());
51    ///
52    /// let cigar = Cigar::new(b"8M13N");
53    /// let mut iter = cigar.iter();
54    /// assert_eq!(iter.next().transpose()?, Some(Op::new(Kind::Match, 8)));
55    /// assert_eq!(iter.next().transpose()?, Some(Op::new(Kind::Skip, 13)));
56    /// assert!(iter.next().is_none());
57    /// # Ok::<_, Box<dyn std::error::Error>>(())
58    /// ```
59    pub fn iter(&self) -> impl Iterator<Item = Result<Op, op::ParseError>> + '_ {
60        use crate::io::reader::record_buf::cigar::op::parse_op;
61
62        let mut src = self.0;
63
64        iter::from_fn(move || {
65            if src.is_empty() {
66                None
67            } else {
68                Some(parse_op(&mut src))
69            }
70        })
71    }
72}
73
74impl fmt::Debug for Cigar<'_> {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.debug_list().entries(self.iter()).finish()
77    }
78}
79
80impl crate::alignment::record::Cigar for Cigar<'_> {
81    fn is_empty(&self) -> bool {
82        self.is_empty()
83    }
84
85    fn len(&self) -> usize {
86        self.as_ref()
87            .iter()
88            .filter(|&b| {
89                matches!(
90                    b,
91                    b'M' | b'I' | b'D' | b'N' | b'S' | b'H' | b'P' | b'=' | b'X'
92                )
93            })
94            .count()
95    }
96
97    fn iter(&self) -> Box<dyn Iterator<Item = io::Result<Op>> + '_> {
98        Box::new(self.iter().map(|result| {
99            result
100                .map(|op| Op::new(op.kind(), op.len()))
101                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
102        }))
103    }
104}
105
106impl AsRef<[u8]> for Cigar<'_> {
107    fn as_ref(&self) -> &[u8] {
108        self.0
109    }
110}
111
112impl<'a> TryFrom<Cigar<'a>> for crate::alignment::record_buf::Cigar {
113    type Error = io::Error;
114
115    fn try_from(Cigar(src): Cigar<'a>) -> Result<Self, Self::Error> {
116        use crate::io::reader::record_buf::parse_cigar;
117
118        let mut cigar = Self::default();
119
120        if !src.is_empty() {
121            parse_cigar(src, &mut cigar)
122                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
123        }
124
125        Ok(cigar)
126    }
127}