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
//! VCF record genotype format.

use std::{convert::TryFrom, error, fmt, ops::Deref, str::FromStr};

use indexmap::IndexSet;

use super::genotype::field::{key, Key};

const DELIMITER: char = ':';

/// A VCF record genotype format (`FORMAT`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Format(IndexSet<Key>);

impl Deref for Format {
    type Target = IndexSet<Key>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl fmt::Display for Format {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, key) in self.iter().enumerate() {
            if i > 0 {
                write!(f, "{}", DELIMITER)?;
            }

            f.write_str(key.as_ref())?;
        }

        Ok(())
    }
}

/// An error returned when a raw VCF record format fails to parse.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseError {
    /// The input is empty.
    Empty,
    /// The key is invalid.
    InvalidKey(key::ParseError),
    /// The format is invalid.
    InvalidFormat(TryFromKeyVectorError),
}

impl error::Error for ParseError {}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str("empty input"),
            Self::InvalidKey(e) => write!(f, "{}", e),
            Self::InvalidFormat(e) => write!(f, "{}", e),
        }
    }
}

impl FromStr for Format {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            Err(ParseError::Empty)
        } else {
            s.split(DELIMITER)
                .map(|s| s.parse())
                .collect::<Result<Vec<_>, _>>()
                .map_err(ParseError::InvalidKey)
                .and_then(|keys| Self::try_from(keys).map_err(ParseError::InvalidFormat))
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
/// An error returned when a vector of keys fails to convert to a format.
pub enum TryFromKeyVectorError {
    /// The input is empty.
    Empty,
    /// The genotype key (`GT`) position is invalid.
    ///
    /// The genotype key must be first if present. See § 1.6.2 Genotype fields (2020-06-25).
    InvalidGenotypeKeyPosition,
    /// A key is duplicated.
    ///
    /// § 1.6.2 Genotype fields (2021-01-13): "...duplicate keys are not allowed".
    DuplicateKey(Key),
}

impl error::Error for TryFromKeyVectorError {}

impl fmt::Display for TryFromKeyVectorError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str("empty input"),
            Self::InvalidGenotypeKeyPosition => f.write_str("invalid genotype key position"),
            Self::DuplicateKey(key) => write!(f, "duplicate key: {}", key),
        }
    }
}

impl TryFrom<Vec<Key>> for Format {
    type Error = TryFromKeyVectorError;

    fn try_from(keys: Vec<Key>) -> Result<Self, Self::Error> {
        if keys.is_empty() {
            return Err(TryFromKeyVectorError::Empty);
        } else if let Some(i) = keys.iter().position(|k| k == &Key::Genotype) {
            if i != 0 {
                return Err(TryFromKeyVectorError::InvalidGenotypeKeyPosition);
            }
        }

        let mut set = IndexSet::new();

        for key in &keys {
            if !set.insert(key.clone()) {
                return Err(TryFromKeyVectorError::DuplicateKey(key.clone()));
            }
        }

        Ok(Self(set))
    }
}

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

    #[test]
    fn test_fmt() {
        let format = Format(vec![Key::Genotype].into_iter().collect());
        assert_eq!(format.to_string(), "GT");

        let format = Format(
            vec![
                Key::Genotype,
                Key::ConditionalGenotypeQuality,
                Key::ReadDepth,
                Key::HaplotypeQuality,
            ]
            .into_iter()
            .collect(),
        );
        assert_eq!(format.to_string(), "GT:GQ:DP:HQ");
    }

    #[test]
    fn test_from_str() {
        assert_eq!(
            "GT".parse(),
            Ok(Format(vec![Key::Genotype].into_iter().collect()))
        );
        assert_eq!(
            "GT:GQ".parse(),
            Ok(Format(
                vec![Key::Genotype, Key::ConditionalGenotypeQuality]
                    .into_iter()
                    .collect()
            ))
        );

        assert_eq!("".parse::<Format>(), Err(ParseError::Empty));
        assert!(matches!(
            "GQ:GT".parse::<Format>(),
            Err(ParseError::InvalidFormat(_))
        ));
    }

    #[test]
    fn test_try_from_vec_key_for_format() {
        assert_eq!(
            Format::try_from(vec![Key::Genotype]),
            Ok(Format(vec![Key::Genotype].into_iter().collect()))
        );

        assert_eq!(
            Format::try_from(vec![Key::Genotype, Key::ConditionalGenotypeQuality]),
            Ok(Format(
                vec![Key::Genotype, Key::ConditionalGenotypeQuality]
                    .into_iter()
                    .collect()
            ))
        );

        assert_eq!(
            Format::try_from(vec![Key::ConditionalGenotypeQuality]),
            Ok(Format(
                vec![Key::ConditionalGenotypeQuality].into_iter().collect()
            ))
        );

        assert_eq!(
            Format::try_from(Vec::new()),
            Err(TryFromKeyVectorError::Empty)
        );

        assert_eq!(
            Format::try_from(vec![Key::ConditionalGenotypeQuality, Key::Genotype]),
            Err(TryFromKeyVectorError::InvalidGenotypeKeyPosition)
        );

        assert_eq!(
            Format::try_from(vec![Key::Genotype, Key::Genotype]),
            Err(TryFromKeyVectorError::DuplicateKey(Key::Genotype))
        );
    }
}