Skip to main content

qualia_core_db/nlp/
span.rs

1//! UTF-8 byte span. Same fields as core-db `TextSpan` minus the hash (computed at emit).
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub struct DocSpan {
5    pub start_utf8: u32,
6    pub end_utf8: u32,
7}
8
9impl DocSpan {
10    /// Creates a default `DocSpan`.
11    pub fn new(start_utf8: u32, end_utf8: u32) -> Self {
12        Self {
13            start_utf8,
14            end_utf8,
15        }
16    }
17
18    /// Views `self` as `range`.
19    pub fn as_range(self) -> std::ops::Range<usize> {
20        self.start_utf8 as usize..self.end_utf8 as usize
21    }
22
23    /// Slice view.
24    pub fn slice<'a>(self, source: &'a str) -> Option<&'a str> {
25        let start = self.start_utf8 as usize;
26        let end = self.end_utf8 as usize;
27        if start <= end
28            && end <= source.len()
29            && source.is_char_boundary(start)
30            && source.is_char_boundary(end)
31        {
32            Some(&source[start..end])
33        } else {
34            None
35        }
36    }
37}