grass_runtime/record/
bed3.rs

1use std::io::{Result, Write};
2
3use crate::{
4    property::{Named, Parsable, RegionCore, Scored, Serializable, Stranded, Tagged},
5    ChrRef,
6};
7
8use super::ToSelfContained;
9
10#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
11pub struct Bed3 {
12    pub chrom: ChrRef<'static>,
13    pub start: u32,
14    pub end: u32,
15}
16
17impl Serializable for Bed3 {
18    fn dump<W: Write>(&self, mut fp: W) -> Result<()> {
19        fp.write_all(self.chrom().get_chr_name().as_bytes())?;
20        fp.write(b"\t")?;
21        crate::ioutils::write_number(&mut fp, self.start() as i32)?;
22        fp.write(b"\t")?;
23        crate::ioutils::write_number(&mut fp, self.end() as i32).map(|_| ())
24    }
25}
26
27impl Serializable for Option<Bed3> {
28    fn dump<W: Write>(&self, mut fp: W) -> Result<()> {
29        if let Some(inner) = self {
30            inner.dump(fp)
31        } else {
32            fp.write_all(b".\t.\t.\t")
33        }
34    }
35}
36
37impl<'a> Parsable<'a> for Bed3 {
38    fn parse(s: &'a str) -> Option<(Self, usize)> {
39        let mut bytes = s.as_bytes();
40
41        if bytes.last() == Some(&b'\n') {
42            bytes = &bytes[..bytes.len() - 1];
43        }
44
45        let mut token_pos_iter = memchr::Memchr::new(b'\t', bytes);
46        let end_1 = token_pos_iter.next()?;
47        let end_2 = token_pos_iter.next()?;
48        let end_3 = token_pos_iter.next().unwrap_or(bytes.len());
49        let chrom = &s[..end_1];
50
51        Some((
52            Self {
53                chrom: crate::Genome::query_chr(chrom).to_static(),
54                start: s[end_1 + 1..end_2].parse().ok()?,
55                end: s[end_2 + 1..end_3].parse().ok()?,
56            },
57            end_3,
58        ))
59    }
60}
61
62impl Bed3 {
63    pub fn new<T: RegionCore>(region: &T) -> Self {
64        Self {
65            chrom: region.chrom(),
66            start: region.start(),
67            end: region.end(),
68        }
69    }
70    #[inline(always)]
71    pub fn set_start(&mut self, start: f64) {
72        self.start = start as u32;
73    }
74    #[inline(always)]
75    pub fn set_end(&mut self, end: f64) {
76        self.end = end as u32;
77    }
78}
79
80impl RegionCore for Bed3 {
81    #[inline(always)]
82    fn start(&self) -> u32 {
83        self.start
84    }
85    #[inline(always)]
86    fn end(&self) -> u32 {
87        self.end
88    }
89    #[inline(always)]
90    fn chrom(&self) -> ChrRef<'static> {
91        self.chrom
92    }
93}
94
95impl Scored<f64> for Bed3 {
96    #[inline(always)]
97    fn score(&self) -> Option<f64> {
98        Default::default()
99    }
100}
101
102impl Stranded for Bed3 {}
103
104impl<'a> Named<'a> for Bed3 {}
105
106impl ToSelfContained for Bed3 {
107    type SelfContained = Bed3;
108    fn to_self_contained(&self) -> Self::SelfContained {
109        *self
110    }
111}
112
113impl<T: Clone> Tagged<T> for Bed3 {}