use super::{
super::{annotate::*, format::*, normal::*},
error::*,
};
use {kutil::std::immutable::*, std::io};
pub struct Parser {
pub format: Format,
pub source: Option<ByteString>,
pub try_integers: bool,
pub try_unsigned_integers: bool,
pub allow_legacy_words: bool,
pub allow_legacy_types: bool,
pub base64: bool,
}
impl Parser {
pub fn new(format: Format) -> Self {
Self {
format,
source: None,
try_integers: false,
try_unsigned_integers: false,
allow_legacy_words: false,
allow_legacy_types: false,
base64: false,
}
}
pub fn with_format(mut self, format: Format) -> Self {
self.format = format;
self
}
pub fn with_source(mut self, source: ByteString) -> Self {
self.source = Some(source);
self
}
pub fn with_try_integers(mut self, allow_integers: bool) -> Self {
self.try_integers = allow_integers;
if !allow_integers {
self.try_unsigned_integers = false;
}
self
}
pub fn with_try_unsigned_integers(mut self, allow_unsigned_integers: bool) -> Self {
self.try_unsigned_integers = allow_unsigned_integers;
if allow_unsigned_integers {
self.try_integers = true;
}
self
}
pub fn with_allow_legacy_words(mut self, allow_legacy_words: bool) -> Self {
self.allow_legacy_words = allow_legacy_words;
self
}
pub fn with_allow_legacy_types(mut self, allow_legacy_types: bool) -> Self {
self.allow_legacy_types = allow_legacy_types;
self
}
pub fn with_base64(mut self, base64: bool) -> Self {
self.base64 = base64;
self
}
#[allow(unused_variables)]
pub fn parse_reader<ReadT, AnnotatedT>(&self, reader: &mut ReadT) -> Result<Variant<AnnotatedT>, ParseError>
where
ReadT: io::Read,
AnnotatedT: Annotated + Clone + Default,
{
match &self.format {
#[cfg(feature = "cbor")]
Format::CBOR => self.parse_cbor(reader),
#[cfg(feature = "messagepack")]
Format::MessagePack => self.parse_message_pack(reader),
#[cfg(feature = "yaml")]
Format::YAML => self.parse_yaml(reader),
#[cfg(feature = "json")]
Format::JSON => self.parse_json(reader),
#[cfg(feature = "json")]
Format::XJSON => self.parse_xjson(reader),
#[cfg(feature = "xml")]
Format::XML => todo!(),
#[cfg(not(all(
feature = "cbor",
feature = "messagepack",
feature = "yaml",
feature = "json",
feature = "xml",
)))]
_ => Err(ParseError::UnsupportedFormat(self.format.clone())),
}
}
pub fn parse_bytes<AnnotatedT>(&self, bytes: &[u8]) -> Result<Variant<AnnotatedT>, ParseError>
where
AnnotatedT: Annotated + Clone + Default,
{
self.parse_reader(&mut io::Cursor::new(bytes))
}
pub fn parse_string<AnnotatedT>(&self, string: &str) -> Result<Variant<AnnotatedT>, ParseError>
where
AnnotatedT: Annotated + Clone + Default,
{
self.parse_reader(&mut string.as_bytes())
}
#[allow(dead_code)]
pub(crate) fn base64_reader<ReadT>(
reader: &mut ReadT,
) -> base64::read::DecoderReader<'_, base64::engine::GeneralPurpose, &mut ReadT>
where
ReadT: io::Read,
{
base64::read::DecoderReader::new(reader, &base64::prelude::BASE64_STANDARD)
}
}