#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AbstractResourceLocation {
InMemory,
RelativePath,
}
impl ToString for &AbstractResourceLocation {
fn to_string(&self) -> String {
match self {
AbstractResourceLocation::InMemory => "in-memory".to_string(),
AbstractResourceLocation::RelativePath => "filesystem-relative".to_string(),
}
}
}
impl TryFrom<&str> for AbstractResourceLocation {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"in-memory" => Ok(Self::InMemory),
"filesystem-relative" => Ok(Self::RelativePath),
_ => Err(format!("{} is not a valid resource location", value)),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConcreteResourceLocation {
InMemory,
RelativePath(String),
}
impl From<&ConcreteResourceLocation> for AbstractResourceLocation {
fn from(l: &ConcreteResourceLocation) -> Self {
match l {
ConcreteResourceLocation::InMemory => AbstractResourceLocation::InMemory,
ConcreteResourceLocation::RelativePath(_) => AbstractResourceLocation::RelativePath,
}
}
}
impl ToString for ConcreteResourceLocation {
fn to_string(&self) -> String {
match self {
ConcreteResourceLocation::InMemory => "in-memory".to_string(),
ConcreteResourceLocation::RelativePath(prefix) => {
format!("filesystem-relative:{}", prefix)
}
}
}
}
impl From<ConcreteResourceLocation> for String {
fn from(location: ConcreteResourceLocation) -> Self {
location.to_string()
}
}
impl TryFrom<&str> for ConcreteResourceLocation {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
if value == "in-memory" {
Ok(Self::InMemory)
} else {
let parts = value.splitn(2, ':').collect::<Vec<_>>();
if parts.len() != 2 {
Err(format!("{} is not a valid resource location", value))
} else {
let prefix = parts[0];
let suffix = parts[1];
if prefix == "filesystem-relative" {
Ok(Self::RelativePath(suffix.to_string()))
} else {
Err(format!("{} is not a valid resource location", value))
}
}
}
}
}
#[cfg(test)]
mod tests {
use {super::*, anyhow::Result};
#[test]
fn test_abstract_from_string() -> Result<()> {
assert_eq!(
AbstractResourceLocation::try_from("in-memory"),
Ok(AbstractResourceLocation::InMemory)
);
assert_eq!(
AbstractResourceLocation::try_from("filesystem-relative"),
Ok(AbstractResourceLocation::RelativePath)
);
Ok(())
}
#[test]
fn test_concrete_from_string() -> Result<()> {
assert_eq!(
ConcreteResourceLocation::try_from("in-memory"),
Ok(ConcreteResourceLocation::InMemory)
);
assert_eq!(
ConcreteResourceLocation::try_from("filesystem-relative:lib"),
Ok(ConcreteResourceLocation::RelativePath("lib".to_string()))
);
Ok(())
}
}