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

use super::Ret;

use crate::ctx::Context;
use crate::err::Error;
use crate::re::Extract;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Span {
    pub beg: usize,

    pub len: usize,
}

impl Span {
    pub fn new(beg: usize, len: usize) -> Self {
        Self { beg, len }
    }
}

impl Ret for Span {
    fn fst(&self) -> usize {
        self.beg
    }

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

    fn is_zero(&self) -> bool {
        self.len == 0
    }

    fn add_assign(&mut self, other: Self) -> &mut Self {
        self.len += other.len + other.beg - (self.beg + self.len);
        self
    }

    fn from_ctx<'a, C>(ctx: &mut C, info: (usize, usize)) -> Self
    where
        C: Context<'a>,
    {
        Span {
            beg: ctx.offset(),
            len: info.1,
        }
    }
}

impl<'a, C: Context<'a>> Extract<'a, C, Span> for Span {
    type Out<'b> = Span;

    type Error = Error;

    fn extract(_: &C, ret: &Span) -> Result<Self::Out<'a>, Self::Error> {
        Ok(Clone::clone(ret))
    }
}

impl Display for Span {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{{beg: {}, len: {}}}", self.beg, self.len)
    }
}