aboutsummaryrefslogtreecommitdiff
path: root/jsonrpc/src/codec.rs
blob: 29c6f1350e84f8a25c7b884d725063855ba332fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#[cfg(feature = "ws")]
use async_tungstenite::tungstenite::Message;

use karyon_net::{
    codec::{Codec, Decoder, Encoder},
    Error, Result,
};

#[cfg(feature = "ws")]
use karyon_net::codec::{WebSocketCodec, WebSocketDecoder, WebSocketEncoder};

#[derive(Clone)]
pub struct JsonCodec {}

impl Codec for JsonCodec {
    type Item = serde_json::Value;
}

impl Encoder for JsonCodec {
    type EnItem = serde_json::Value;
    fn encode(&self, src: &Self::EnItem, dst: &mut [u8]) -> Result<usize> {
        let msg = match serde_json::to_string(src) {
            Ok(m) => m,
            Err(err) => return Err(Error::Encode(err.to_string())),
        };
        let buf = msg.as_bytes();
        dst[..buf.len()].copy_from_slice(buf);
        Ok(buf.len())
    }
}

impl Decoder for JsonCodec {
    type DeItem = serde_json::Value;
    fn decode(&self, src: &mut [u8]) -> Result<Option<(usize, Self::DeItem)>> {
        let de = serde_json::Deserializer::from_slice(src);
        let mut iter = de.into_iter::<serde_json::Value>();

        let item = match iter.next() {
            Some(Ok(item)) => item,
            Some(Err(ref e)) if e.is_eof() => return Ok(None),
            Some(Err(e)) => return Err(Error::Encode(e.to_string())),
            None => return Ok(None),
        };

        Ok(Some((iter.byte_offset(), item)))
    }
}

#[cfg(feature = "ws")]
#[derive(Clone)]
pub struct WsJsonCodec {}

#[cfg(feature = "ws")]
impl WebSocketCodec for WsJsonCodec {
    type Item = serde_json::Value;
}

#[cfg(feature = "ws")]
impl WebSocketEncoder for WsJsonCodec {
    type EnItem = serde_json::Value;
    fn encode(&self, src: &Self::EnItem) -> Result<Message> {
        let msg = match serde_json::to_string(src) {
            Ok(m) => m,
            Err(err) => return Err(Error::Encode(err.to_string())),
        };
        Ok(Message::Text(msg))
    }
}

#[cfg(feature = "ws")]
impl WebSocketDecoder for WsJsonCodec {
    type DeItem = serde_json::Value;
    fn decode(&self, src: &Message) -> Result<Self::DeItem> {
        match src {
            Message::Text(s) => match serde_json::from_str(s) {
                Ok(m) => Ok(m),
                Err(err) => Err(Error::Decode(err.to_string())),
            },
            _ => Err(Error::Decode("Receive wrong message".to_string())),
        }
    }
}