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
use crate::ChrRef;

pub trait RegionCore {
    fn start(&self) -> u32;
    fn end(&self) -> u32;
    fn chrom(&self) -> ChrRef<'static>;

    #[inline(always)]
    fn empty(&self) -> bool {
        self.end() <= self.start()
    }

    #[inline(always)]
    fn length(&self) -> u32 {
        self.end().max(self.start()) - self.start()
    }
}

impl <'a> RegionCore for (ChrRef<'a>, u32, u32) {
    fn start(&self) -> u32 {
        self.1
    }
    fn end(&self) -> u32 {
        self.2
    }
    fn chrom(&self) -> ChrRef<'static> {
        self.0.to_static()
    }
}

pub trait Region: RegionCore {
    #[inline(always)]
    fn overlaps(&self, b: &impl Region) -> bool {
        let a = self;
        if a.chrom() != b.chrom() {
            return false;
        }

        !(a.end() <= b.start() || b.end() <= a.start())
    }
}

impl<T: RegionCore> Region for T {}

impl<T: Region> RegionCore for Option<T> {
    #[inline(always)]
    fn start(&self) -> u32 {
        self.as_ref().map_or(0, |what| what.start())
    }
    #[inline(always)]
    fn end(&self) -> u32 {
        self.as_ref().map_or(0, |what| what.end())
    }
    #[inline(always)]
    fn chrom(&self) -> ChrRef<'static> {
        self.as_ref().map_or(ChrRef::Dummy, |what| what.chrom())
    }
}

impl<'a, T: Region> RegionCore for &'a T {
    #[inline(always)]
    fn start(&self) -> u32 {
        T::start(*self)
    }
    #[inline(always)]
    fn end(&self) -> u32 {
        T::end(*self)
    }
    #[inline(always)]
    fn chrom(&self) -> ChrRef<'static> {
        T::chrom(*self)
    }
}

impl<A: Region, B: Region> RegionCore for (A, B) {
    #[inline(always)]
    fn start(&self) -> u32 {
        if self.0.overlaps(&self.1) {
            self.0.start().max(self.1.start())
        } else {
            0
        }
    }

    #[inline(always)]
    fn end(&self) -> u32 {
        if self.0.overlaps(&self.1) {
            self.0.end().min(self.1.end())
        } else {
            0
        }
    }

    #[inline(always)]
    fn chrom(&self) -> ChrRef<'static> {
        self.0.chrom()
    }
}