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
//! VCF header pedigree record.

pub mod key;

pub use self::key::Key;

use std::{convert::TryFrom, error, fmt};

use indexmap::IndexMap;

use super::{record, Record};

/// A VCF header pedigree record (`PEDIGREE`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Pedigree {
    id: String,
    fields: IndexMap<String, String>,
}

impl Pedigree {
    /// Creates a VCF header pedigree record.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::header::Pedigree;
    /// let pedigree = Pedigree::new(String::from("cid"), Default::default());
    /// ```
    pub fn new(id: String, fields: IndexMap<String, String>) -> Self {
        Self { id, fields }
    }

    /// Returns the ID of the sample record.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::header::Pedigree;
    /// let pedigree = Pedigree::new(String::from("cid"), Default::default());
    /// assert_eq!(pedigree.id(), "cid");
    /// ```
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Returns the extra fields in the record.
    ///
    /// This includes fields other than `ID`.
    ///
    /// # Examples
    ///
    /// ```
    /// use noodles_vcf::header::Pedigree;
    /// let pedigree = Pedigree::new(String::from("cid"), Default::default());
    /// assert!(pedigree.fields().is_empty());
    /// ```
    pub fn fields(&self) -> &IndexMap<String, String> {
        &self.fields
    }
}

impl fmt::Display for Pedigree {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(record::PREFIX)?;
        f.write_str(record::Key::Pedigree.as_ref())?;
        f.write_str("=<")?;

        write!(f, "ID={}", self.id())?;

        for (key, value) in &self.fields {
            write!(f, r#",{}={}"#, key, value)?;
        }

        f.write_str(">")?;

        Ok(())
    }
}

/// An error returned when a generic VCF header record fails to convert to a pedigree record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TryFromRecordError {
    /// The record is invalid.
    InvalidRecord,
    /// A required field is missing.
    MissingField(Key),
}

impl error::Error for TryFromRecordError {}

impl fmt::Display for TryFromRecordError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidRecord => f.write_str("invalid record"),
            Self::MissingField(key) => write!(f, "missing field: {}", key),
        }
    }
}

impl TryFrom<Record> for Pedigree {
    type Error = TryFromRecordError;

    fn try_from(record: Record) -> Result<Self, Self::Error> {
        match record.into() {
            (record::Key::Pedigree, record::Value::Struct(fields)) => parse_struct(fields),
            _ => Err(TryFromRecordError::InvalidRecord),
        }
    }
}

fn parse_struct(fields: Vec<(String, String)>) -> Result<Pedigree, TryFromRecordError> {
    let mut it = fields.into_iter();

    let id = it
        .next()
        .ok_or(TryFromRecordError::MissingField(Key::Id))
        .and_then(|(k, v)| match k.parse() {
            Ok(Key::Id) => Ok(v),
            _ => Err(TryFromRecordError::MissingField(Key::Id)),
        })?;

    let fields = it.collect();

    Ok(Pedigree::new(id, fields))
}

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

    fn build_record() -> Record {
        Record::new(
            record::Key::Pedigree,
            record::Value::Struct(vec![
                (String::from("ID"), String::from("cid")),
                (String::from("Father"), String::from("fid")),
                (String::from("Mother"), String::from("mid")),
            ]),
        )
    }

    #[test]
    fn test_fmt() {
        let sample = Pedigree::new(String::from("cid"), IndexMap::new());
        assert_eq!(sample.to_string(), "##PEDIGREE=<ID=cid>");

        let mut fields = IndexMap::new();
        fields.insert(String::from("Father"), String::from("fid"));
        fields.insert(String::from("Mother"), String::from("mid"));
        let sample = Pedigree::new(String::from("cid"), fields);
        assert_eq!(
            sample.to_string(),
            "##PEDIGREE=<ID=cid,Father=fid,Mother=mid>"
        );
    }

    #[test]
    fn test_try_from_record_for_pedigree() {
        let record = build_record();
        let actual = Pedigree::try_from(record);

        let mut fields = IndexMap::new();
        fields.insert(String::from("Father"), String::from("fid"));
        fields.insert(String::from("Mother"), String::from("mid"));
        let expected = Pedigree::new(String::from("cid"), fields);

        assert_eq!(actual, Ok(expected));
    }
}