1pub use crate::parser::common::ParseError;
12use crate::{highlevel, lowlevel};
13use std::io;
14use thiserror::Error;
15
16#[derive(Clone, Debug, Error, PartialEq)]
19pub enum DeserializeErrorCause {
20 #[error("IO error: {0:?}")]
22 IoError(String),
23 #[error("Parse error: {0:?}")]
26 ParseError(String),
27 #[error("Bad UTF8: {0:?}")]
28 Utf8Error(std::str::Utf8Error),
29 #[error("Parsed unknown command: {0:?}")]
30 UnknownCommand(lowlevel::Command),
31 #[error("Parsed unknown response: {0:?}")]
32 UnknownResponse(lowlevel::Response),
33 #[error("Parsed arguments do not match argument definition: {0:?}")]
34 UnknownArguments(lowlevel::Arguments),
35}
36
37impl From<io::Error> for DeserializeErrorCause {
38 fn from(io_error: io::Error) -> DeserializeErrorCause {
39 let string = format!("{:?}", io_error);
40 DeserializeErrorCause::IoError(string)
41 }
42}
43
44impl<RT: pest::RuleType> From<Box<ParseError<RT>>> for DeserializeErrorCause {
45 fn from(parse_error: Box<ParseError<RT>>) -> DeserializeErrorCause {
46 let string = format!("{:?}", parse_error);
47 DeserializeErrorCause::ParseError(string)
48 }
49}
50
51impl From<std::str::Utf8Error> for DeserializeErrorCause {
52 fn from(utf8_error: std::str::Utf8Error) -> DeserializeErrorCause {
53 DeserializeErrorCause::Utf8Error(utf8_error)
54 }
55}
56
57#[derive(Clone, Debug, PartialEq)]
59pub struct DeserializeError {
60 pub cause: DeserializeErrorCause,
61 pub bytes: Vec<u8>,
62}
63
64#[derive(Debug, Error)]
65pub enum SerializeErrorCause {
66 #[error("IO error: {0:?}")]
67 IoError(io::Error),
68}
69
70impl From<io::Error> for SerializeErrorCause {
71 fn from(io_error: io::Error) -> SerializeErrorCause {
72 SerializeErrorCause::IoError(io_error)
73 }
74}
75
76pub(crate) mod internal {
81 use super::{DeserializeError, DeserializeErrorCause, ParseError, SerializeErrorCause};
82 use crate::lowlevel::write_to::WriteTo;
83 use crate::parser::{command_grammar, command_parser, response_grammar, response_parser};
84 use crate::{highlevel, lowlevel, translate};
85 use std::io;
86
87 pub trait SerDeMethods: Sized {
91 type Lowlevel: WriteTo;
92 type Rule: pest::RuleType;
93
94 fn parse(string: &str) -> Result<Self::Lowlevel, Box<ParseError<Self::Rule>>>;
95 fn raise(lowlevel: &Self::Lowlevel) -> Result<Self, DeserializeErrorCause>;
96 fn lower(&self) -> Self::Lowlevel;
97
98 fn write_to<W: io::Write>(sink: &mut W, lowlevel: &Self::Lowlevel) -> io::Result<()> {
99 lowlevel.write_to(sink)
100 }
101 }
102
103 impl SerDeMethods for highlevel::Command {
105 type Lowlevel = lowlevel::Command;
106 type Rule = command_grammar::Rule;
107
108 fn parse(string: &str) -> Result<lowlevel::Command, Box<ParseError<Self::Rule>>> {
109 command_parser::parse(string)
110 }
111
112 fn raise(lowlevel: &Self::Lowlevel) -> Result<Self, DeserializeErrorCause> {
113 translate::raise_command(lowlevel)
114 }
115
116 fn lower(&self) -> Self::Lowlevel {
117 translate::lower_command(self)
118 }
119 }
120
121 impl SerDeMethods for highlevel::Response {
123 type Lowlevel = lowlevel::Response;
124 type Rule = response_grammar::Rule;
125
126 fn parse(string: &str) -> Result<lowlevel::Response, Box<ParseError<Self::Rule>>> {
127 response_parser::parse(string)
128 }
129
130 fn raise(lowlevel: &Self::Lowlevel) -> Result<Self, DeserializeErrorCause> {
131 translate::raise_response(lowlevel)
132 }
133
134 fn lower(&self) -> Self::Lowlevel {
135 translate::lower_response(self)
136 }
137 }
138
139 pub trait SerDeOne: Sized {
143 fn deserialize_one<R: io::Read>(source: &mut R) -> Result<Self, Box<DeserializeError>>;
144 fn serialize_one<W: io::Write>(&self, sink: &mut W) -> Result<(), SerializeErrorCause>;
145 }
146
147 impl<T: SerDeMethods> SerDeOne for T {
150 fn deserialize_one<R: io::Read>(source: &mut R) -> Result<Self, Box<DeserializeError>> {
151 let mut bytes: Vec<u8> = Vec::new();
153
154 (|| {
155 let _byte_count = source.read_to_end(&mut bytes)?;
156 let string = std::str::from_utf8(&bytes)?;
157 let lowlevel = Self::parse(string)?;
158 Ok(Self::raise(&lowlevel)?)
159 })()
160 .map_err(|cause| Box::new(DeserializeError { cause, bytes }))
161 }
162
163 fn serialize_one<W: io::Write>(&self, sink: &mut W) -> Result<(), SerializeErrorCause> {
164 let lowlevel = Self::lower(self);
165 Self::write_to(sink, &lowlevel)?;
166
167 Ok(())
168 }
169 }
170} #[derive(Debug)]
175pub struct SerializeError<T> {
176 pub remaining: Vec<T>,
177 pub failed: T,
178 pub cause: SerializeErrorCause,
179}
180
181#[derive(Debug, PartialEq)]
183pub struct DeserializeBytes {
184 pub(crate) bytes: Vec<u8>,
186}
187
188impl DeserializeBytes {
189 fn add_bytes<R: io::Read>(&mut self, source: &mut R) -> Result<(), Box<DeserializeError>> {
192 let mut more_bytes = Vec::new();
193 let byte_count_result = source.read_to_end(&mut more_bytes);
194 self.bytes.append(&mut more_bytes);
195
196 match byte_count_result {
197 Ok(_byte_count) => Ok(()),
198 Err(err) => Err(Box::new(DeserializeError { cause: err.into(), bytes: more_bytes })),
199 }
200 }
201
202 fn from(bytes: &[u8]) -> Self {
203 DeserializeBytes { bytes: bytes.into() }
204 }
205
206 pub fn new() -> Self {
209 DeserializeBytes { bytes: Vec::new() }
210 }
211}
212
213impl Default for DeserializeBytes {
214 fn default() -> Self {
215 Self::new()
216 }
217}
218
219#[derive(Debug, PartialEq)]
222pub struct DeserializeResult<T> {
223 pub values: Vec<T>,
224 pub error: Option<Box<DeserializeError>>,
225 pub remaining_bytes: DeserializeBytes,
226}
227
228pub trait SerDe: Sized {
231 fn serialize<W: io::Write>(sink: &mut W, values: &[Self]) -> Result<(), SerializeError<Self>>;
232 fn deserialize<R: io::Read>(
233 source: &mut R,
234 existing_bytes: DeserializeBytes,
235 ) -> DeserializeResult<Self>;
236}
237
238impl<T: internal::SerDeOne + Clone> SerDe for T {
242 fn serialize<W: io::Write>(sink: &mut W, values: &[Self]) -> Result<(), SerializeError<Self>> {
243 let mut iter = values.iter();
244 for value in &mut iter {
245 match value.serialize_one(sink) {
246 Ok(()) => (),
247 Err(cause) => {
248 return Err(SerializeError {
249 remaining: iter.cloned().collect(),
250 failed: value.clone(),
251 cause,
252 })
253 }
254 }
255 }
256 Ok(())
257 }
258
259 fn deserialize<R: io::Read>(
260 source: &mut R,
261 mut existing_bytes: DeserializeBytes,
262 ) -> DeserializeResult<T> {
263 let mut values = Vec::new();
264 if let Err(error) = existing_bytes.add_bytes(source) {
265 return DeserializeResult {
266 values,
267 error: Some(error),
268 remaining_bytes: existing_bytes,
269 };
270 }
271 let mut beginning = 0;
272 let mut end = 0;
273 let bytes = &existing_bytes.bytes;
274 let len = bytes.len();
275 let should_split = |b| b == &b'\n' || b == &b'\r';
276 let is_not_whitespace = |b| !should_split(b);
277 loop {
278 end += 1;
279 if end >= len {
280 break;
281 };
282 if !(should_split(&bytes[end])) {
283 continue;
284 }
285 let mut slice = &bytes[beginning..end];
286 if slice.is_empty() || slice.iter().position(is_not_whitespace).is_none() {
288 beginning = end;
289 continue;
290 }
291
292 let value_result = T::deserialize_one(&mut slice);
293 match value_result {
294 Ok(value) => values.push(value),
295 Err(error) => {
296 return DeserializeResult {
299 values,
300 error: Some(error),
301 remaining_bytes: DeserializeBytes::from(&bytes[end..]),
302 };
303 }
304 };
305
306 beginning = end;
307 }
308 DeserializeResult {
309 values,
310 error: None,
311 remaining_bytes: DeserializeBytes::from(&bytes[beginning..]),
312 }
313 }
314}
315
316pub fn success(success: highlevel::Success) -> highlevel::Response {
318 highlevel::Response::Success(success)
319}