mun_syntax/
token_text.rs

1//! An owned string backed by a rowan syntax tree token.
2
3use std::{cmp::Ordering, fmt, ops};
4
5use rowan::GreenToken;
6
7pub struct TokenText<'a>(pub(crate) Inner<'a>);
8
9pub(crate) enum Inner<'a> {
10    Borrowed(&'a str),
11    Owned(GreenToken),
12}
13
14impl<'a> TokenText<'a> {
15    /// Creates a new instance where the text is borrowed from a `str`
16    pub(crate) fn borrowed(text: &'a str) -> Self {
17        TokenText(Inner::Borrowed(text))
18    }
19
20    /// Creates a new instance where the text is borrowed from a syntax node.
21    pub(crate) fn owned(green: GreenToken) -> Self {
22        TokenText(Inner::Owned(green))
23    }
24
25    /// Returns the string representation of this instance
26    pub fn as_str(&self) -> &str {
27        match &self.0 {
28            &Inner::Borrowed(it) => it,
29            Inner::Owned(green) => green.text(),
30        }
31    }
32}
33
34impl ops::Deref for TokenText<'_> {
35    type Target = str;
36
37    fn deref(&self) -> &str {
38        self.as_str()
39    }
40}
41impl AsRef<str> for TokenText<'_> {
42    fn as_ref(&self) -> &str {
43        self.as_str()
44    }
45}
46
47impl From<TokenText<'_>> for String {
48    fn from(token_text: TokenText) -> Self {
49        token_text.as_str().into()
50    }
51}
52
53impl PartialEq<&'_ str> for TokenText<'_> {
54    fn eq(&self, other: &&str) -> bool {
55        self.as_str() == *other
56    }
57}
58impl PartialEq<TokenText<'_>> for &'_ str {
59    fn eq(&self, other: &TokenText) -> bool {
60        other == self
61    }
62}
63impl PartialEq<String> for TokenText<'_> {
64    fn eq(&self, other: &String) -> bool {
65        self.as_str() == other.as_str()
66    }
67}
68impl PartialEq<TokenText<'_>> for String {
69    fn eq(&self, other: &TokenText) -> bool {
70        other == self
71    }
72}
73impl PartialEq for TokenText<'_> {
74    fn eq(&self, other: &TokenText) -> bool {
75        self.as_str() == other.as_str()
76    }
77}
78impl Eq for TokenText<'_> {}
79impl Ord for TokenText<'_> {
80    fn cmp(&self, other: &Self) -> Ordering {
81        self.as_str().cmp(other.as_str())
82    }
83}
84impl PartialOrd for TokenText<'_> {
85    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
86        Some(self.cmp(other))
87    }
88}
89impl fmt::Display for TokenText<'_> {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        fmt::Display::fmt(self.as_str(), f)
92    }
93}
94impl fmt::Debug for TokenText<'_> {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        fmt::Debug::fmt(self.as_str(), f)
97    }
98}