preserves/implementations/rust/src/value/decoder.rs

50 lines
1.3 KiB
Rust

use std::marker::PhantomData;
use super::packed::PackedReader;
use super::reader::{self, Reader};
use super::value::IOValue;
pub use super::reader::IOResult as Result;
pub struct Decoder<'de, R: Reader<'de>> {
pub read: R,
read_annotations: bool,
phantom: PhantomData<&'de ()>,
}
pub fn from_bytes<'de>(bytes: &'de [u8]) ->
Decoder<'de, PackedReader<'de, reader::BytesBinarySource<'de>>>
{
Decoder::new(PackedReader::from_bytes(bytes))
}
pub fn from_read<'de, 'a, IOR: std::io::Read>(read: &'a mut IOR) ->
Decoder<'de, PackedReader<'de, reader::IOBinarySource<'a, IOR>>>
{
Decoder::new(PackedReader::from_read(read))
}
impl<'de, R: Reader<'de>> Decoder<'de, R> {
pub fn new(read: R) -> Self {
Decoder { read, read_annotations: true, phantom: PhantomData }
}
pub fn set_read_annotations(&mut self, read_annotations: bool) {
self.read_annotations = read_annotations
}
pub fn demand_next(&mut self) -> Result<IOValue> {
self.read.demand_next(self.read_annotations)
}
}
impl<'de, R: Reader<'de>> std::iter::Iterator for Decoder<'de, R> {
type Item = Result<IOValue>;
fn next(&mut self) -> Option<Self::Item> {
match self.read.next(self.read_annotations) {
Err(e) => Some(Err(e)),
Ok(None) => None,
Ok(Some(v)) => Some(Ok(v)),
}
}
}