cdoc_parser/
common.rs

1use serde::{Deserialize, Serialize};
2use std::cmp::min;
3use std::ops::Range;
4
5// #[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize)]
6// pub struct Span {
7//     pub input: CowStr,
8//     pub start: usize,
9//     pub end: usize,
10// }
11
12// impl Span {
13//     pub fn new(input: CowStr, start: usize, end: usize) -> Self {
14//         Span { input, start, end }
15//     }
16//
17//     pub fn get_with_margin(&self, margin: usize) -> &str {
18//         &self.input[self.start.checked_sub(margin).unwrap_or_default()
19//             ..min(self.end + margin, self.input.len())]
20//     }
21// }
22
23// impl<'a> From<pest::Span<'a>> for Span {
24//     fn from(value: pest::Span) -> Self {
25//         Span {
26//             input: value.get_input().into(),
27//             start: value.start(),
28//             end: value.end(),
29//         }
30//     }
31// }
32
33#[derive(Debug, PartialEq, Default, Clone, Serialize, Deserialize)]
34pub struct Span {
35    pub range: Range<usize>,
36}
37
38impl Span {
39    pub fn new(start: usize, end: usize) -> Self {
40        Self { range: start..end }
41    }
42
43    pub fn get_with_margin<'a>(&self, input: &'a str, margin: usize) -> &'a str {
44        &input[self.range.start.checked_sub(margin).unwrap_or_default()
45            ..min(self.range.end + margin, input.len())]
46    }
47}
48
49impl From<pest::Span<'_>> for Span {
50    fn from(value: pest::Span) -> Self {
51        Self {
52            range: value.start()..value.end(),
53        }
54    }
55}