wit_encoder/
ident.rs

1use std::{borrow::Cow, fmt};
2
3#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
4#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
5#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
6pub struct Ident(Cow<'static, str>);
7
8impl Ident {
9    pub fn new(s: impl Into<Cow<'static, str>>) -> Self {
10        Self(s.into())
11    }
12
13    /// Get the name without escaping keywords with '%'
14    pub fn raw_name(&self) -> &str {
15        self.0.as_ref()
16    }
17}
18
19impl<S> From<S> for Ident
20where
21    S: Into<Cow<'static, str>>,
22{
23    fn from(value: S) -> Self {
24        Self::new(value)
25    }
26}
27
28impl fmt::Display for Ident {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        if is_keyword(&self.0) {
31            write!(f, "%")?;
32        }
33        self.0.fmt(f)
34    }
35}
36
37impl AsRef<str> for Ident {
38    fn as_ref(&self) -> &str {
39        self.0.as_ref()
40    }
41}
42
43fn is_keyword(name: &str) -> bool {
44    match name {
45        "u8" | "u16" | "u32" | "u64" | "s8" | "s16" | "s32" | "s64" | "f32" | "f64" | "char"
46        | "bool" | "string" | "tuple" | "list" | "option" | "result" | "use" | "type"
47        | "resource" | "func" | "record" | "enum" | "flags" | "variant" | "static"
48        | "interface" | "world" | "import" | "export" | "package" | "own" | "borrow" | "future"
49        | "stream" | "constructor" | "with" | "from" | "as" | "include" | "error-context"
50        | "async" => true,
51        _ => false,
52    }
53}