use crate::{invalid_data, BoxError};
use alloc::{string::String, vec::Vec};
use ciborium_io::Read;
use ciborium_ll::{simple, tag, Decoder, Error, Header};
use core::fmt::{self, Formatter};
use jaq_json::{Num, Val};
use num_bigint::{BigInt, BigUint};
use std::io;
const BUF_SIZE: usize = 4096;
const MAX_CAP: usize = 1024;
trait IsEof {
fn is_eof(&self) -> bool;
}
impl IsEof for std::io::Error {
fn is_eof(&self) -> bool {
matches!(self.kind(), std::io::ErrorKind::UnexpectedEof)
}
}
#[derive(Debug)]
enum PError<E> {
Lex(Error<E>),
Simple(u8),
Tag(u64),
Break,
}
impl<E: fmt::Debug + fmt::Display> std::error::Error for PError<E> {}
impl<E> From<Error<E>> for PError<E> {
fn from(e: Error<E>) -> Self {
Self::Lex(e)
}
}
impl<E: fmt::Display> fmt::Display for PError<E> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Lex(Error::Io(e)) => e.fmt(f),
Self::Lex(Error::Syntax(offset)) => write!(f, "lexing failed at byte {offset}"),
Self::Simple(s) => write!(f, "unsupported simple value: {s}"),
Self::Tag(t) => write!(f, "unsupported tag: {t}"),
Self::Break => write!(f, "unexpected break"),
}
}
}
impl From<PError<io::Error>> for io::Error {
fn from(e: PError<io::Error>) -> Self {
match e {
PError::Lex(Error::Io(e)) => e,
e => invalid_data(e),
}
}
}
pub fn parse_many(b: &[u8]) -> impl Iterator<Item = Result<Val, BoxError>> + '_ {
decode_many(b).map(|r| r.map_err(Into::into))
}
pub fn read_many(read: impl io::Read) -> impl Iterator<Item = io::Result<Val>> {
decode_many(read).map(|r| r.map_err(Into::into))
}
fn decode_many<R: Read>(read: R) -> impl Iterator<Item = Result<Val, PError<R::Error>>>
where
R::Error: IsEof,
{
let mut decoder = Decoder::from(read);
core::iter::from_fn(move || {
let offset = decoder.offset();
match decoder.pull() {
Ok(header) => Some(parse(header, &mut decoder)),
Err(Error::Io(e)) if e.is_eof() && offset == decoder.offset() => None,
Err(e) => Some(Err(e.into())),
}
})
}
fn with_size<R: Read, T>(
size: Option<usize>,
decoder: &mut Decoder<R>,
f: impl Fn(Header, &mut Decoder<R>) -> Result<T, PError<R::Error>>,
) -> Result<Vec<T>, PError<R::Error>> {
let mut a;
if let Some(size) = size {
a = Vec::with_capacity(size.min(MAX_CAP));
for _ in 0..size {
a.push(f(decoder.pull()?, decoder)?);
}
} else {
a = Vec::new();
loop {
match decoder.pull()? {
Header::Break => break,
header => a.push(f(header, decoder)?),
}
}
}
a.shrink_to_fit();
Ok(a)
}
fn parse_str<R: Read>(
len: Option<usize>,
decoder: &mut Decoder<R>,
) -> Result<String, Error<R::Error>> {
let mut s = len.map_or_else(String::new, |c| String::with_capacity(c.min(MAX_CAP)));
let mut segments = decoder.text(len);
while let Some(mut segment) = segments.pull()? {
let mut buffer = [0; BUF_SIZE];
while let Some(chunk) = segment.pull(&mut buffer[..])? {
s.push_str(chunk);
}
}
s.shrink_to_fit();
Ok(s)
}
fn parse_bytes<R: Read>(
len: Option<usize>,
decoder: &mut Decoder<R>,
) -> Result<Vec<u8>, Error<R::Error>> {
let mut b = len.map_or_else(Vec::new, |c| Vec::with_capacity(c.min(MAX_CAP)));
let mut segments = decoder.bytes(len);
while let Some(mut segment) = segments.pull()? {
let mut buffer = [0; BUF_SIZE];
while let Some(chunk) = segment.pull(&mut buffer)? {
b.extend(chunk);
}
}
b.shrink_to_fit();
Ok(b)
}
fn biguint<R: Read>(decoder: &mut Decoder<R>) -> Result<BigUint, Error<R::Error>> {
match decoder.pull()? {
Header::Bytes(len) => Ok(BigUint::from_bytes_be(&parse_bytes(len, decoder)?)),
_ => Err(Error::Syntax(decoder.offset())),
}
}
fn parse<R: Read>(header: Header, decoder: &mut Decoder<R>) -> Result<Val, PError<R::Error>> {
match header {
Header::Text(len) => Ok(Val::from(parse_str(len, decoder)?)),
Header::Bytes(len) => Ok(Val::byte_str(parse_bytes(len, decoder)?)),
Header::Simple(simple::NULL) => Ok(Val::Null),
Header::Simple(simple::FALSE) => Ok(Val::Bool(false)),
Header::Simple(simple::TRUE) => Ok(Val::Bool(true)),
Header::Simple(simple) => Err(PError::Simple(simple)),
Header::Tag(tag::BIGNEG) => {
Ok(biguint(decoder).map(|u| Val::Num(Num::big_int(-BigInt::from(u) - 1)))?)
}
Header::Tag(tag::BIGPOS) => {
Ok(biguint(decoder).map(|u| Val::Num(Num::big_int(BigInt::from(u))))?)
}
Header::Tag(tag) => Err(PError::Tag(tag)),
Header::Positive(pos) => Ok(Val::Num(Num::from_integral(pos))),
Header::Negative(neg) => Ok(Val::Num(Num::from_integral(neg as i128 ^ !0))),
Header::Float(f) => Ok(Val::from(f)),
Header::Array(size) => Ok(Val::Arr(
with_size(size, decoder, |h, d| parse(h, d))?.into(),
)),
Header::Map(size) => {
let o = with_size(size, decoder, |h, d| {
Ok((parse(h, d)?, parse(d.pull()?, d)?))
})?;
Ok(Val::obj(o.into_iter().collect()))
}
Header::Break => Err(PError::Break),
}
}