vvv_core/text/
source_text.rs1use std::sync::OnceLock;
2
3use super::{LineIndex, Position, Span, SpanError};
4
5#[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 pub fn slice(&self, span: Span) -> &str {
38 &self.text[span.start..span.end]
39 }
40
41 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 pub fn offset(&self, position: Position) -> Option<usize> {
53 self.line_index().offset(&self.text, position)
54 }
55
56 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}