]> git.lizzy.rs Git - rust.git/blob - crates/syntax/src/token_text.rs
Borrow text from nodes of immutable syntax trees
[rust.git] / crates / syntax / src / token_text.rs
1 //! Yet another version of owned string, backed by a syntax tree token.
2
3 use std::{cmp::Ordering, fmt, ops};
4
5 pub enum TokenText<'a> {
6     Borrowed(&'a str),
7     Owned(rowan::GreenToken),
8 }
9
10 impl TokenText<'_> {
11     pub fn as_str(&self) -> &str {
12         match self {
13             TokenText::Borrowed(it) => *it,
14             TokenText::Owned(green) => green.text(),
15         }
16     }
17 }
18
19 impl ops::Deref for TokenText<'_> {
20     type Target = str;
21
22     fn deref(&self) -> &str {
23         self.as_str()
24     }
25 }
26 impl AsRef<str> for TokenText<'_> {
27     fn as_ref(&self) -> &str {
28         self.as_str()
29     }
30 }
31
32 impl From<TokenText<'_>> for String {
33     fn from(token_text: TokenText) -> Self {
34         token_text.as_str().into()
35     }
36 }
37
38 impl PartialEq<&'_ str> for TokenText<'_> {
39     fn eq(&self, other: &&str) -> bool {
40         self.as_str() == *other
41     }
42 }
43 impl PartialEq<TokenText<'_>> for &'_ str {
44     fn eq(&self, other: &TokenText) -> bool {
45         other == self
46     }
47 }
48 impl PartialEq<String> for TokenText<'_> {
49     fn eq(&self, other: &String) -> bool {
50         self.as_str() == other.as_str()
51     }
52 }
53 impl PartialEq<TokenText<'_>> for String {
54     fn eq(&self, other: &TokenText) -> bool {
55         other == self
56     }
57 }
58 impl PartialEq for TokenText<'_> {
59     fn eq(&self, other: &TokenText) -> bool {
60         self.as_str() == other.as_str()
61     }
62 }
63 impl Eq for TokenText<'_> {}
64 impl Ord for TokenText<'_> {
65     fn cmp(&self, other: &Self) -> Ordering {
66         self.as_str().cmp(other.as_str())
67     }
68 }
69 impl PartialOrd for TokenText<'_> {
70     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
71         Some(self.cmp(other))
72     }
73 }
74 impl fmt::Display for TokenText<'_> {
75     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76         fmt::Display::fmt(self.as_str(), f)
77     }
78 }
79 impl fmt::Debug for TokenText<'_> {
80     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81         fmt::Debug::fmt(self.as_str(), f)
82     }
83 }