use crate::decode::Decoder;
use crate::encode::Encoder;
use crate::error::Error;
use crate::head::{self, Major};
pub const ENCODE_DEPTH_LIMIT: usize = 16;
impl Encoder<'_> {
pub fn begin_bytes(&mut self) -> Result<&mut Self, Error> {
self.begin(Major::Bytes)
}
pub fn begin_str(&mut self) -> Result<&mut Self, Error> {
self.begin(Major::Text)
}
pub fn begin_array(&mut self) -> Result<&mut Self, Error> {
self.begin(Major::Array)
}
pub fn begin_map(&mut self) -> Result<&mut Self, Error> {
self.begin(Major::Map)
}
fn begin(&mut self, major: Major) -> Result<&mut Self, Error> {
self.open_scope(major)?;
match self.reserve(1) {
Ok(()) => {}
Err(e) => {
self.indef_sp -= 1;
return Err(e);
}
}
self.buf[self.pos] = major.bits() | 0x1f;
self.pos += 1;
Ok(self)
}
pub fn bytes_chunk(&mut self, b: &[u8]) -> Result<&mut Self, Error> {
self.require_kind(Major::Bytes)?;
self.put_payload(Major::Bytes, b)?;
Ok(self)
}
pub fn str_chunk(&mut self, s: &str) -> Result<&mut Self, Error> {
self.require_kind(Major::Text)?;
self.put_payload(Major::Text, s.as_bytes())?;
Ok(self)
}
pub fn end_indef(&mut self) -> Result<&mut Self, Error> {
match self.pop_scope() {
Some(_) => {
self.write_break()?;
Ok(self)
}
None => Err(Error::TYPE_MISMATCH),
}
}
pub fn end_bytes(&mut self) -> Result<&mut Self, Error> {
self.end_of_kind(Major::Bytes)
}
pub fn end_str(&mut self) -> Result<&mut Self, Error> {
self.end_of_kind(Major::Text)
}
pub fn bytes_indef(&mut self, chunks: &[&[u8]]) -> Result<&mut Self, Error> {
self.begin_bytes()?;
for c in chunks {
self.bytes_chunk(c)?;
}
self.end_bytes()
}
pub fn str_indef(&mut self, chunks: &[&str]) -> Result<&mut Self, Error> {
self.begin_str()?;
for c in chunks {
self.str_chunk(c)?;
}
self.end_str()
}
fn end_of_kind(&mut self, major: Major) -> Result<&mut Self, Error> {
self.require_kind(major)?;
self.end_indef()
}
#[inline]
fn require_kind(&self, major: Major) -> Result<(), Error> {
match self.open_kind() == Some(major) {
true => Ok(()),
false => Err(Error::TYPE_MISMATCH),
}
}
#[inline]
fn open_scope(&mut self, major: Major) -> Result<(), Error> {
let sp = usize::from(self.indef_sp);
match sp < ENCODE_DEPTH_LIMIT {
true => {
self.indef[sp] = major as u8;
self.indef_sp += 1;
Ok(())
}
false => Err(Error::DEPTH_EXCEEDED),
}
}
#[inline]
fn open_kind(&self) -> Option<Major> {
match self.indef_sp {
0 => None,
n => Some(Major::from_initial(self.indef[usize::from(n) - 1] << 5)),
}
}
#[inline]
fn pop_scope(&mut self) -> Option<Major> {
let kind = self.open_kind();
self.indef_sp -= u8::from(kind.is_some());
kind
}
#[inline]
fn write_break(&mut self) -> Result<(), Error> {
self.reserve(1)?;
self.buf[self.pos] = head::BREAK;
self.pos += 1;
Ok(())
}
}
#[allow(clippy::copy_iterator)]
#[derive(Clone, Copy, Debug)]
pub struct StringChunks<'a, T> {
rest: &'a [u8],
state: State,
_marker: core::marker::PhantomData<fn() -> T>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
Open,
Broken,
Malformed,
}
impl<T> StringChunks<'_, T> {
#[must_use]
pub const fn finished(&self) -> bool {
matches!(self.state, State::Broken)
}
#[must_use]
pub const fn unconsumed(&self) -> usize {
self.rest.len()
}
}
#[allow(clippy::copy_iterator)]
impl<'a> Iterator for StringChunks<'a, &'a [u8]> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
self.advance(|rest| {
let mut dec = Decoder::new(rest);
let raw = dec.bytes_of(Major::Bytes).ok()?;
Some((raw, dec.position()))
})
}
}
#[allow(clippy::copy_iterator)]
impl<'a> Iterator for StringChunks<'a, &'a str> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
self.advance(|rest| {
let mut dec = Decoder::new(rest);
let raw = dec.bytes_of(Major::Text).ok()?;
let s = core::str::from_utf8(raw).ok()?;
Some((s, dec.position()))
})
}
}
impl<'a, T> StringChunks<'a, T> {
fn advance(&mut self, read: impl FnOnce(&'a [u8]) -> Option<(T, usize)>) -> Option<T> {
match self.state {
State::Open => {}
_ => return None,
}
match self.rest.first() {
Some(&b) if head::is_break(b) => {
self.rest = &self.rest[1..];
self.state = State::Broken;
None
}
None => {
self.state = State::Malformed;
None
}
Some(_) => match read(self.rest) {
Some((chunk, used)) => {
self.rest = &self.rest[used..];
Some(chunk)
}
None => {
self.state = State::Malformed;
None
}
},
}
}
}
impl<'a> Decoder<'a> {
pub fn bytes_chunks(&mut self) -> Result<StringChunks<'a, &'a [u8]>, Error> {
self.begin_chunks(Major::Bytes).map(|start| StringChunks {
rest: &self.input[start..],
state: State::Open,
_marker: core::marker::PhantomData,
})
}
pub fn str_chunks(&mut self) -> Result<StringChunks<'a, &'a str>, Error> {
self.begin_chunks(Major::Text).map(|start| StringChunks {
rest: &self.input[start..],
state: State::Open,
_marker: core::marker::PhantomData,
})
}
pub fn sync_chunks<T>(&mut self, it: &StringChunks<'a, T>) -> Result<(), Error> {
match it.finished() {
true => {}
false => return Err(Error::TRUNCATED),
}
self.pos = self.input.len() - it.rest.len();
Ok(())
}
#[inline]
fn begin_chunks(&mut self, want: Major) -> Result<usize, Error> {
let pos = self.pos;
let (major, _, indef) = self.next_head_ext()?;
match major == want && indef {
true => Ok(pos + 1),
false => Err(Error::TYPE_MISMATCH),
}
}
}