Skip to main content

vvv_core/text/
source_text.rs

1use std::sync::OnceLock;
2
3use super::{LineIndex, Position, Span, SpanError};
4
5/// Immutable file contents together with a line index, built the first time
6/// a line is asked for: most files a search loads are never located in.
7#[derive(Debug, Clone)]
8pub struct SourceText {
9    text: String,
10    index: OnceLock<LineIndex>,
11}
12
13impl SourceText {
14    pub fn new(text: impl Into<String>) -> Self {
15        Self {
16            text: text.into(),
17            index: OnceLock::new(),
18        }
19    }
20
21    pub fn as_str(&self) -> &str {
22        &self.text
23    }
24
25    pub fn len(&self) -> usize {
26        self.text.len()
27    }
28
29    pub fn is_empty(&self) -> bool {
30        self.text.is_empty()
31    }
32
33    /// Slice a trusted range. Use [`Self::get`] for unchecked external coordinates.
34    ///
35    /// # Panics
36    /// Panics when the range is reversed, outside the source, or splits UTF-8.
37    pub fn slice(&self, span: Span) -> &str {
38        &self.text[span.start..span.end]
39    }
40
41    /// Read a range received from a plugin or client without unchecked indexing.
42    pub fn get(&self, span: Span) -> Result<&str, SpanError> {
43        span.validate_in(&self.text)?;
44        Ok(self.slice(span))
45    }
46
47    pub fn position(&self, offset: usize) -> Position {
48        self.line_index().position(&self.text, offset)
49    }
50
51    /// The byte offset of `position`, `None` past the end of the file.
52    pub fn offset(&self, position: Position) -> Option<usize> {
53        self.line_index().offset(&self.text, position)
54    }
55
56    /// The text of the zero-based `line`, without its terminator.
57    pub fn line(&self, line: usize) -> Option<&str> {
58        self.line_index().line_text(&self.text, line)
59    }
60
61    pub fn line_index(&self) -> &LineIndex {
62        self.index.get_or_init(|| LineIndex::new(&self.text))
63    }
64}
65
66impl From<String> for SourceText {
67    fn from(text: String) -> Self {
68        SourceText::new(text)
69    }
70}
71
72impl From<&str> for SourceText {
73    fn from(text: &str) -> Self {
74        SourceText::new(text)
75    }
76}