use core::fmt;
use crate::path::Path;
use crate::{Dynconfig, Result};
#[derive(Clone)]
pub struct Pair<'a>(pub Path<'a>, pub &'a str);
impl<'a> From<(Path<'a>, &'a str)> for Pair<'a> {
fn from(x: (Path<'a>, &'a str)) -> Self {
Self(x.0, x.1)
}
}
impl<'a> From<Pair<'a>> for (Path<'a>, &'a str) {
fn from(pair: Pair<'a>) -> Self {
(pair.0, pair.1)
}
}
impl<'a> Pair<'a> {
pub fn set_on<D>(&self, target: &mut D) -> Result<()>
where
D: Dynconfig,
{
let mut path = self.0.clone();
target.set(&mut path, self.1)
}
}
impl fmt::Debug for Pair<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\"{}={}\"", self.0.full(), self.1)
}
}
impl fmt::Display for Pair<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write!(f, "{} = {}", self.0.full(), self.1)
} else {
write!(f, "{}={}", self.0.full(), self.1)
}
}
}
#[derive(Debug, Clone)]
pub struct ParsePairError();
impl fmt::Display for ParsePairError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "missing '='")
}
}
impl core::error::Error for ParsePairError {}
impl<'a> TryFrom<&'a str> for Pair<'a> {
type Error = ParsePairError;
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
let Some((path, value)) = value.split_once('=') else {
return Err(ParsePairError());
};
let path = path.trim();
let path = Path::new(path);
let value = value.trim();
Ok(Self(path, value))
}
}
#[inline]
pub fn parse<'a>(x: &'a str) -> Result<Pair<'a>, ParsePairError> {
x.try_into()
}