noodles_vcf/variant/record_buf/samples/
sample.rs

1//! VCF record genotype sample.
2
3pub mod value;
4
5use std::{hash::Hash, io};
6
7pub use self::value::Value;
8use super::Keys;
9use crate::Header;
10
11/// A VCF record genotype sample.
12#[derive(Debug, PartialEq)]
13pub struct Sample<'g> {
14    keys: &'g Keys,
15    values: &'g [Option<Value>],
16}
17
18impl<'g> Sample<'g> {
19    /// Creates a new genotype sample.
20    pub fn new(keys: &'g Keys, values: &'g [Option<Value>]) -> Self {
21        Self { keys, values }
22    }
23
24    /// Returns the keys.
25    pub fn keys(&self) -> &'g Keys {
26        self.keys
27    }
28
29    /// Returns the values.
30    pub fn values(&self) -> &'g [Option<Value>] {
31        self.values
32    }
33
34    /// Returns a reference to the value with the given key.
35    pub fn get<K>(&self, key: &K) -> Option<Option<&'g Value>>
36    where
37        K: Hash + indexmap::Equivalent<String> + ?Sized,
38    {
39        self.keys
40            .as_ref()
41            .get_index_of(key)
42            .and_then(|i| self.values.get(i).map(|value| value.as_ref()))
43    }
44}
45
46impl crate::variant::record::samples::Sample for Sample<'_> {
47    fn get<'a, 'h: 'a>(
48        &'a self,
49        header: &'h Header,
50        key: &str,
51    ) -> Option<io::Result<Option<crate::variant::record::samples::series::Value<'a>>>> {
52        self.keys
53            .as_ref()
54            .get_index_of(key)
55            .and_then(|i| self.get_index(header, i))
56    }
57
58    fn get_index<'a, 'h: 'a>(
59        &'a self,
60        _: &'h Header,
61        i: usize,
62    ) -> Option<io::Result<Option<crate::variant::record::samples::series::Value<'a>>>> {
63        self.values
64            .get(i)
65            .map(|value| Ok(value.as_ref().map(|v| v.into())))
66    }
67
68    fn iter<'a, 'h: 'a>(
69        &'a self,
70        _: &'h Header,
71    ) -> Box<
72        dyn Iterator<
73                Item = io::Result<(
74                    &'a str,
75                    Option<crate::variant::record::samples::series::Value<'a>>,
76                )>,
77            > + 'a,
78    > {
79        Box::new(
80            self.keys
81                .as_ref()
82                .iter()
83                .zip(self.values)
84                .map(|(key, value)| Ok((key.as_ref(), value.as_ref().map(|v| v.into())))),
85        )
86    }
87}