You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

92 lines
2.0 KiB

use core::fmt;
use std::fmt::Display;
use serde::{Deserialize, Serialize, de::Visitor};
use super::{StorePath, Hash};
#[derive(Clone, PartialEq, Eq)]
pub struct Path {
pub(super) hash: Hash,
name: String,
version: String,
}
impl From<StorePath> for Path {
fn from(store_path: StorePath) -> Self {
store_path.path
}
}
impl Display for Path {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}-{}-{}", self.hash, self.name, self.version)
}
}
impl fmt::Debug for Path {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}-{:?}-{:?}", self.hash, self.name, self.version)
}
}
struct PathVisitor;
impl<'de> Visitor<'de> for PathVisitor {
type Value = Path;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a nix path")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Self::Value::parse(v).ok_or(E::custom("Invalid path"))
}
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_str(v)
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_str(&v)
}
}
impl<'de> Deserialize<'de> for Path {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de> {
deserializer.deserialize_str(PathVisitor)
}
}
impl Serialize for Path {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer {
serializer.serialize_str(&self.to_string())
}
}
impl Path {
pub fn parse<S: AsRef<str>>(str: S) -> Option<Self> {
let splits = str.as_ref().split('-').collect::<Vec<_>>();
match splits.len() {
3 => Some(Self {
hash: Hash::parse(splits[0]).ok()?,
name: splits[1].into(),
version: splits[2].into()
}),
_ => None
}
}
}