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

pub mod key;
pub mod value;

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

use std::{error, fmt, str::FromStr};

use crate::header::info::Type;

const SEPARATOR: char = '=';
const MAX_COMPONENTS: usize = 2;

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

impl Field {
    /// Creates a VCF record info field.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::record::info::{field::{Key, Value}, Field};
    /// let field = Field::new(Key::SamplesWithDataCount, Value::Integer(1));
    /// ```
    pub fn new(key: Key, value: Value) -> Self {
        Self { key, value }
    }

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

    /// Returns the field value.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::record::info::{field::{Key, Value}, Field};
    /// let field = Field::new(Key::SamplesWithDataCount, Value::Integer(1));
    /// assert_eq!(field.value(), &Value::Integer(1));
    /// ```
    pub fn value(&self) -> &Value {
        &self.value
    }
}

impl fmt::Display for Field {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.value() {
            Value::Flag => write!(f, "{}", self.key),
            value => write!(f, "{}{}{}", self.key, SEPARATOR, value),
        }
    }
}

/// An error returned when a raw VCF record info field fails to parse.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseError {
    /// The key is missing.
    MissingKey,
    /// The key is invalid.
    InvalidKey(key::ParseError),
    /// The value is missing.
    MissingValue,
    /// 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::MissingKey => f.write_str("missing key"),
            Self::InvalidKey(e) => write!(f, "invalid key: {}", e),
            Self::MissingValue => f.write_str("missing value"),
            Self::InvalidValue(e) => write!(f, "invalid value: {}", e),
        }
    }
}

impl FromStr for Field {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut components = s.splitn(MAX_COMPONENTS, SEPARATOR);

        let key: Key = components
            .next()
            .ok_or(ParseError::MissingKey)
            .and_then(|s| s.parse().map_err(ParseError::InvalidKey))?;

        let value = if let Type::Flag = key.ty() {
            let t = components.next().unwrap_or_default();
            Value::from_str_key(t, &key).map_err(ParseError::InvalidValue)?
        } else if let Key::Other(..) = key {
            if let Some(t) = components.next() {
                Value::from_str_key(t, &key).map_err(ParseError::InvalidValue)?
            } else {
                Value::Flag
            }
        } else {
            components
                .next()
                .ok_or(ParseError::MissingValue)
                .and_then(|t| Value::from_str_key(t, &key).map_err(ParseError::InvalidValue))?
        };

        Ok(Self::new(key, value))
    }
}

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

    use super::*;

    #[test]
    fn test_fmt() {
        let field = Field::new(Key::SamplesWithDataCount, Value::Integer(2));
        assert_eq!(field.to_string(), "NS=2");

        let field = Field::new(Key::BaseQuality, Value::Float(1.333));
        assert_eq!(field.to_string(), "BQ=1.333");

        let field = Field::new(Key::IsSomaticMutation, Value::Flag);
        assert_eq!(field.to_string(), "SOMATIC");

        let field = Field::new(
            Key::Other(
                String::from("SVTYPE"),
                Number::Count(1),
                Type::String,
                String::default(),
            ),
            Value::String(String::from("DEL")),
        );
        assert_eq!(field.to_string(), "SVTYPE=DEL");
    }

    #[test]
    fn test_from_str() -> Result<(), ParseError> {
        let actual: Field = "NS=2".parse()?;
        assert_eq!(actual.key(), &Key::SamplesWithDataCount);
        assert_eq!(actual.value(), &Value::Integer(2));

        let actual: Field = "BQ=1.333".parse()?;
        assert_eq!(actual.key(), &Key::BaseQuality);
        assert_eq!(actual.value(), &Value::Float(1.333));

        let actual: Field = "SOMATIC".parse()?;
        assert_eq!(actual.key(), &Key::IsSomaticMutation);
        assert_eq!(actual.value(), &Value::Flag);

        let actual: Field = "EVENT=INV0".parse()?;
        assert_eq!(actual.key(), &Key::BreakendEventId);
        assert_eq!(actual.value(), &Value::String(String::from("INV0")));

        let actual: Field = "NDLS=VCF".parse()?;
        assert_eq!(
            actual.key(),
            &Key::Other(
                String::from("NDLS"),
                Number::Count(1),
                Type::String,
                String::default()
            )
        );
        assert_eq!(actual.value(), &Value::String(String::from("VCF")));

        let actual: Field = "FLG".parse()?;
        assert_eq!(
            actual.key(),
            &Key::Other(
                String::from("FLG"),
                Number::Count(1),
                Type::String,
                String::default()
            )
        );
        assert_eq!(actual.value(), &Value::Flag);

        Ok(())
    }
}