use std::fmt;
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SyntaxError {
pub line: u32,
pub msg: Vec<u8>,
}
impl SyntaxError {
pub fn new(line: u32, msg: impl Into<Vec<u8>>) -> Self {
SyntaxError {
line,
msg: msg.into(),
}
}
pub fn unpositioned(msg: impl Into<Vec<u8>>) -> Self {
SyntaxError {
line: 0,
msg: msg.into(),
}
}
pub fn render(&self, chunkid: &[u8]) -> Vec<u8> {
if self.line == 0 {
return self.msg.clone();
}
let mut out = chunkid.to_vec();
out.push(b':');
out.extend_from_slice(self.line.to_string().as_bytes());
out.extend_from_slice(b": ");
out.extend_from_slice(&self.msg);
out
}
pub fn msg_str(&self) -> std::borrow::Cow<'_, str> {
String::from_utf8_lossy(&self.msg)
}
}
impl fmt::Display for SyntaxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.line == 0 {
return f.write_str(&self.msg_str());
}
write!(f, "{}: {}", self.line, self.msg_str())
}
}
impl std::error::Error for SyntaxError {}