use alloc::boxed::Box;
use alloc::string::String;
use super::origin::SourceOrigin;
use super::source::Source;
use super::span::Span;
#[derive(Clone, Debug)]
pub enum TextContent {
Spanned(Span),
Owned(Box<str>),
}
impl TextContent {
pub fn empty() -> TextContent {
TextContent::Owned(Box::from(""))
}
pub fn resolve<'a, O: SourceOrigin>(&'a self, source: &'a Source<O>) -> &'a str {
match self {
TextContent::Spanned(span) => span.slice(source.content()),
TextContent::Owned(text) => text,
}
}
pub fn materialized<O: SourceOrigin>(&self, source: &Source<O>) -> TextContent {
match self {
TextContent::Spanned(span) => {
TextContent::Owned(Box::from(span.slice(source.content())))
}
TextContent::Owned(text) => TextContent::Owned(text.clone()),
}
}
pub fn is_owned(&self) -> bool {
matches!(self, TextContent::Owned(_))
}
}
impl From<Span> for TextContent {
fn from(span: Span) -> TextContent {
TextContent::Spanned(span)
}
}
impl From<&str> for TextContent {
fn from(text: &str) -> TextContent {
TextContent::Owned(Box::from(text))
}
}
impl From<String> for TextContent {
fn from(text: String) -> TextContent {
TextContent::Owned(text.into_boxed_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn source(content: &str) -> Source {
Source::new(content)
}
#[test]
fn spanned_resolution() {
let src = source("hello world");
let tc = TextContent::from(Span::new(6, 11));
assert!(!tc.is_owned());
assert_eq!(tc.resolve(&src), "world");
}
#[test]
fn owned_resolution_ignores_source() {
let tc = TextContent::from("synthesized");
assert!(tc.is_owned());
assert_eq!(tc.resolve(&source("unrelated")), "synthesized");
}
#[test]
fn materialized_preserves_logical_text() {
let empty = source("");
let spanned = TextContent::from(Span::new(0, 5));
let owned = spanned.materialized(&source("hello world"));
assert!(owned.is_owned());
assert_eq!(owned.resolve(&empty), "hello");
let already_owned = TextContent::from(String::from("abc")).materialized(&empty);
assert_eq!(already_owned.resolve(&empty), "abc");
}
#[test]
fn empty_is_owned_empty() {
let tc = TextContent::empty();
assert!(tc.is_owned());
assert_eq!(tc.resolve(&source("")), "");
}
}