1 use std::fmt;
2 
3 use crate::gen::rust::ident_with_path::RustIdentWithPath;
4 use crate::gen::rust::keywords::is_rust_keyword;
5 use crate::gen::rust::rel_path::RustRelativePath;
6 
7 /// Valid Rust identifier
8 #[derive(Eq, PartialEq, Debug, Clone, Hash)]
9 pub(crate) struct RustIdent(String);
10 
11 impl RustIdent {
new(s: &str) -> RustIdent12     pub fn new(s: &str) -> RustIdent {
13         assert!(!s.is_empty());
14         assert!(!s.contains("/"), "{}", s);
15         assert!(!s.contains("."), "{}", s);
16         assert!(!s.contains(":"), "{}", s);
17         assert!(!s.contains(" "), "{}", s);
18         assert!(!s.contains("#"), "{}", s);
19         RustIdent(s.to_owned())
20     }
21 
get(&self) -> &str22     pub(crate) fn get(&self) -> &str {
23         &self.0
24     }
25 
into_string(self) -> String26     pub fn into_string(self) -> String {
27         self.0
28     }
29 
to_path(&self) -> RustIdentWithPath30     pub fn to_path(&self) -> RustIdentWithPath {
31         RustIdentWithPath::from(&self.0)
32     }
33 
into_rel_path(self) -> RustRelativePath34     pub(crate) fn into_rel_path(self) -> RustRelativePath {
35         RustRelativePath::from_idents([self])
36     }
37 }
38 
39 impl fmt::Display for RustIdent {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result40     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
41         // Rust-protobuf uses `_` suffix to escape identifiers instead of raw identifiers
42         // because some identifiers cannot be escaped as raw identifiers,
43         // e.g. `r#self` is not a valid raw identifier.
44         if is_rust_keyword(&self.0) {
45             write!(f, "{}_", self.0)
46         } else {
47             write!(f, "{}", self.0)
48         }
49     }
50 }
51 
52 impl From<&'_ str> for RustIdent {
from(s: &str) -> Self53     fn from(s: &str) -> Self {
54         RustIdent::new(s)
55     }
56 }
57 
58 impl From<String> for RustIdent {
from(s: String) -> Self59     fn from(s: String) -> Self {
60         RustIdent::new(&s)
61     }
62 }
63