]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/syntax/src/token_text.rs
:arrow_up: rust-analyzer
[rust.git] / src / tools / rust-analyzer / 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 use rowan::GreenToken;
6
7 pub struct TokenText<'a>(pub(crate) Repr<'a>);
8
9 pub(crate) enum Repr<'a> {
10     Borrowed(&'a str),
11     Owned(GreenToken),
12 }
13
14 impl<'a> TokenText<'a> {
15     pub(crate) fn borrowed(text: &'a str) -> Self {
16         TokenText(Repr::Borrowed(text))
17     }
18
19     pub(crate) fn owned(green: GreenToken) -> Self {
20         TokenText(Repr::Owned(green))
21     }
22
23     pub fn as_str(&self) -> &str {
24         match &self.0 {
25             &Repr::Borrowed(it) => it,
26             Repr::Owned(green) => green.text(),
27         }
28     }
29 }
30
31 impl ops::Deref for TokenText<'_> {
32     type Target = str;
33
34     fn deref(&self) -> &str {
35         self.as_str()
36     }
37 }
38 impl AsRef<str> for TokenText<'_> {
39     fn as_ref(&self) -> &str {
40         self.as_str()
41     }
42 }
43
44 impl From<TokenText<'_>> for String {
45     fn from(token_text: TokenText<'_>) -> Self {
46         token_text.as_str().into()
47     }
48 }
49
50 impl PartialEq<&'_ str> for TokenText<'_> {
51     fn eq(&self, other: &&str) -> bool {
52         self.as_str() == *other
53     }
54 }
55 impl PartialEq<TokenText<'_>> for &'_ str {
56     fn eq(&self, other: &TokenText<'_>) -> bool {
57         other == self
58     }
59 }
60 impl PartialEq<String> for TokenText<'_> {
61     fn eq(&self, other: &String) -> bool {
62         self.as_str() == other.as_str()
63     }
64 }
65 impl PartialEq<TokenText<'_>> for String {
66     fn eq(&self, other: &TokenText<'_>) -> bool {
67         other == self
68     }
69 }
70 impl PartialEq for TokenText<'_> {
71     fn eq(&self, other: &TokenText<'_>) -> bool {
72         self.as_str() == other.as_str()
73     }
74 }
75 impl Eq for TokenText<'_> {}
76 impl Ord for TokenText<'_> {
77     fn cmp(&self, other: &Self) -> Ordering {
78         self.as_str().cmp(other.as_str())
79     }
80 }
81 impl PartialOrd for TokenText<'_> {
82     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
83         Some(self.cmp(other))
84     }
85 }
86 impl fmt::Display for TokenText<'_> {
87     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88         fmt::Display::fmt(self.as_str(), f)
89     }
90 }
91 impl fmt::Debug for TokenText<'_> {
92     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93         fmt::Debug::fmt(self.as_str(), f)
94     }
95 }