1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
//! An alignment data record.

use std::num::ParseIntError;
use std::str::FromStr;

/// The delimiter for an alignment data record.
const ALIGNMENT_DATA_DELIMITER: char = '\t';

/// The number of expected fields in a non-terminating alignment data record.
pub const NUM_ALIGNMENT_DATA_FIELDS_NONTERMINATING: usize = 3;

/// The number of expected fields in a terminating alignment data record.
pub const NUM_ALIGNMENT_DATA_FIELDS_TERMINATING: usize = 1;

/// A type of alignment data record (whether the alignment data record is
/// terminating or not).
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AlignmentDataRecordType {
    /// Every line except the last line in an alignment section.
    NonTerminating,
    /// The last line in an alignment section.
    Terminating,
}

/// An error related to the parsing of an alignment data record.
#[derive(Debug)]
pub enum ParseError {
    /// An incorrect number of fields in the alignment data line.
    IncorrectNumberOfFields(usize),
    /// An invalid size.
    InvalidSize(ParseIntError),
    /// An invalid dt.
    InvalidDt(ParseIntError),
    /// An invalid dq.
    InvalidDq(ParseIntError),
    /// An invalid dt value for a non-terminating alignment data line.
    InvalidNonTerminatingDt,
    /// An invalid dq value for a non-terminating alignment data line.
    InvalidNonTerminatingDq,
    /// An invalid dt value for a terminating alignment data line.
    InvalidTerminatingDt,
    /// An invalid dq value for a terminating alignment data line.
    InvalidTerminatingDq,
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::IncorrectNumberOfFields(n) => write!(f,
                "invalid number of fields in alignment data: expected {} (non-terminating) or {} (terminating) fields, found {} fields",
                NUM_ALIGNMENT_DATA_FIELDS_NONTERMINATING, NUM_ALIGNMENT_DATA_FIELDS_TERMINATING, n
            ),
            ParseError::InvalidSize(err) => write!(f, "invalid size: {}", err),
            ParseError::InvalidDt(err) => write!(f, "invalid dt: {}", err),
            ParseError::InvalidDq(err) => write!(f, "invalid dq: {}", err),
            ParseError::InvalidNonTerminatingDt => write!(f, "expected value for dt in non-terminating alignment data line, found no value"),
            ParseError::InvalidNonTerminatingDq => write!(f, "expected value for dq in non-terminating alignment data line, found no value"),
            ParseError::InvalidTerminatingDt => write!(f, "expected no value for dt in terminating alignment data line, found value"),
            ParseError::InvalidTerminatingDq => write!(f, "expected no value for dq in terminating alignment data line, found value"),
        }
    }
}

impl std::error::Error for ParseError {}

/// An alignment data record within a chain file.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AlignmentDataRecord(usize, Option<usize>, Option<usize>, AlignmentDataRecordType);

impl AlignmentDataRecord {
    /// Creates a new `AlignmentDataRecord`.
    pub fn new(
        size: usize,
        dt: Option<usize>,
        dq: Option<usize>,
        record_type: AlignmentDataRecordType,
    ) -> Result<Self, ParseError> {
        match record_type {
            AlignmentDataRecordType::NonTerminating => {
                if dt.is_none() {
                    return Err(ParseError::InvalidNonTerminatingDt);
                }

                if dq.is_none() {
                    return Err(ParseError::InvalidNonTerminatingDq);
                }
            }
            AlignmentDataRecordType::Terminating => {
                if dt.is_some() {
                    return Err(ParseError::InvalidTerminatingDt);
                }

                if dq.is_some() {
                    return Err(ParseError::InvalidTerminatingDq);
                }
            }
        }

        Ok(AlignmentDataRecord(size, dt, dq, record_type))
    }

    /// Retuns the size of the ungapped alignment.
    ///
    /// # Examples
    ///
    /// ```
    /// use chainfile as chain;
    /// use chain::record::AlignmentDataRecord;
    ///
    /// let alignment: AlignmentDataRecord = "9\t1\t0".parse()?;
    /// assert_eq!(alignment.size(), 9);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn size(&self) -> usize {
        self.0
    }

    /// Returns the difference between this block and the next block for the
    /// reference/target sequence.
    ///
    /// # Examples
    ///
    /// ```
    /// use chainfile as chain;
    /// use chain::record::AlignmentDataRecord;
    ///
    /// let alignment: AlignmentDataRecord = "9\t1\t0".parse()?;
    /// assert_eq!(*alignment.dt(), Some(1));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn dt(&self) -> &Option<usize> {
        &self.1
    }

    /// Returns the difference between this block and the next block for the
    /// query sequence.
    ///
    /// # Examples
    ///
    /// ```
    /// use chainfile as chain;
    /// use chain::record::AlignmentDataRecord;
    ///
    /// let alignment: AlignmentDataRecord = "9\t1\t0".parse()?;
    /// assert_eq!(*alignment.dq(), Some(0));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn dq(&self) -> &Option<usize> {
        &self.2
    }

    /// Returns the record type.
    ///
    /// # Examples
    ///
    /// ```
    /// use chainfile as chain;
    /// use chain::record::AlignmentDataRecord;
    /// use chain::record::alignment_data::AlignmentDataRecordType;
    ///
    /// let alignment: AlignmentDataRecord = "9\t1\t0".parse()?;
    /// assert_eq!(*alignment.record_type(), AlignmentDataRecordType::NonTerminating);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn record_type(&self) -> &AlignmentDataRecordType {
        &self.3
    }
}

impl FromStr for AlignmentDataRecord {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts = s.split(ALIGNMENT_DATA_DELIMITER).collect::<Vec<_>>();
        let record_type = match parts.len() {
            NUM_ALIGNMENT_DATA_FIELDS_TERMINATING => AlignmentDataRecordType::Terminating,
            NUM_ALIGNMENT_DATA_FIELDS_NONTERMINATING => AlignmentDataRecordType::NonTerminating,
            _ => return Err(ParseError::IncorrectNumberOfFields(parts.len())),
        };

        let size = parts[0].parse().map_err(ParseError::InvalidSize)?;
        let (dt, dq) = match record_type {
            AlignmentDataRecordType::NonTerminating => {
                let dt = parts[1].parse().map_err(ParseError::InvalidDt)?;
                let dq = parts[2].parse().map_err(ParseError::InvalidDq)?;
                (Some(dt), Some(dq))
            }
            AlignmentDataRecordType::Terminating => (None, None),
        };

        AlignmentDataRecord::new(size, dt, dq, record_type)
    }
}

impl std::fmt::Display for AlignmentDataRecord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.size())?;

        match self.record_type() {
            AlignmentDataRecordType::NonTerminating => {
                write!(
                    f,
                    "{}{}{}{}",
                    ALIGNMENT_DATA_DELIMITER,
                    self.dt().expect("non-terminating record must have a dt"),
                    ALIGNMENT_DATA_DELIMITER,
                    self.dq().expect("non-terminating record must have a dq"),
                )?;
            }
            AlignmentDataRecordType::Terminating => {}
        }

        Ok(())
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;

    #[test]
    fn test_nonterminating_alignment_data() -> Result<(), Box<dyn std::error::Error>> {
        let record = "9\t1\t0".parse::<AlignmentDataRecord>()?;

        assert_eq!(record.size(), 9);
        assert_eq!(*record.dt(), Some(1));
        assert_eq!(*record.dq(), Some(0));
        assert_eq!(
            *record.record_type(),
            AlignmentDataRecordType::NonTerminating
        );

        Ok(())
    }

    #[test]
    fn test_terminating_alignment_data() -> Result<(), Box<dyn std::error::Error>> {
        let record = "9".parse::<AlignmentDataRecord>()?;

        assert_eq!(record.size(), 9);
        assert_eq!(*record.dt(), None);
        assert_eq!(*record.dq(), None);
        assert_eq!(*record.record_type(), AlignmentDataRecordType::Terminating);

        Ok(())
    }

    #[test]
    fn test_invalid_number_of_fields() -> Result<(), Box<dyn std::error::Error>> {
        let err = "9\t0".parse::<AlignmentDataRecord>().unwrap_err();

        assert_eq!(
            err.to_string(),
            "invalid number of fields in alignment data: expected 3 (non-terminating) \
             or 1 (terminating) fields, found 2 fields"
        );

        Ok(())
    }

    #[test]
    fn test_invalid_size() -> Result<(), Box<dyn std::error::Error>> {
        let err = "?\t0\t1".parse::<AlignmentDataRecord>().unwrap_err();

        assert_eq!(
            err.to_string(),
            "invalid size: invalid digit found in string"
        );

        Ok(())
    }

    #[test]
    fn test_invalid_dt() -> Result<(), Box<dyn std::error::Error>> {
        let err = "9\t?\t1".parse::<AlignmentDataRecord>().unwrap_err();

        assert_eq!(err.to_string(), "invalid dt: invalid digit found in string");

        Ok(())
    }

    #[test]
    fn test_invalid_dq() -> Result<(), Box<dyn std::error::Error>> {
        let err = "9\t0\t?".parse::<AlignmentDataRecord>().unwrap_err();

        assert_eq!(err.to_string(), "invalid dq: invalid digit found in string");

        Ok(())
    }

    #[test]
    fn test_invalid_nonterminating_dt() -> Result<(), Box<dyn std::error::Error>> {
        let err =
            AlignmentDataRecord::new(9, None, Some(1), AlignmentDataRecordType::NonTerminating)
                .unwrap_err();

        assert_eq!(
            err.to_string(),
            "expected value for dt in non-terminating alignment data line, found no value"
        );

        Ok(())
    }

    #[test]
    fn test_invalid_nonterminating_dq() -> Result<(), Box<dyn std::error::Error>> {
        let err =
            AlignmentDataRecord::new(9, Some(0), None, AlignmentDataRecordType::NonTerminating)
                .unwrap_err();

        assert_eq!(
            err.to_string(),
            "expected value for dq in non-terminating alignment data line, found no value"
        );

        Ok(())
    }

    #[test]
    fn test_invalid_terminating_dt() -> Result<(), Box<dyn std::error::Error>> {
        let err = AlignmentDataRecord::new(9, Some(0), None, AlignmentDataRecordType::Terminating)
            .unwrap_err();

        assert_eq!(
            err.to_string(),
            "expected no value for dt in terminating alignment data line, found value"
        );

        Ok(())
    }

    #[test]
    fn test_invalid_terminating_dq() -> Result<(), Box<dyn std::error::Error>> {
        let err = AlignmentDataRecord::new(9, None, Some(1), AlignmentDataRecordType::Terminating)
            .unwrap_err();

        assert_eq!(
            err.to_string(),
            "expected no value for dq in terminating alignment data line, found value"
        );

        Ok(())
    }

    #[test]
    fn test_nonterminating_alignment_data_display() -> Result<(), Box<dyn std::error::Error>> {
        let alignment =
            AlignmentDataRecord::new(9, Some(1), Some(0), AlignmentDataRecordType::NonTerminating)?;

        assert_eq!(alignment.to_string(), "9\t1\t0");

        Ok(())
    }

    #[test]
    fn test_terminating_alignment_data_display() -> Result<(), Box<dyn std::error::Error>> {
        let alignment =
            AlignmentDataRecord::new(9, None, None, AlignmentDataRecordType::Terminating)?;

        assert_eq!(alignment.to_string(), "9");

        Ok(())
    }
}