Skip to main content

azalea_core/
identifier.rs

1//! An arbitrary identifier or resource location.
2
3use std::{
4    borrow::Cow,
5    cmp,
6    fmt::{self, Debug, Display},
7    hash::{Hash, Hasher},
8    io::{self, Cursor, Write},
9    num::NonZeroUsize,
10    str::FromStr,
11};
12
13use azalea_buf::{AzBuf, BufReadError};
14use azalea_codec::{Codec, error::ReadError};
15
16/// An identifier, like `minecraft:stone` or `brigadier:number`.
17///
18/// All registry variants can be converted to an identifier.
19///
20/// This was formerly called a `ResourceLocation`.
21#[doc(alias = "ResourceLocation")]
22#[derive(Clone, Eq)]
23pub enum Identifier {
24    Owned {
25        // empty namespaces aren't allowed, so NonZero is fine
26        colon_index: Option<NonZeroUsize>,
27        inner: Box<str>,
28    },
29    Static(IdentifierRef<'static>),
30}
31const _: () = assert!(size_of::<Identifier>() == 24);
32#[derive(Clone, Copy, Eq, PartialEq, Debug)]
33pub struct IdentifierRef<'a>(
34    // this string is required to be include a namespace
35    &'a str,
36);
37
38impl Default for Identifier {
39    fn default() -> Self {
40        Self::Static(Default::default())
41    }
42}
43impl Default for IdentifierRef<'static> {
44    fn default() -> Self {
45        Self("minecraft:")
46    }
47}
48
49static DEFAULT_NAMESPACE: &str = "minecraft";
50// static REALMS_NAMESPACE: &str = "realms";
51
52impl Identifier {
53    pub fn new(resource_string: impl Into<String>) -> Identifier {
54        let mut resource_string = resource_string.into();
55
56        let colon_index = resource_string.find(':');
57        let colon_index = if let Some(colon_index) = colon_index {
58            if colon_index == 0 {
59                resource_string = resource_string.split_off(1);
60            }
61            NonZeroUsize::new(colon_index)
62        } else {
63            None
64        };
65
66        Self::Owned {
67            colon_index,
68            inner: resource_string.into(),
69        }
70    }
71    pub fn new_from_parts(namespace: &str, path: &str) -> Self {
72        Self::new(format!("{namespace}:{path}"))
73    }
74    pub const fn const_new(s: &'static str) -> Self {
75        Self::Static(IdentifierRef::new(s))
76    }
77
78    pub fn namespace(&self) -> &str {
79        match self {
80            Self::Owned {
81                colon_index: Some(colon_index),
82                inner,
83            } => &inner[..colon_index.get()],
84            Self::Owned {
85                colon_index: None, ..
86            } => DEFAULT_NAMESPACE,
87            Self::Static(s) => s.namespace(),
88        }
89    }
90    pub fn path(&self) -> &str {
91        match self {
92            Self::Owned {
93                colon_index: Some(colon_index),
94                inner,
95            } => &inner[(colon_index.get() + 1)..],
96            Self::Owned {
97                colon_index: None,
98                inner,
99            } => inner,
100            Self::Static(s) => s.path(),
101        }
102    }
103
104    /// Returns the identifier as it is stored, with a boolean indicating
105    /// whether or not there's a namespace present.
106    pub fn as_ref(&self) -> (bool, &str) {
107        match self {
108            Identifier::Owned { colon_index, inner } => (colon_index.is_some(), inner),
109            Identifier::Static(identifier_ref) => (true, identifier_ref.0),
110        }
111    }
112    /// Returns a fully-qualified identifier string with both namespace and
113    /// path.
114    pub fn to_cow<'a>(&'a self) -> Cow<'a, str> {
115        match self {
116            Identifier::Owned { colon_index, inner } => {
117                if colon_index.is_some() {
118                    Cow::Borrowed(inner)
119                } else {
120                    Cow::Owned(self.to_string())
121                }
122            }
123            Identifier::Static(identifier_ref) => Cow::Borrowed(identifier_ref.0),
124        }
125    }
126}
127impl<'a> IdentifierRef<'a> {
128    pub const fn new(s: &'a str) -> Self {
129        let s = Self(s);
130        // validate that it contains a colon
131        s.colon_index();
132        s
133    }
134    pub fn namespace(self) -> &'a str {
135        str::from_utf8(&self.0.as_bytes()[..self.colon_index()]).unwrap()
136    }
137    pub fn path(self) -> &'a str {
138        str::from_utf8(&self.0.as_bytes()[(self.colon_index() + 1)..]).unwrap()
139    }
140    pub const fn colon_index(self) -> usize {
141        let bytes = self.0.as_bytes();
142        assert!(bytes.is_ascii(), "static identifiers must be valid ascii");
143
144        // namespace isn't allowed to be the first character
145        let mut idx = 1;
146        while idx < bytes.len() {
147            if bytes[idx] == b':' {
148                return idx;
149            }
150            idx += 1;
151        }
152        panic!("static identifiers must contain a namespace.");
153    }
154}
155
156impl PartialEq for Identifier {
157    fn eq(&self, other: &Self) -> bool {
158        self.namespace() == other.namespace() && self.path() == other.path()
159    }
160}
161impl Hash for Identifier {
162    fn hash<H: Hasher>(&self, state: &mut H) {
163        let namespace = self.namespace();
164        if namespace != DEFAULT_NAMESPACE {
165            namespace.hash(state);
166        }
167        self.path().hash(state);
168    }
169}
170
171impl Display for Identifier {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        match self {
174            Self::Owned {
175                colon_index: None,
176                inner,
177            } => {
178                write!(f, "{DEFAULT_NAMESPACE}:{inner}")
179            }
180            Self::Owned { inner, .. } => {
181                write!(f, "{inner}")
182            }
183            Self::Static(s) => Display::fmt(s, f),
184        }
185    }
186}
187impl Display for IdentifierRef<'_> {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        Display::fmt(self.0, f)
190    }
191}
192
193impl Debug for Identifier {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        write!(f, "{self}")
196    }
197}
198impl FromStr for Identifier {
199    type Err = &'static str;
200
201    fn from_str(s: &str) -> Result<Self, Self::Err> {
202        Ok(Identifier::new(s))
203    }
204}
205impl From<&str> for Identifier {
206    fn from(s: &str) -> Self {
207        Identifier::new(s)
208    }
209}
210
211impl AzBuf for Identifier {
212    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
213        let location_string = String::azalea_read(ctx, buf)?;
214        Ok(Identifier::new(&location_string))
215    }
216    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
217        self.to_string().azalea_write(ctx, buf)
218    }
219}
220
221impl<O: azalea_codec::Ops> Codec<O> for Identifier {
222    fn codec_read(ops: &O) -> azalea_codec::error::ReadResult<Self> {
223        ops.get_string()?
224            .parse()
225            .map_err(|_| ReadError::custom("invalid identifier"))
226    }
227    fn codec_write(&self) -> azalea_codec::error::WriteResult<O> {
228        self.to_string().codec_write()
229    }
230}
231impl PartialOrd for Identifier {
232    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
233        Some(self.cmp(other))
234    }
235}
236impl Ord for Identifier {
237    fn cmp(&self, other: &Self) -> cmp::Ordering {
238        self.to_cow().cmp(&other.to_cow())
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    #[test]
247    fn basic_identifier() {
248        let r = Identifier::new("abcdef:ghijkl");
249        assert_eq!(r.namespace(), "abcdef");
250        assert_eq!(r.path(), "ghijkl");
251    }
252    #[test]
253    fn no_namespace() {
254        let r = Identifier::new("azalea");
255        assert_eq!(r.namespace(), "minecraft");
256        assert_eq!(r.path(), "azalea");
257    }
258    #[test]
259    fn colon_start() {
260        let r = Identifier::new(":azalea");
261        assert_eq!(r.namespace(), "minecraft");
262        assert_eq!(r.path(), "azalea");
263    }
264    #[test]
265    fn colon_end() {
266        let r = Identifier::new("azalea:");
267        assert_eq!(r.namespace(), "azalea");
268        assert_eq!(r.path(), "");
269    }
270
271    #[test]
272    fn azbuf_identifier() {
273        let ctx = Default::default();
274
275        let mut buf = Vec::new();
276        Identifier::new("minecraft:dirt")
277            .azalea_write(ctx, &mut buf)
278            .unwrap();
279
280        let mut buf = Cursor::new(&buf[..]);
281
282        assert_eq!(
283            Identifier::azalea_read(Default::default(), &mut buf).unwrap(),
284            Identifier::new("minecraft:dirt")
285        );
286    }
287}