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
//! SAM record template length.

use std::{
    error, fmt,
    num::{self, NonZeroUsize},
    ops::Not,
};

/// A SAM record template length.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum TemplateLength {
    /// The leftmost segment.
    Left(NonZeroUsize),
    /// The rightmost segment.
    Right(NonZeroUsize),
}

impl TemplateLength {
    /// Creates a template length for the leftmost segment.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::record::TemplateLength;
    ///
    /// let template_length = TemplateLength::left(0);
    /// assert!(template_length.is_none());
    ///
    /// let template_length = TemplateLength::left(8);
    /// assert!(matches!(template_length, Some(TemplateLength::Left(_))));
    /// assert_eq!(template_length.map(usize::from), Some(8));
    /// ```
    pub const fn left(len: usize) -> Option<Self> {
        if let Some(n) = NonZeroUsize::new(len) {
            Some(Self::Left(n))
        } else {
            None
        }
    }

    /// Creates a template length for the rightmost segment.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_sam::record::TemplateLength;
    ///
    /// let template_length = TemplateLength::right(0);
    /// assert!(template_length.is_none());
    ///
    /// let template_length = TemplateLength::right(8);
    /// assert!(matches!(template_length, Some(TemplateLength::Right(_))));
    /// assert_eq!(template_length.map(usize::from), Some(8));
    /// ```
    pub const fn right(len: usize) -> Option<Self> {
        if let Some(n) = NonZeroUsize::new(len) {
            Some(Self::Right(n))
        } else {
            None
        }
    }
}

impl fmt::Display for TemplateLength {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Left(len) => len.fmt(f),
            Self::Right(len) => write!(f, "-{}", len),
        }
    }
}

impl Not for TemplateLength {
    type Output = Self;

    fn not(self) -> Self::Output {
        match self {
            Self::Left(len) => Self::Right(len),
            Self::Right(len) => Self::Left(len),
        }
    }
}

/// An error returned when a raw SAM record template length fails to convert.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TryFromIntError {
    /// The input is invalid.
    Invalid(num::TryFromIntError),
}

impl error::Error for TryFromIntError {}

impl fmt::Display for TryFromIntError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Invalid(e) => write!(f, "invalid input: {}", e),
        }
    }
}

impl TryFrom<i32> for TemplateLength {
    type Error = TryFromIntError;

    fn try_from(n: i32) -> Result<Self, Self::Error> {
        usize::try_from(abs(n))
            .and_then(NonZeroUsize::try_from)
            .map(|len| {
                if n > 0 {
                    Self::Left(len)
                } else {
                    Self::Right(len)
                }
            })
            .map_err(TryFromIntError::Invalid)
    }
}

impl From<TemplateLength> for usize {
    fn from(template_length: TemplateLength) -> Self {
        match template_length {
            TemplateLength::Left(len) => usize::from(len),
            TemplateLength::Right(len) => usize::from(len),
        }
    }
}

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

    #[test]
    fn test_not() -> Result<(), TryFromIntError> {
        let left_template_length = TemplateLength::try_from(8)?;
        let right_template_length = TemplateLength::try_from(-8)?;

        assert_eq!(!left_template_length, right_template_length);
        assert_eq!(!right_template_length, left_template_length);

        Ok(())
    }

    #[test]
    fn test_fmt() -> Result<(), TryFromIntError> {
        let template_length = TemplateLength::try_from(8)?;
        assert_eq!(template_length.to_string(), "8");

        let template_length = TemplateLength::try_from(-8)?;
        assert_eq!(template_length.to_string(), "-8");

        Ok(())
    }

    #[test]
    fn test_try_from_i32_for_template_length() -> Result<(), num::TryFromIntError> {
        assert_eq!(
            TemplateLength::try_from(8),
            Ok(TemplateLength::Left(NonZeroUsize::try_from(8)?))
        );

        assert_eq!(
            TemplateLength::try_from(-8),
            Ok(TemplateLength::Right(NonZeroUsize::try_from(8)?))
        );

        assert_eq!(
            TemplateLength::try_from(i32::MAX),
            Ok(TemplateLength::Left(NonZeroUsize::try_from((1 << 31) - 1)?))
        );

        assert_eq!(
            TemplateLength::try_from(i32::MIN),
            Ok(TemplateLength::Right(NonZeroUsize::try_from(1 << 31)?))
        );

        assert!(matches!(
            TemplateLength::try_from(0),
            Err(TryFromIntError::Invalid(_))
        ));

        Ok(())
    }

    #[test]
    fn test_from_template_length_for_usize() -> Result<(), TryFromIntError> {
        assert_eq!(usize::from(TemplateLength::try_from(8)?), 8);
        assert_eq!(usize::from(TemplateLength::try_from(-8)?), 8);
        Ok(())
    }
}

// Returns the absolute value without overflow.
fn abs(n: i32) -> u32 {
    if n < 0 {
        0u32.wrapping_sub(n as u32)
    } else {
        n as u32
    }
}