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

pub mod key;
pub mod value;

pub use self::{key::Key, value::Value};

use std::{error, fmt};

const MISSING_VALUE: &str = ".";

/// A VCF record genotype field.
#[derive(Clone, Debug, PartialEq)]
pub struct Field {
    key: Key,
    value: Option<Value>,
}

/// An error returned when a raw VCF record info field value fails to parse.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseError {
    /// The value is invalid.
    InvalidValue(value::ParseError),
}

impl error::Error for ParseError {}

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

impl Field {
    /// Parses a raw genotype field for the given key.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::record::genotype::{field::{Key, Value}, Field};
    ///
    /// assert_eq!(
    ///     Field::from_str_key("13", &Key::ConditionalGenotypeQuality),
    ///     Ok(Field::new(Key::ConditionalGenotypeQuality, Some(Value::Integer(13))))
    /// );
    /// ```
    pub fn from_str_key(s: &str, key: &Key) -> Result<Self, ParseError> {
        if s == MISSING_VALUE {
            Ok(Self::new(key.clone(), None))
        } else {
            Value::from_str_key(s, key)
                .map(|v| Self::new(key.clone(), Some(v)))
                .map_err(ParseError::InvalidValue)
        }
    }

    /// Creates a VCF record genotype field.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::record::genotype::{field::{Key, Value}, Field};
    ///
    /// let field = Field::new(
    ///     Key::ConditionalGenotypeQuality,
    ///     Some(Value::Integer(13)),
    /// );
    /// ```
    pub fn new(key: Key, value: Option<Value>) -> Self {
        Self { key, value }
    }

    /// Returns the genotype field key.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::record::genotype::{field::{Key, Value}, Field};
    ///
    /// let field = Field::new(
    ///     Key::ConditionalGenotypeQuality,
    ///     Some(Value::Integer(13)),
    /// );
    ///
    /// assert_eq!(field.key(), &Key::ConditionalGenotypeQuality);
    /// ```
    pub fn key(&self) -> &Key {
        &self.key
    }

    /// Returns the genotype field value.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::record::genotype::{field::{Key, Value}, Field};
    ///
    /// let field = Field::new(
    ///     Key::ConditionalGenotypeQuality,
    ///     Some(Value::Integer(13)),
    /// );
    ///
    /// assert_eq!(field.value(), Some(&Value::Integer(13)));
    /// ```
    pub fn value(&self) -> Option<&Value> {
        self.value.as_ref()
    }
}

impl fmt::Display for Field {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(value) = self.value() {
            write!(f, "{}", value)
        } else {
            f.write_str(MISSING_VALUE)
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::header::{format::Type, Number};

    use super::*;

    #[test]
    fn test_from_str_key() -> Result<(), ParseError> {
        let key = Key::MappingQuality;
        let actual = Field::from_str_key(".", &key)?;
        assert_eq!(actual.key(), &key);
        assert_eq!(actual.value(), None);

        let key = Key::ConditionalGenotypeQuality;
        let actual = Field::from_str_key("13", &key)?;
        assert_eq!(actual.key(), &key);
        assert_eq!(actual.value(), Some(&Value::Integer(13)));

        let key = Key::Other(
            String::from("CNQ"),
            Number::Count(1),
            Type::Float,
            String::default(),
        );
        let actual = Field::from_str_key("8.333", &key)?;
        assert_eq!(actual.key(), &key);
        assert_eq!(actual.value(), Some(&Value::Float(8.333)));

        let key = Key::Genotype;
        let actual = Field::from_str_key("0|0", &key)?;
        assert_eq!(actual.key(), &key);
        assert_eq!(actual.value(), Some(&Value::String(String::from("0|0"))));

        Ok(())
    }

    #[test]
    fn test_fmt() {
        let field = Field::new(Key::MappingQuality, None);
        assert_eq!(field.to_string(), ".");

        let field = Field::new(Key::ConditionalGenotypeQuality, Some(Value::Integer(13)));
        assert_eq!(field.to_string(), "13");

        let key = Key::Other(
            String::from("CNQ"),
            Number::Count(1),
            Type::Float,
            String::default(),
        );
        let field = Field::new(key, Some(Value::Float(8.333)));
        assert_eq!(field.to_string(), "8.333");

        let field = Field::new(Key::Genotype, Some(Value::String(String::from("0|0"))));
        assert_eq!(field.to_string(), "0|0");
    }
}