Skip to main content

ferro_jtype/types/
class_name.rs

1use crate::NameError;
2
3/// A JVM internal class name.
4///
5/// Internal names use `/` as the package separator, for example
6/// `java/lang/String`, rather than Java source names such as
7/// `java.lang.String`.
8#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub struct ClassName(String);
10
11impl ClassName {
12    pub(crate) fn java_lang_string() -> Self {
13        Self("java/lang/String".to_owned())
14    }
15
16    pub(crate) fn java_lang_object() -> Self {
17        Self("java/lang/Object".to_owned())
18    }
19
20    pub(crate) fn java_lang_class() -> Self {
21        Self("java/lang/Class".to_owned())
22    }
23
24    pub(crate) fn java_lang_invoke_method_handle() -> Self {
25        Self("java/lang/invoke/MethodHandle".to_owned())
26    }
27
28    pub(crate) fn java_lang_invoke_method_type() -> Self {
29        Self("java/lang/invoke/MethodType".to_owned())
30    }
31
32    pub(crate) fn java_lang_throwable() -> Self {
33        Self("java/lang/Throwable".to_owned())
34    }
35
36    /// Parses and validates a JVM internal class name.
37    ///
38    /// Empty names and descriptor-only punctuation are rejected. The value is
39    /// otherwise preserved exactly as supplied.
40    pub fn parse(value: impl Into<String>) -> Result<Self, NameError> {
41        let value = value.into();
42
43        if value.is_empty() {
44            return Err(NameError::Empty);
45        }
46
47        if value
48            .chars()
49            .any(|character| matches!(character, '.' | ';' | '[' | '(' | ')'))
50        {
51            return Err(NameError::Invalid { value });
52        }
53
54        Ok(Self(value))
55    }
56
57    /// Returns the internal name as a string slice.
58    #[must_use]
59    pub fn as_str(&self) -> &str {
60        &self.0
61    }
62
63    /// Consumes this name and returns its owned string.
64    #[must_use]
65    pub fn into_string(self) -> String {
66        self.0
67    }
68}
69
70impl AsRef<str> for ClassName {
71    fn as_ref(&self) -> &str {
72        self.as_str()
73    }
74}
75
76impl std::fmt::Display for ClassName {
77    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        formatter.write_str(&self.0)
79    }
80}