source_text/
source.rs

1use crate::OwnedSource;
2use std::borrow::Cow;
3
4/// A [Source] owns or refers to a `text` string with an optional `name` denoting the origin.
5///
6/// The `name` and `text` are both `Cow<'a, str>` allowing a [Source] to either own or refer to
7/// these.
8#[derive(Debug)]
9pub struct Source<'a> {
10    name: Option<Cow<'a, str>>,
11    text: Cow<'a, str>,
12}
13
14impl<'a> Source<'a> {
15    /// Create a new [Source] with an optional origin name. Example: `Source::new(Some("<built-in>"), "my text")`
16    pub fn new<N, T>(optname: Option<N>, text: T) -> Self
17    where
18        Cow<'a, str>: From<N>,
19        Cow<'a, str>: From<T>,
20    {
21        Source {
22            name: optname.map(|n| Cow::from(n)),
23            text: Cow::from(text),
24        }
25    }
26
27    /// Create a new [Source] with a given origin name. Example: `Source::new_named("<built-in>", "my text")`
28    pub fn new_named<N, T>(name: N, text: T) -> Self
29    where
30        Cow<'a, str>: From<N>,
31        Cow<'a, str>: From<T>,
32    {
33        Source::new(Some(name), text)
34    }
35
36    /// Create a new [Source] without an origin name. Example: `Source::new_unnamed("my text")`
37    pub fn new_unnamed<T>(text: T) -> Self
38    where
39        Cow<'a, str>: From<T>,
40    {
41        Source::new(None, text)
42    }
43
44    /// Borrow the name of this [Source], which if absent defaults to `"<string>"`.
45    pub fn name(&self) -> &str {
46        use crate::optname_to_str;
47
48        optname_to_str(self.name.as_ref().map(|cow| cow.as_ref()))
49    }
50
51    /// Borrow the text of this [Source].
52    pub fn text(&self) -> &str {
53        self.text.as_ref()
54    }
55}
56
57impl<'a> From<Source<'a>> for OwnedSource {
58    fn from(s: Source<'a>) -> OwnedSource {
59        OwnedSource::new(s.name, s.text)
60    }
61}
62
63impl<'a> From<OwnedSource> for Source<'a> {
64    fn from(s: OwnedSource) -> Source<'a> {
65        let (optname, text) = s.unwrap();
66        Source::new(optname, text)
67    }
68}