jsn 0.14.0

A library for querying streaming JSON tokens
Documentation
use std::default::Default;
use std::fmt::Display;
use std::io;

/// Current position in the input JSON input
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Position {
    /// Byte offset from start of the input
    pub offset: usize,
    /// Column number. First column is 1
    pub col: usize,
    /// Line number. First line is 1
    pub line: usize,
}

impl Default for Position {
    fn default() -> Self {
        Self {
            offset: 0,
            line: 1,
            col: 0,
        }
    }
}

impl Display for Position {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "offset:{} line:{} col:{}",
            self.offset, self.line, self.col
        )
    }
}

/// All the possible reasons parsing json might fail
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Reason {
    /// Failed to parse what looked like a number
    ExpectedNumber,

    /// Failed to parse what looked like a string
    ExpectedString,

    /// Failed to parse what looked like a boolean
    ExpectedBool,

    /// Failed to parse what looked like a null
    ExpectedNull,

    /// Unexpected control character in string
    UnexpectedCtrlChar,

    /// Encountered an invalid unicode/utf8 sequence while parsing a string
    InvalidUtf8,

    /// Invalid escape escape code in string
    InvalidEscapeCode,

    /// Unexpectedly reached end of file. Json is malformed
    UnexpectedEof,

    /// A character was not recognized as being part of a valid json construct
    UnexpectedChar,

    /// The read implementation was non-blocking, which is not supported
    NonBlockingRead,

    /// Failed to rewind a `Seek`able input.
    CouldNotRewindInput(io::ErrorKind),

    /// An unrecognized io-related error occured
    UnrecognizedIoError(io::ErrorKind),
}

/// Bundles the reason & location of a parsing error
#[derive(Debug, Copy, Clone, thiserror::Error, PartialEq, Eq)]
#[error("malformed json at position {position}")]
pub struct JsonError {
    /// The reason parsing failed
    pub reason: Reason,
    /// Position in the input at which parsing failed
    pub position: Position,
}

impl From<io::ErrorKind> for Reason {
    fn from(value: io::ErrorKind) -> Self {
        match value {
            io::ErrorKind::UnexpectedEof => Reason::UnexpectedEof,
            io::ErrorKind::WouldBlock => Reason::NonBlockingRead,
            _ => Reason::UnrecognizedIoError(value),
        }
    }
}