protobuf_parse/
protobuf_ident.rs

1#![doc(hidden)]
2
3use std::fmt;
4use std::mem;
5use std::ops::Deref;
6
7/// Identifier in `.proto` file
8#[derive(Eq, PartialEq, Debug, Clone, Hash)]
9#[doc(hidden)]
10pub struct ProtobufIdent(String);
11
12#[derive(Eq, PartialEq, Debug, Hash)]
13#[doc(hidden)]
14#[repr(transparent)]
15pub struct ProtobufIdentRef(str);
16
17impl Deref for ProtobufIdentRef {
18    type Target = str;
19
20    fn deref(&self) -> &str {
21        &self.0
22    }
23}
24
25impl Deref for ProtobufIdent {
26    type Target = ProtobufIdentRef;
27
28    fn deref(&self) -> &ProtobufIdentRef {
29        ProtobufIdentRef::new(&self.0)
30    }
31}
32
33impl From<&'_ str> for ProtobufIdent {
34    fn from(s: &str) -> Self {
35        ProtobufIdent::new(s)
36    }
37}
38
39impl From<String> for ProtobufIdent {
40    fn from(s: String) -> Self {
41        ProtobufIdent::new(&s)
42    }
43}
44
45impl Into<String> for ProtobufIdent {
46    fn into(self) -> String {
47        self.0
48    }
49}
50
51impl fmt::Display for ProtobufIdent {
52    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53        fmt::Display::fmt(&self.get(), f)
54    }
55}
56
57impl ProtobufIdentRef {
58    pub fn new<'a>(ident: &'a str) -> &'a ProtobufIdentRef {
59        assert!(!ident.is_empty());
60        // SAFETY: ProtobufIdentRef is repr(transparent)
61        unsafe { mem::transmute(ident) }
62    }
63
64    pub fn as_str(&self) -> &str {
65        &*self
66    }
67
68    pub fn to_owned(&self) -> ProtobufIdent {
69        ProtobufIdent(self.0.to_owned())
70    }
71}
72
73impl ProtobufIdent {
74    pub fn as_ref(&self) -> &ProtobufIdentRef {
75        ProtobufIdentRef::new(&self.0)
76    }
77
78    pub fn new(s: &str) -> ProtobufIdent {
79        assert!(!s.is_empty());
80        assert!(!s.contains("/"));
81        assert!(!s.contains("."));
82        assert!(!s.contains(":"));
83        assert!(!s.contains("("));
84        assert!(!s.contains(")"));
85        ProtobufIdent(s.to_owned())
86    }
87
88    pub fn get(&self) -> &str {
89        &self.0
90    }
91
92    pub fn into_string(self) -> String {
93        self.0
94    }
95}