enet_proto/enc/
decoder.rs1use super::DELIMETER;
2use crate::Response;
3use bytes::BytesMut;
4use lazy_static::lazy_static;
5use regex::bytes::{Regex, RegexBuilder};
6use thiserror::Error;
7use tracing::{event, Level};
8
9lazy_static! {
10 static ref DELIMETER_REGEX: Regex = RegexBuilder::new(DELIMETER).unicode(false).build().unwrap();
11}
12
13#[derive(Default)]
14pub struct EnetDecoder {
15 next_index: usize,
22}
23
24impl EnetDecoder {
25 #[inline]
26 pub const fn new() -> Self {
27 Self { next_index: 0 }
28 }
29
30 pub fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Response>, EnetDecoderError> {
31 match DELIMETER_REGEX.find_at(buf, self.next_index) {
32 None => {
33 let mut end_chars_matching = 0usize;
35 let mut end_iter = buf.iter().rev();
36 let mut pat_iter = DELIMETER.as_bytes().iter().rev();
37 while end_iter.next() == pat_iter.next() && end_chars_matching < DELIMETER.len() - 1 {
38 end_chars_matching += 1;
39 }
40
41 self.next_index = buf.len() - end_chars_matching;
42 Ok(None)
43 }
44
45 Some(m) => {
46 let range = m.range();
47 self.next_index = 0;
48 let chunk_with_delimeter = buf.split_to(range.end);
49 let chunk = &chunk_with_delimeter[..chunk_with_delimeter.len() - DELIMETER.len()];
50 let item = parse(chunk)?;
51 Ok(Some(item))
52 }
53 }
54 }
55}
56
57fn parse(buf: &[u8]) -> Result<Response, EnetDecoderError> {
58 if let Ok(utf8) = std::str::from_utf8(buf) {
59 event!(target: "enet-proto::enc::decoder", Level::TRACE, "parsing enet data: {}", utf8);
60 }
61
62 let response = serde_json::from_slice(buf)?;
65 Ok(response)
66}
67
68#[non_exhaustive]
69#[derive(Debug, Error)]
70pub enum EnetDecoderError {
71 #[error("Failed to decode eNet message.")]
72 JsonError(#[from] serde_json::Error),
73}