noodles_csi/binning_index/index/header/format/
coordinate_system.rs

1//! Tabix index format coordinate system.
2
3use std::{error, fmt};
4
5/// A tabix index format coordinate system.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum CoordinateSystem {
8    /// GFF coordinates: 1-based [start, end]
9    Gff,
10    /// BED coordinates: 0-based [start, end)
11    Bed,
12}
13
14/// An error returned when a raw coordinate system fails to convert.
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub struct TryFromIntError(u16);
17
18impl error::Error for TryFromIntError {}
19
20impl fmt::Display for TryFromIntError {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        write!(
23            f,
24            "invalid coordinate system: expected 0 or 1, got {}",
25            self.0
26        )
27    }
28}
29
30impl TryFrom<u16> for CoordinateSystem {
31    type Error = TryFromIntError;
32
33    fn try_from(n: u16) -> Result<Self, Self::Error> {
34        match n {
35            0 => Ok(Self::Gff),
36            1 => Ok(Self::Bed),
37            _ => Err(TryFromIntError(n)),
38        }
39    }
40}
41
42impl From<CoordinateSystem> for u16 {
43    fn from(coordinate_system: CoordinateSystem) -> Self {
44        coordinate_system as u16
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn test_try_from_u16_for_coordinate_system() {
54        assert_eq!(CoordinateSystem::try_from(0), Ok(CoordinateSystem::Gff));
55        assert_eq!(CoordinateSystem::try_from(1), Ok(CoordinateSystem::Bed));
56        assert_eq!(CoordinateSystem::try_from(2), Err(TryFromIntError(2)));
57    }
58
59    #[test]
60    fn test_from_coordinate_system_for_u16() {
61        assert_eq!(u16::from(CoordinateSystem::Gff), 0);
62        assert_eq!(u16::from(CoordinateSystem::Bed), 1);
63    }
64}