refactor: make all flex stuff use serde

This commit is contained in:
Nova
2022-10-13 00:14:06 -04:00
parent 9d9d51ddeb
commit a421b27e0c
22 changed files with 460 additions and 431 deletions

View File

@@ -1,4 +1,5 @@
use anyhow::bail;
use anyhow::anyhow;
use serde::{de::Visitor, Deserialize};
use std::path::PathBuf;
pub enum ResourceID {
@@ -24,20 +25,47 @@ impl ResourceID {
}
}
}
pub fn parse_resource_id(reader: flexbuffers::Reader<&[u8]>) -> anyhow::Result<ResourceID> {
let string = reader.get_str()?;
Ok(if string.starts_with('/') {
let path = PathBuf::from(string);
path.metadata()?;
ResourceID::File(path)
} else if let Some((namespace, path)) = string.split_once(':') {
ResourceID::Namespaced {
namespace: namespace.to_string(),
path: PathBuf::from(path),
}
} else {
bail!("Invalid format for string");
})
impl<'de> Deserialize<'de> for ResourceID {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_any(ResourceVisitor)
}
}
struct ResourceVisitor;
impl<'de> Visitor<'de> for ResourceVisitor {
type Value = ResourceID;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("A string containing an absolute path to file or \"[namespace]:[path]\" for a namespaced resource")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(if v.starts_with('/') {
let path = PathBuf::from(v);
path.metadata().map_err(serde::de::Error::custom)?;
ResourceID::File(path)
} else if let Some((namespace, path)) = v.split_once(':') {
ResourceID::Namespaced {
namespace: namespace.to_string(),
path: PathBuf::from(path),
}
} else {
return Err(serde::de::Error::custom(anyhow!(
"Invalid format for string"
)));
})
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_str(&v)
}
}