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

pub mod field;

pub use self::field::Field;

use std::{error, fmt, ops::Deref};

use indexmap::IndexMap;

use super::Keys;
use crate::record::MISSING_FIELD;

const DELIMITER: char = ':';

/// A VCF record genotype.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Genotype(IndexMap<field::Key, Field>);

/// An error returned when a raw VCF genotype fails to parse.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseError {
    /// The input is empty.
    Empty,
    /// The input is invalid.
    Invalid(TryFromFieldsError),
    /// A field is invalid.
    InvalidField(field::ParseError),
}

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::Invalid(e) => write!(f, "invalid input: {}", e),
            Self::InvalidField(e) => write!(f, "invalid field: {}", e),
        }
    }
}

/// An error returned when a genotype (`GT`) field value fails to parse.
#[derive(Clone, Debug, PartialEq)]
pub enum GenotypeError {
    /// The genotype field value is invalid.
    InvalidValue(field::value::genotype::ParseError),
    /// The genotype field value type is invalid.
    ///
    /// The `GT` field value must be a `String`.
    InvalidValueType(field::Value),
}

impl error::Error for GenotypeError {}

impl fmt::Display for GenotypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidValue(e) => write!(f, "invalid value: {}", e),
            Self::InvalidValueType(value) => write!(f, "invalid String, got {:?}", value),
        }
    }
}

impl Genotype {
    /// Parses a raw genotype for the given genotype format.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::record::genotypes::{genotype::{field::{Key, Value}, Field}, Genotype};
    ///
    /// let keys = "GT:GQ".parse()?;
    ///
    /// assert_eq!(
    ///     Genotype::from_str_format("0|0:13", &keys),
    ///     Ok(Genotype::try_from(vec![
    ///         Field::new(Key::Genotype, Some(Value::String(String::from("0|0")))),
    ///         Field::new(Key::ConditionalGenotypeQuality, Some(Value::Integer(13))),
    ///     ])?)
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_str_format(s: &str, keys: &Keys) -> Result<Self, ParseError> {
        match s {
            "" => Err(ParseError::Empty),
            MISSING_FIELD => Ok(Self::default()),
            _ => {
                let fields = s
                    .split(DELIMITER)
                    .zip(keys.iter())
                    .map(|(t, k)| Field::from_str_key(t, k))
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(ParseError::InvalidField)?;

                Self::try_from(fields).map_err(ParseError::Invalid)
            }
        }
    }

    /// Returns the VCF record genotypes genotype value.
    ///
    /// This is a convenience method to return a parsed version of the genotype (`GT`) field value.
    /// Use `[Self::get]` with `[field::Key::Genotype]` to get the raw value.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::record::{genotypes::{genotype::{field::{Key, Value}, Field}, Genotype}};
    /// let genotype = Genotype::from_str_format("0|0:13", &"GT:GQ".parse()?)?;
    /// assert_eq!(genotype.genotype(), Some(Ok("0|0".parse()?)));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn genotype(&self) -> Option<Result<field::value::Genotype, GenotypeError>> {
        self.get(&field::Key::Genotype)
            .and_then(|f| f.value())
            .map(|value| match value {
                field::Value::String(s) => s.parse().map_err(GenotypeError::InvalidValue),
                _ => Err(GenotypeError::InvalidValueType(value.clone())),
            })
    }
}

impl Deref for Genotype {
    type Target = IndexMap<field::Key, Field>;

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

impl fmt::Display for Genotype {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_empty() {
            f.write_str(MISSING_FIELD)
        } else {
            for (i, field) in self.values().enumerate() {
                if i > 0 {
                    write!(f, "{}", DELIMITER)?;
                }

                write!(f, "{}", field)?;
            }

            Ok(())
        }
    }
}

/// An error returned when VCF genotype fields fail to convert.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TryFromFieldsError {
    /// The genotype field (`GT`) position is invalid.
    ///
    /// The genotype field must be first if present. See § 1.6.2 Genotype fields (2020-06-25).
    InvalidGenotypeFieldPosition,
    /// A key is duplicated.
    ///
    /// § 1.6.2 Genotype fields (2021-01-13): "...duplicate keys are not allowed".
    DuplicateKey(field::Key),
}

impl error::Error for TryFromFieldsError {}

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

impl TryFrom<Vec<Field>> for Genotype {
    type Error = TryFromFieldsError;

    fn try_from(fields: Vec<Field>) -> Result<Self, Self::Error> {
        if fields.is_empty() {
            return Ok(Self::default());
        } else if let Some(i) = fields.iter().position(|f| f.key() == &field::Key::Genotype) {
            if i != 0 {
                return Err(TryFromFieldsError::InvalidGenotypeFieldPosition);
            }
        }

        let mut map = IndexMap::with_capacity(fields.len());

        for field in fields {
            if let Some(duplicate_field) = map.insert(field.key().clone(), field) {
                return Err(TryFromFieldsError::DuplicateKey(
                    duplicate_field.key().clone(),
                ));
            }
        }

        Ok(Self(map))
    }
}

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

    #[test]
    fn test_from_str_format() -> Result<(), Box<dyn std::error::Error>> {
        let keys = "GT".parse()?;
        assert_eq!(
            Genotype::from_str_format(".", &keys),
            Ok(Genotype::default())
        );

        let keys = "GT".parse()?;
        let actual = Genotype::from_str_format("0|0", &keys)?;
        assert_eq!(actual.len(), 1);

        let keys = "GT:GQ".parse()?;
        let actual = Genotype::from_str_format("0|0:13", &keys)?;
        assert_eq!(actual.len(), 2);

        let keys = "GT".parse()?;
        assert_eq!(Genotype::from_str_format("", &keys), Err(ParseError::Empty));

        Ok(())
    }

    #[test]
    fn test_fmt() -> Result<(), TryFromFieldsError> {
        let genotype = Genotype::default();
        assert_eq!(genotype.to_string(), ".");

        let genotype = Genotype::try_from(vec![Field::new(
            field::Key::Genotype,
            Some(field::Value::String(String::from("0|0"))),
        )])?;

        assert_eq!(genotype.to_string(), "0|0");

        let genotype = Genotype::try_from(vec![
            Field::new(
                field::Key::Genotype,
                Some(field::Value::String(String::from("0|0"))),
            ),
            Field::new(
                field::Key::ConditionalGenotypeQuality,
                Some(field::Value::Integer(13)),
            ),
        ])?;

        assert_eq!(genotype.to_string(), "0|0:13");

        Ok(())
    }

    #[test]
    fn test_try_from_fields_for_genotype() {
        assert!(Genotype::try_from(Vec::new()).is_ok());

        let fields = vec![Field::new(
            field::Key::Genotype,
            Some(field::Value::String(String::from("0|0"))),
        )];
        assert!(Genotype::try_from(fields).is_ok());

        let fields = vec![Field::new(
            field::Key::ConditionalGenotypeQuality,
            Some(field::Value::Integer(13)),
        )];
        assert!(Genotype::try_from(fields).is_ok());

        let fields = vec![
            Field::new(
                field::Key::ConditionalGenotypeQuality,
                Some(field::Value::Integer(13)),
            ),
            Field::new(
                field::Key::Genotype,
                Some(field::Value::String(String::from("0|0"))),
            ),
        ];
        assert_eq!(
            Genotype::try_from(fields),
            Err(TryFromFieldsError::InvalidGenotypeFieldPosition)
        );

        let fields = vec![
            Field::new(
                field::Key::Genotype,
                Some(field::Value::String(String::from("0|0"))),
            ),
            Field::new(
                field::Key::Genotype,
                Some(field::Value::String(String::from("0|0"))),
            ),
        ];
        assert_eq!(
            Genotype::try_from(fields),
            Err(TryFromFieldsError::DuplicateKey(field::Key::Genotype))
        );
    }

    #[test]
    fn test_genotype() -> Result<(), TryFromFieldsError> {
        let genotype = Genotype::try_from(vec![Field::new(
            field::Key::Genotype,
            Some(field::Value::String(String::from("ndls"))),
        )])?;

        assert!(matches!(
            genotype.genotype(),
            Some(Err(GenotypeError::InvalidValue(_)))
        ));

        let genotype = Genotype::try_from(vec![Field::new(
            field::Key::Genotype,
            Some(field::Value::Integer(0)),
        )])?;

        assert!(matches!(
            genotype.genotype(),
            Some(Err(GenotypeError::InvalidValueType(_)))
        ));

        Ok(())
    }
}