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
use std::{io, iter};

use crate::variant::record::samples::series::value::genotype::Phasing;

/// VCF record samples series genotype value.
#[derive(Debug)]
pub struct Genotype<'a>(&'a str);

impl<'a> Genotype<'a> {
    pub(crate) fn new(src: &'a str) -> Self {
        Self(src)
    }
}

impl<'a> crate::variant::record::samples::series::value::Genotype for Genotype<'a> {
    fn iter(&self) -> Box<dyn Iterator<Item = io::Result<(Option<usize>, Phasing)>> + '_> {
        let mut src = self.0;

        let first_allele_result = parse_first_allele(&mut src);

        Box::new(
            iter::once(first_allele_result).chain(iter::from_fn(move || {
                if src.is_empty() {
                    None
                } else {
                    Some(parse_allele(&mut src))
                }
            })),
        )
    }
}

fn parse_first_allele(src: &mut &str) -> io::Result<(Option<usize>, Phasing)> {
    let mut buf = next_allele(src);

    let phasing = if buf.starts_with(|c| matches!(c, '|' | '/')) {
        let p = parse_phasing(&buf[..1])?;
        buf = &buf[1..];
        p
    } else if src
        .as_bytes()
        .iter()
        .filter(|&&b| matches!(b, b'|' | b'/'))
        .any(|&b| b == b'/')
    {
        Phasing::Unphased
    } else {
        Phasing::Phased
    };

    let position = parse_position(buf)?;

    Ok((position, phasing))
}

fn parse_allele(src: &mut &str) -> io::Result<(Option<usize>, Phasing)> {
    let buf = next_allele(src);

    let phasing = parse_phasing(&buf[..1])?;
    let position = parse_position(&buf[1..])?;

    Ok((position, phasing))
}

fn next_allele<'a>(src: &mut &'a str) -> &'a str {
    let (buf, rest) = match src.chars().skip(1).position(is_phasing_indicator) {
        Some(i) => src.split_at(i + 1),
        None => src.split_at(src.len()),
    };

    *src = rest;

    buf
}

fn is_phasing_indicator(c: char) -> bool {
    const PHASED: char = '|';
    const UNPHASED: char = '/';

    matches!(c, PHASED | UNPHASED)
}

fn parse_phasing(src: &str) -> io::Result<Phasing> {
    const PHASED: &str = "|";
    const UNPHASED: &str = "/";

    match src {
        PHASED => Ok(Phasing::Phased),
        UNPHASED => Ok(Phasing::Unphased),
        _ => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "invalid phasing indicator",
        )),
    }
}

fn parse_position(src: &str) -> io::Result<Option<usize>> {
    const MISSING: &str = ".";

    match src {
        MISSING => Ok(None),
        _ => src
            .parse()
            .map(Some)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::variant::record::samples::series::value::Genotype as _;

    #[test]
    fn test_iter() -> io::Result<()> {
        fn t(src: &str, expected: &[(Option<usize>, Phasing)]) -> io::Result<()> {
            let genotype = Genotype::new(src);
            let actual: Vec<_> = genotype.iter().collect::<io::Result<_>>()?;
            assert_eq!(actual, expected);
            Ok(())
        }

        t(
            "0|0",
            &[(Some(0), Phasing::Phased), (Some(0), Phasing::Phased)],
        )?;
        t(
            "0/1",
            &[(Some(0), Phasing::Unphased), (Some(1), Phasing::Unphased)],
        )?;
        t(
            "|0/1",
            &[(Some(0), Phasing::Phased), (Some(1), Phasing::Unphased)],
        )?;
        t(
            "|1/2|3",
            &[
                (Some(1), Phasing::Phased),
                (Some(2), Phasing::Unphased),
                (Some(3), Phasing::Phased),
            ],
        )?;
        t(
            "./.",
            &[(None, Phasing::Unphased), (None, Phasing::Unphased)],
        )?;

        Ok(())
    }
}