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
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
 * rust-daemon
 * JSON Codec
 *
 * https://github.com/ryankurte/rust-daemon
 * Copyright 2018 Ryan Kurte
 */

use std::io;
use std::marker::PhantomData;

use bytes::{BufMut, BytesMut};
use tokio_io::_tokio_codec::{Encoder, Decoder};
use serde::{Serialize, Deserialize};
use serde_json;

/// A codec for JSON encoding and decoding
/// Enc is the type to encode, Dec is the type to decode, E is the error type to be
/// returned for both operations
#[derive(Debug, PartialEq)]
pub struct JsonCodec<Enc, Dec, E> 
{
    enc: PhantomData<Enc>,
    dec: PhantomData<Dec>,
    err: PhantomData<E>,
}

/// Basic compatible error type
#[derive(Debug)]
pub enum JsonError {
    Io(io::Error),
    Json(serde_json::Error),
}

impl From<io::Error> for JsonError {
    fn from(e: io::Error) -> JsonError {
        return JsonError::Io(e);
    }
}

impl From<serde_json::Error> for JsonError {
    fn from(e: serde_json::Error) -> JsonError {
        return JsonError::Json(e);
    }
}

/// New builds an empty codec with associated types
impl <Enc, Dec, E>JsonCodec<Enc, Dec, E> 
where 
    for<'de> Dec: Deserialize<'de> + Clone + Send + 'static,
    for<'de> Enc: Serialize + Clone + Send + 'static,
    E: From<serde_json::Error> + From<io::Error> + 'static,
{
    /// Creates a new `JsonCodec` for shipping around raw bytes.
    pub fn new() -> JsonCodec<Enc, Dec, E> { 
        JsonCodec {enc: PhantomData, dec: PhantomData, err: PhantomData}  
    }
}

/// Clone impl required for use with connections
impl <Enc, Dec, E>Clone for JsonCodec<Enc, Dec, E> 
where 
    for<'de> Dec: Deserialize<'de> + Clone + Send + 'static,
    for<'de> Enc: Serialize + Clone + Send + 'static,
    E: From<serde_json::Error> + From<io::Error> + 'static,
{
    fn clone(&self) -> JsonCodec<Enc, Dec, E> {
        JsonCodec::new()
    }
}

/// Decoder impl parses json objects from bytes
impl <Enc, Dec, E>Decoder for JsonCodec<Enc, Dec, E> 
where 
    for<'de> Dec: Deserialize<'de> + Clone + Send + 'static,
    for<'de> Enc: Serialize + Clone + Send + 'static,
    E: From<serde_json::Error> + From<io::Error> + 'static,
{
    type Item = Dec;
    type Error = E;

    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        let offset;
        let res;
        
        {
            // Build streaming JSON iterator over data
            let de = serde_json::Deserializer::from_slice(&buf);
            let mut iter = de.into_iter::<Dec>();

            // Attempt to fetch an item and generate response
            res = match iter.next() {
                Some(Ok(v)) => Ok(Some(v)),
                Some(Err(ref e)) if e.is_eof() => {
                    Ok(None)
                },
                Some(Err(e)) => Err(e.into()),
                None => Ok(None),
            };
            offset = iter.byte_offset();
        }

        // Advance buffer
        buf.advance(offset);

        res
    }
}

/// Encoder impl encodes object streams to bytes
impl <Enc, Dec, E>Encoder for JsonCodec<Enc, Dec, E> 
where 
    for<'de> Dec: Deserialize<'de> + Clone + Send + 'static,
    for<'de> Enc: Serialize + Clone + Send + 'static,
    E: From<serde_json::Error> + From<io::Error> + 'static,
{
    type Item = Enc;
    type Error = E;

    fn encode(&mut self, data: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> {
        // Encode json
        let j = serde_json::to_string(&data)?;
        
        // Write to buffer
        buf.reserve(j.len());
        buf.put_slice(&j.as_bytes());

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use bytes::BytesMut;
    use tokio_codec::{Encoder, Decoder};

    use super::{JsonCodec, JsonError};

    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    struct TestStruct {
        pub name: String,
    }

    #[test]
    fn json_codec_encode_decode() {
        let mut codec = JsonCodec::<TestStruct, TestStruct, JsonError>::new();
        let mut buff = BytesMut::new();

        let item1 = TestStruct{name: "Test name".to_owned()};
        codec.encode(item1.clone(), &mut buff).unwrap();

        let item2 = codec.decode(&mut buff).unwrap().unwrap();
        assert_eq!(item1, item2);

        assert_eq!(codec.decode(&mut buff).unwrap(), None);

        assert_eq!(buff.len(), 0);
    }

    #[test]
    fn json_codec_partial_decode() {
        let mut codec = JsonCodec::<TestStruct, TestStruct, JsonError>::new();
        let mut buff = BytesMut::new();

        let item1 = TestStruct{name: "Test name".to_owned()};
        codec.encode(item1.clone(), &mut buff).unwrap();

        let mut start = buff.clone().split_to(4);
        assert_eq!(codec.decode(&mut start).unwrap(), None);

        codec.decode(&mut buff).unwrap().unwrap();

        assert_eq!(buff.len(), 0);
        
    }
}