xmlparser/
strspan.rs

1use core::fmt;
2use core::ops::{Deref, Range};
3
4
5/// A string slice.
6///
7/// Like `&str`, but also contains the position in the input XML
8/// from which it was parsed.
9#[must_use]
10#[derive(Clone, Copy, PartialEq, Eq, Hash)]
11pub struct StrSpan<'a> {
12    text: &'a str,
13    start: usize,
14}
15
16impl<'a> From<&'a str> for StrSpan<'a> {
17    #[inline]
18    fn from(text: &'a str) -> Self {
19        StrSpan {
20            text,
21            start: 0,
22        }
23    }
24}
25
26impl<'a> StrSpan<'a> {
27    /// Constructs a new `StrSpan` from substring.
28    #[inline]
29    pub(crate) fn from_substr(text: &str, start: usize, end: usize) -> StrSpan {
30        debug_assert!(start <= end);
31        StrSpan { text: &text[start..end], start }
32    }
33
34    /// Returns the start position of the span.
35    #[inline]
36    pub fn start(&self) -> usize {
37        self.start
38    }
39
40    /// Returns the end position of the span.
41    #[inline]
42    pub fn end(&self) -> usize {
43        self.start + self.text.len()
44    }
45
46    /// Returns the range of the span.
47    #[inline]
48    pub fn range(&self) -> Range<usize> {
49        self.start..self.end()
50    }
51
52    /// Returns the span as a string slice
53    #[inline]
54    pub fn as_str(&self) -> &'a str {
55        &self.text
56    }
57
58    /// Returns an underling string region as `StrSpan`.
59    #[inline]
60    pub(crate) fn slice_region(&self, start: usize, end: usize) -> StrSpan<'a> {
61        StrSpan::from_substr(self.text, start, end)
62    }
63}
64
65impl<'a> fmt::Debug for StrSpan<'a> {
66    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67        write!(f, "StrSpan({:?} {}..{})", self.as_str(), self.start(), self.end())
68    }
69}
70
71impl<'a> fmt::Display for StrSpan<'a> {
72    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73        write!(f, "{}", self.as_str())
74    }
75}
76
77impl<'a> Deref for StrSpan<'a> {
78    type Target = str;
79
80    fn deref(&self) -> &Self::Target {
81        self.text
82    }
83}