use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum JsonRepairErrorKind {
UnexpectedEnd,
UnexpectedCharacter,
InvalidUnicode,
ObjectKeyExpected,
ColonExpected,
MaxDepthExceeded,
InvalidCharacter,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct JsonRepairError {
pub message: String,
pub position: usize,
pub kind: JsonRepairErrorKind,
pub line: usize,
pub column: usize,
}
impl JsonRepairError {
pub fn new(message: impl Into<String>, position: usize) -> Self {
Self {
message: message.into(),
position,
kind: JsonRepairErrorKind::UnexpectedCharacter,
line: 0,
column: 0,
}
}
pub fn with_kind(
message: impl Into<String>,
position: usize,
kind: JsonRepairErrorKind,
) -> Self {
Self {
message: message.into(),
position,
kind,
line: 0,
column: 0,
}
}
pub(crate) fn with_location(mut self, line: usize, column: usize) -> Self {
self.line = line;
self.column = column;
self
}
}
impl fmt::Display for JsonRepairError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.line > 0 {
write!(
f,
"JSON repair error at position {} (line {}, col {}): {}",
self.position, self.line, self.column, self.message
)
} else {
write!(
f,
"JSON repair error at position {}: {}",
self.position, self.message
)
}
}
}
impl std::error::Error for JsonRepairError {}