use std::fmt;
use crate::json::quote;
#[derive(Clone, Default, PartialEq, Eq, Debug)]
pub(crate) struct Path(Vec<Step>);
#[derive(Clone, PartialEq, Eq, Debug)]
enum Step {
Name(String),
Index(usize),
Key(String),
}
impl Path {
pub(crate) fn name(&mut self, name: &str) {
self.0.push(Step::Name(name.to_owned()));
}
pub(crate) fn index(&mut self, index: usize) {
self.0.push(Step::Index(index));
}
pub(crate) fn key(&mut self, key: &str) {
self.0.push(Step::Key(key.to_owned()));
}
pub(crate) fn pop(&mut self) {
self.0.pop();
}
}
impl fmt::Display for Path {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (at, step) in self.0.iter().enumerate() {
match step {
Step::Name(name) if at == 0 => f.write_str(name)?,
Step::Name(name) => write!(f, ".{name}")?,
Step::Index(index) => write!(f, "[{index}]")?,
Step::Key(key) => write!(f, "[{}]", quote(key))?,
}
}
Ok(())
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct DecodeError {
pub path: String,
pub problem: String,
pub kind: DecodeErrorKind,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum DecodeErrorKind {
Invalid,
Limit,
}
impl DecodeError {
pub(crate) fn new(path: &Path, problem: String) -> Self {
DecodeError {
path: path.to_string(),
problem,
kind: DecodeErrorKind::Invalid,
}
}
pub(crate) fn limited(path: &Path, problem: String) -> Self {
DecodeError {
path: path.to_string(),
problem,
kind: DecodeErrorKind::Limit,
}
}
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.path.is_empty() {
write!(f, "the value {}", self.problem)
} else {
write!(f, "`{}` {}", self.path, self.problem)
}
}
}
impl std::error::Error for DecodeError {}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct EncodeError {
pub path: String,
pub problem: String,
}
impl EncodeError {
pub(crate) fn new(path: &Path, problem: impl Into<String>) -> Self {
EncodeError {
path: path.to_string(),
problem: problem.into(),
}
}
}
impl fmt::Display for EncodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.path.is_empty() {
write!(f, "the value {}", self.problem)
} else {
write!(f, "`{}` {}", self.path, self.problem)
}
}
}
impl std::error::Error for EncodeError {}