enet_proto/enc/
decoder.rs

1use 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  // Stored index of the next index to examine for the delimiter character.
16  // This is used to optimize searching.
17  // For example, if `decode` was called with `abc`, it would hold `3`,
18  // because that is the next index to examine.
19  // The next time `decode` is called with `abcde}`, the method will
20  // only look at `de}` before returning.
21  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        // no match was found
34        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  // Due to some of the enet messages having duplicate keys, we "sanitize" the input by deserializing to serde_json::Value first
63  // let value: serde_json::Value = serde_json::from_slice(buf)?;
64  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}