chisel_json/lexer/decoders.rs
1//! Both the DOM and SAX parser implementations operate over a stream of `char`s produced by some
2//! flavour of iterator. By default, this iterator is based on a decoder that will take a stream of
3//! bytes from an underlying source, and convert into a stream of `char`s.
4//!
5//! The [DecoderSelector] implemented within this module is used to instantiate new `char`
6//! iterators, based on different encodings. (Currently only ASCII and UTF-8 are supported).
7use std::io::BufRead;
8
9use chisel_decoders::{ascii::AsciiDecoder, utf8::Utf8Decoder};
10
11/// Enumeration of different supported encoding types
12#[derive(Copy, Clone)]
13pub enum Encoding {
14 Utf8,
15 Ascii,
16}
17
18impl Default for Encoding {
19 fn default() -> Self {
20 Self::Utf8
21 }
22}
23
24/// A struct that is essentially a factory for creating new instances of [char] iterators,
25/// based on a specified encoding type
26#[derive(Default)]
27pub(crate) struct DecoderSelector {}
28
29impl DecoderSelector {
30 /// Create and return an instance of the default byte decoder / char iterator. (Utf-8)
31 pub fn default_decoder<'a, Buffer: BufRead>(
32 &'a self,
33 buffer: &'a mut Buffer,
34 ) -> Box<dyn Iterator<Item = char> + 'a> {
35 Box::new(Utf8Decoder::new(buffer))
36 }
37
38 /// Create and return an instance of a given byte decoder / char iterator based on a specific
39 /// encoding
40 pub fn new_decoder<'a, Buffer: BufRead>(
41 &'a self,
42 buffer: &'a mut Buffer,
43 encoding: Encoding,
44 ) -> Box<dyn Iterator<Item = char> + 'a> {
45 match encoding {
46 Encoding::Ascii => Box::new(AsciiDecoder::new(buffer)),
47 Encoding::Utf8 => Box::new(Utf8Decoder::new(buffer)),
48 }
49 }
50}