Skip to main content

melodium_share/
identifier.rs

1use core::{
2    fmt::{Display, Formatter},
3    str::FromStr,
4};
5use melodium_common::descriptor::{Identifier as CommonIdentifier, Version};
6use serde::{Deserialize, Serialize};
7
8#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
9#[cfg_attr(feature = "webassembly", derive(tsify::Tsify))]
10#[cfg_attr(feature = "webassembly", tsify(into_wasm_abi, from_wasm_abi))]
11pub struct Identifier {
12    pub version: Option<String>,
13    pub path: Vec<String>,
14    pub name: String,
15}
16
17impl Identifier {
18    pub fn root(&self) -> &str {
19        self.path.first().map(|s| s.as_str()).unwrap_or("")
20    }
21
22    pub fn with_version(self, version: String) -> Self {
23        Self {
24            version: Some(version),
25            path: self.path,
26            name: self.name,
27        }
28    }
29}
30
31impl Display for Identifier {
32    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
33        let mut string = self.path.join("/");
34
35        string = string + "::" + &self.name;
36
37        write!(f, "{}", string)
38    }
39}
40
41impl From<&CommonIdentifier> for Identifier {
42    fn from(value: &CommonIdentifier) -> Self {
43        Self {
44            version: value.version().map(|v| v.to_string()),
45            name: value.name().to_string(),
46            path: value.path().clone(),
47        }
48    }
49}
50
51impl FromStr for Identifier {
52    type Err = ();
53
54    fn from_str(value: &str) -> Result<Self, Self::Err> {
55        match CommonIdentifier::from_str(value) {
56            Ok(id) => Ok(Self::from(&id)),
57            Err(_) => Err(()),
58        }
59    }
60}
61
62impl TryInto<CommonIdentifier> for &Identifier {
63    type Error = Self;
64
65    fn try_into(self) -> Result<CommonIdentifier, Self::Error> {
66        if let Some(version) = &self.version {
67            match Version::parse(version) {
68                Ok(version) => Ok(CommonIdentifier::new_versionned(
69                    &version,
70                    self.path.clone(),
71                    &self.name,
72                )),
73                Err(_) => Err(self),
74            }
75        } else {
76            Ok(CommonIdentifier::new(self.path.clone(), &self.name))
77        }
78    }
79}
80
81impl TryInto<CommonIdentifier> for Identifier {
82    type Error = Self;
83
84    fn try_into(self) -> Result<CommonIdentifier, Self::Error> {
85        if let Some(version) = &self.version {
86            match Version::parse(version) {
87                Ok(version) => Ok(CommonIdentifier::new_versionned(
88                    &version, self.path, &self.name,
89                )),
90                Err(_) => Err(self),
91            }
92        } else {
93            Ok(CommonIdentifier::new(self.path, &self.name))
94        }
95    }
96}