1use std::fmt;
4
5use crate::json::quote;
6
7#[derive(Clone, Default, PartialEq, Eq, Debug)]
15pub(crate) struct Path(Vec<Step>);
16
17#[derive(Clone, PartialEq, Eq, Debug)]
18enum Step {
19 Name(String),
20 Index(usize),
21 Key(String),
22}
23
24impl Path {
25 pub(crate) fn name(&mut self, name: &str) {
26 self.0.push(Step::Name(name.to_owned()));
27 }
28
29 pub(crate) fn index(&mut self, index: usize) {
30 self.0.push(Step::Index(index));
31 }
32
33 pub(crate) fn key(&mut self, key: &str) {
34 self.0.push(Step::Key(key.to_owned()));
35 }
36
37 pub(crate) fn pop(&mut self) {
38 self.0.pop();
39 }
40}
41
42impl fmt::Display for Path {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 for (at, step) in self.0.iter().enumerate() {
45 match step {
46 Step::Name(name) if at == 0 => f.write_str(name)?,
47 Step::Name(name) => write!(f, ".{name}")?,
48 Step::Index(index) => write!(f, "[{index}]")?,
49 Step::Key(key) => write!(f, "[{}]", quote(key))?,
50 }
51 }
52 Ok(())
53 }
54}
55
56#[derive(Clone, PartialEq, Eq, Debug)]
61pub struct DecodeError {
62 pub path: String,
65 pub problem: String,
67 pub kind: DecodeErrorKind,
70}
71
72#[derive(Clone, Copy, PartialEq, Eq, Debug)]
74pub enum DecodeErrorKind {
75 Invalid,
77 Limit,
79}
80
81impl DecodeError {
82 pub(crate) fn new(path: &Path, problem: String) -> Self {
83 DecodeError {
84 path: path.to_string(),
85 problem,
86 kind: DecodeErrorKind::Invalid,
87 }
88 }
89
90 pub(crate) fn limited(path: &Path, problem: String) -> Self {
91 DecodeError {
92 path: path.to_string(),
93 problem,
94 kind: DecodeErrorKind::Limit,
95 }
96 }
97}
98
99impl fmt::Display for DecodeError {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 if self.path.is_empty() {
102 write!(f, "the value {}", self.problem)
103 } else {
104 write!(f, "`{}` {}", self.path, self.problem)
105 }
106 }
107}
108
109impl std::error::Error for DecodeError {}
110
111#[derive(Clone, PartialEq, Eq, Debug)]
116pub struct EncodeError {
117 pub path: String,
119 pub problem: String,
121}
122
123impl EncodeError {
124 pub(crate) fn new(path: &Path, problem: impl Into<String>) -> Self {
125 EncodeError {
126 path: path.to_string(),
127 problem: problem.into(),
128 }
129 }
130}
131
132impl fmt::Display for EncodeError {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 if self.path.is_empty() {
135 write!(f, "the value {}", self.problem)
136 } else {
137 write!(f, "`{}` {}", self.path, self.problem)
138 }
139 }
140}
141
142impl std::error::Error for EncodeError {}