blob: 6e69571c3e0a49588b2afcf2d44a18c899ce831e [file] [log] [blame]
Mohammed Naser3415a2a2025-03-06 21:16:12 -05001use bytes::{BufMut, BytesMut};
2use serde_json::Value;
3use std::io;
4use tokio_util::codec::{Decoder, Encoder};
5
6pub struct JsonCodec;
7
8impl Encoder<BytesMut> for JsonCodec {
9 type Error = io::Error;
10
11 fn encode(&mut self, data: BytesMut, buf: &mut BytesMut) -> Result<(), io::Error> {
12 buf.reserve(data.len());
13 buf.put(data);
14 Ok(())
15 }
16}
17
18impl Decoder for JsonCodec {
19 type Item = Value;
20 type Error = io::Error;
21
22 fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Value>, io::Error> {
23 if src.is_empty() {
24 return Ok(None);
25 }
26
27 match serde_json::from_slice::<Value>(src) {
28 Ok(val) => {
29 src.clear();
30
31 Ok(Some(val))
32 }
33 Err(ref e) if e.is_eof() => Ok(None),
34 Err(e) => Err(e.into()),
35 }
36 }
37}