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

mod keys;
mod sample;
pub mod series;

use std::{io, iter};

pub use self::{keys::Keys, sample::Sample, series::Series};
use crate::Header;

const DELIMITER: char = '\t';

/// Raw VCF record genotypes.
#[derive(Debug, Eq, PartialEq)]
pub struct Samples<'r>(&'r str);

impl<'r> Samples<'r> {
    pub(super) fn new(buf: &'r str) -> Self {
        Self(buf)
    }

    /// Returns whether there may be any genotypes.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the keys.
    pub fn keys(&self) -> Keys<'r> {
        let (src, _) = self.0.split_once(DELIMITER).unwrap_or_default();
        Keys::new(src)
    }

    /// Returns an iterator over series.
    pub fn series(&'r self) -> impl Iterator<Item = Series<'r>> + '_ {
        self.keys()
            .iter()
            .enumerate()
            .map(|(i, key)| Series::new(key, self, i))
    }

    /// Returns an iterator over samples.
    pub fn iter(&self) -> impl Iterator<Item = Sample<'r>> + '_ {
        let (_, mut src) = self.0.split_once(DELIMITER).unwrap_or_default();

        iter::from_fn(move || {
            if src.is_empty() {
                None
            } else {
                Some(parse_sample(&mut src, self.keys()))
            }
        })
    }
}

impl<'a> AsRef<str> for Samples<'a> {
    fn as_ref(&self) -> &str {
        self.0
    }
}

impl<'r> crate::variant::record::Samples for Samples<'r> {
    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    fn len(&self) -> usize {
        self.iter().count()
    }

    fn column_names<'a, 'h: 'a>(
        &'a self,
        _: &'h Header,
    ) -> Box<dyn Iterator<Item = io::Result<&'a str>> + 'a> {
        Box::new(self.keys().iter().map(Ok))
    }

    fn series(
        &self,
    ) -> Box<
        dyn Iterator<Item = io::Result<Box<dyn crate::variant::record::samples::Series + '_>>> + '_,
    > {
        Box::new(
            self.series()
                .map(|series| Box::new(series) as Box<dyn crate::variant::record::samples::Series>)
                .map(Ok),
        )
    }

    fn iter(
        &self,
    ) -> Box<dyn Iterator<Item = Box<dyn crate::variant::record::samples::Sample + '_>> + '_> {
        Box::new(
            self.iter()
                .map(|sample| Box::new(sample) as Box<dyn crate::variant::record::samples::Sample>),
        )
    }
}

fn parse_sample<'r>(src: &mut &'r str, keys: Keys<'r>) -> Sample<'r> {
    const DELIMITER: u8 = b'\t';
    const MISSING: &str = ".";

    let buf = match src.as_bytes().iter().position(|&b| b == DELIMITER) {
        Some(i) => {
            let (buf, rest) = src.split_at(i);
            *src = &rest[1..];
            buf
        }
        None => {
            let (buf, rest) = src.split_at(src.len());
            *src = rest;
            buf
        }
    };

    if buf == MISSING {
        Sample::new("", keys)
    } else {
        Sample::new(buf, keys)
    }
}

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

    #[test]
    fn test_is_empty() {
        assert!(Samples::new("").is_empty());
        assert!(!Samples::new("GT:GQ\t0|0:13").is_empty());
    }

    #[test]
    fn test_iter() {
        let samples = Samples::new("");
        assert!(samples.iter().next().is_none());

        let samples = Samples::new("GT:GQ\t0|0:13\t.");
        let actual: Vec<_> = samples.iter().collect();
        let expected = [
            Sample::new("0|0:13", samples.keys()),
            Sample::new("", samples.keys()),
        ];
        assert_eq!(actual, expected);
    }
}