blob: 4bb8878d8c1bbb75db190d39e215553b352dcacf [file] [log] [blame]
David Tolnay42f50292016-09-04 13:54:21 -07001use std::fmt::{self, Display};
David Tolnay42f50292016-09-04 13:54:21 -07002
David Tolnay55337722016-09-11 12:58:56 -07003#[derive(Debug, Clone, Eq, Hash)]
David Tolnay42f50292016-09-04 13:54:21 -07004pub struct Ident(String);
5
6impl Ident {
7 pub fn new<T: Into<Ident>>(t: T) -> Self {
8 t.into()
9 }
10}
11
12impl<'a> From<&'a str> for Ident {
13 fn from(s: &str) -> Self {
14 Ident(s.to_owned())
15 }
16}
17
18impl From<String> for Ident {
19 fn from(s: String) -> Self {
20 Ident(s)
21 }
22}
23
David Tolnay26469072016-09-04 13:59:48 -070024impl AsRef<str> for Ident {
25 fn as_ref(&self) -> &str {
David Tolnay42f50292016-09-04 13:54:21 -070026 &self.0
27 }
28}
29
30impl Display for Ident {
31 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
32 self.0.fmt(formatter)
33 }
34}
David Tolnayb79ee962016-09-04 09:39:20 -070035
David Tolnay55337722016-09-11 12:58:56 -070036impl<T: ?Sized> PartialEq<T> for Ident where T: AsRef<str> {
37 fn eq(&self, other: &T) -> bool {
38 self.0 == other.as_ref()
39 }
David Tolnayb79ee962016-09-04 09:39:20 -070040}
41
David Tolnay86eca752016-09-04 11:26:41 -070042#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -070043pub mod parsing {
44 use super::*;
David Tolnayf6ccb832016-09-04 15:00:56 -070045 use nom::multispace;
David Tolnay9d8f1972016-09-04 11:58:48 -070046
47 fn ident_ch(ch: char) -> bool {
48 ch.is_alphanumeric() || ch == '_'
49 }
50
David Tolnayb5a7b142016-09-13 22:46:39 -070051 named!(pub ident -> Ident, preceded!(
David Tolnayf6ccb832016-09-04 15:00:56 -070052 option!(multispace),
David Tolnayb5a7b142016-09-13 22:46:39 -070053 map!(take_while1!(ident_ch), Into::into)
David Tolnay9d8f1972016-09-04 11:58:48 -070054 ));
David Tolnayb79ee962016-09-04 09:39:20 -070055}
David Tolnay26469072016-09-04 13:59:48 -070056
57#[cfg(feature = "printing")]
58mod printing {
59 use super::*;
60 use quote::{Tokens, ToTokens};
61
62 impl ToTokens for Ident {
63 fn to_tokens(&self, tokens: &mut Tokens) {
64 tokens.append(self.as_ref())
65 }
66 }
67}