lib_ruby_parser/source/
decoder.rs1#[derive(Debug, PartialEq, Eq, Clone)]
4#[repr(C)]
5pub enum InputError {
6 UnsupportedEncoding(String),
10
11 DecodingError(String),
13}
14
15impl std::fmt::Display for InputError {
16 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 write!(f, "{:?}", self)
18 }
19}
20
21impl std::error::Error for InputError {}
22
23#[repr(C)]
25#[derive(Debug, PartialEq, Eq, Clone)]
26pub enum DecoderResult {
27 Ok(Vec<u8>),
29
30 Err(InputError),
32}
33
34impl DecoderResult {
35 pub(crate) fn into_result(self) -> Result<Vec<u8>, InputError> {
36 match self {
37 Self::Ok(value) => Ok(value),
38 Self::Err(err) => Err(err),
39 }
40 }
41}
42
43pub type DecoderFn = dyn Fn(String, Vec<u8>) -> DecoderResult;
66
67pub struct Decoder {
69 f: Box<DecoderFn>,
70}
71
72impl Decoder {
73 pub fn new(f: Box<DecoderFn>) -> Self {
75 Self { f }
76 }
77
78 pub(crate) fn call(&self, encoding: String, input: Vec<u8>) -> DecoderResult {
79 let f = &*self.f;
80 f(encoding, input)
81 }
82}
83
84impl std::fmt::Debug for Decoder {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 f.debug_struct("Decoder").finish()
87 }
88}
89
90pub fn decode_input(input: Vec<u8>, enc: String, decoder: &mut Option<Decoder>) -> DecoderResult {
91 match enc.to_uppercase().as_str() {
92 "UTF-8" | "ASCII-8BIT" | "BINARY" => DecoderResult::Ok(input),
93 _ => {
94 if let Some(f) = decoder.as_mut() {
95 f.call(enc, input)
96 } else {
97 DecoderResult::Err(InputError::UnsupportedEncoding(enc))
98 }
99 }
100 }
101}