noodles_bcf/record/samples/
sample.rs

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
use std::io;

use noodles_vcf::{self as vcf, variant::record::samples::series::Value};

use super::Samples;

/// A BCF record sample.
pub struct Sample<'r> {
    samples: &'r Samples<'r>,
    i: usize,
}

impl<'r> Sample<'r> {
    pub(super) fn new(samples: &'r Samples<'r>, i: usize) -> Self {
        Self { samples, i }
    }
}

impl<'r> vcf::variant::record::samples::Sample for Sample<'r> {
    fn get<'a, 'h: 'a>(
        &'a self,
        header: &'h vcf::Header,
        key: &str,
    ) -> Option<io::Result<Option<Value<'a>>>> {
        for result in self.iter(header) {
            match result {
                Ok((k, v)) => {
                    if k == key {
                        return Some(Ok(v));
                    }
                }
                Err(e) => return Some(Err(e)),
            }
        }

        None
    }

    fn get_index<'a, 'h: 'a>(
        &'a self,
        header: &'h vcf::Header,
        i: usize,
    ) -> Option<io::Result<Option<Value<'a>>>> {
        self.iter(header)
            .nth(i)
            .map(|result| result.map(|(_, value)| value))
    }

    fn iter<'a, 'h: 'a>(
        &'a self,
        header: &'h vcf::Header,
    ) -> Box<dyn Iterator<Item = io::Result<(&'a str, Option<Value<'a>>)>> + 'a> {
        let series = self.samples.series();

        Box::new(series.map(|result| {
            result.and_then(|series| {
                let name = series.name(header)?;

                let value = series
                    .get(header, self.i)
                    .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing value"))?
                    .transpose()?;

                Ok((name, value))
            })
        }))
    }
}