rune_core/item/
component.rs

1use core::fmt;
2
3use serde::{Deserialize, Serialize};
4
5use crate::alloc;
6use crate::alloc::prelude::*;
7use crate::item::ComponentRef;
8
9/// The component of an item.
10///
11/// All indexes refer to sibling indexes. So two sibling id components could
12/// have the indexes `1` and `2` respectively.
13#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
14#[non_exhaustive]
15#[serde(rename_all = "snake_case", tag = "type")]
16pub enum Component {
17    /// A crate component.
18    Crate(Box<str>),
19    /// A regular string component.
20    Str(Box<str>),
21    /// A nested anonymous part with an identifier.
22    Id(usize),
23}
24
25impl Component {
26    /// Get the identifier of the component.
27    pub fn id(&self) -> Option<usize> {
28        match self {
29            Self::Id(n) => Some(*n),
30            _ => None,
31        }
32    }
33
34    /// Convert into component reference.
35    pub fn as_component_ref(&self) -> ComponentRef<'_> {
36        match self {
37            Self::Crate(s) => ComponentRef::Crate(s),
38            Self::Str(s) => ComponentRef::Str(s),
39            Self::Id(n) => ComponentRef::Id(*n),
40        }
41    }
42}
43
44impl TryClone for Component {
45    fn try_clone(&self) -> alloc::Result<Self> {
46        Ok(match self {
47            Component::Crate(string) => Component::Crate(string.try_clone()?),
48            Component::Str(string) => Component::Str(string.try_clone()?),
49            Component::Id(id) => Component::Id(*id),
50        })
51    }
52}
53
54impl fmt::Display for Component {
55    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            Self::Crate(s) => write!(fmt, "::{}", s),
58            Self::Str(s) => write!(fmt, "{}", s),
59            Self::Id(n) => write!(fmt, "${}", n),
60        }
61    }
62}