source_text/
ownedsource.rs

1use crate::Source;
2
3/// An [OwnedSource] owns a `text` string with an optional `name` denoting the origin.
4#[derive(Debug)]
5pub struct OwnedSource {
6    name: Option<String>,
7    text: String,
8}
9
10impl OwnedSource {
11    /// Create a new [OwnedSource] with an optional origin name. Example: `OwnedSource::new(Some("<built-in>"), "my text")`
12    pub fn new<N, T>(optname: Option<N>, text: T) -> Self
13    where
14        String: From<N>,
15        String: From<T>,
16    {
17        OwnedSource {
18            name: optname.map(|n| String::from(n)),
19            text: String::from(text),
20        }
21    }
22
23    /// Create a new [OwnedSource] with a given origin name. Example: `OwnedSource::new_named("<built-in>", "my text")`
24    pub fn new_named<N, T>(name: N, text: T) -> Self
25    where
26        String: From<N>,
27        String: From<T>,
28    {
29        OwnedSource::new(Some(name), text)
30    }
31
32    /// Create a new [OwnedSource] without an origin name. Example: `Source::new_unnamed("my text")`
33    pub fn new_unnamed<T>(text: T) -> Self
34    where
35        String: From<T>,
36    {
37        OwnedSource::new(None, text)
38    }
39
40    /// Borrow the name, which if absent defaults to `"<string>"`.
41    pub fn name(&self) -> &str {
42        use crate::optname_to_str;
43
44        optname_to_str(self.name.as_ref().map(|s| s.as_ref()))
45    }
46
47    /// Borrow the text.
48    pub fn text(&self) -> &str {
49        self.text.as_ref()
50    }
51
52    /// Return a [Source] referring to `self`'s contents.
53    pub fn source(&self) -> Source {
54        Source::new(self.name.as_ref(), self.text())
55    }
56
57    /// Unbundle the optional `name` and `text` to take direct ownership.
58    pub fn unwrap(self) -> (Option<String>, String) {
59        (self.name, self.text)
60    }
61}