| 1 | use std::marker::PhantomData; |
| 2 | |
| 3 | use crate::{Decoder, Encoder}; |
| 4 | use bytes::{Buf, BufMut, BytesMut}; |
| 5 | |
| 6 | use serde::{Deserialize, Serialize}; |
| 7 | use serde_json; |
| 8 | |
| 9 | /// A codec for JSON encoding and decoding using serde_json |
| 10 | /// Enc is the type to encode, Dec is the type to decode |
| 11 | /// ``` |
| 12 | /// # use futures::{executor, SinkExt, TryStreamExt}; |
| 13 | /// # use futures::io::Cursor; |
| 14 | /// use serde::{Serialize, Deserialize}; |
| 15 | /// use futures_codec::{JsonCodec, Framed}; |
| 16 | /// |
| 17 | /// #[derive(Serialize, Deserialize)] |
| 18 | /// struct Something { |
| 19 | /// pub data: u16, |
| 20 | /// } |
| 21 | /// |
| 22 | /// async move { |
| 23 | /// # let mut buf = vec![]; |
| 24 | /// # let stream = Cursor::new(&mut buf); |
| 25 | /// // let stream = ... |
| 26 | /// let codec = JsonCodec::<Something, Something>::new(); |
| 27 | /// let mut framed = Framed::new(stream, codec); |
| 28 | /// |
| 29 | /// while let Some(s) = framed.try_next().await.unwrap() { |
| 30 | /// println!("{:?}", s.data); |
| 31 | /// } |
| 32 | /// }; |
| 33 | /// ``` |
| 34 | #[derive(Debug, PartialEq)] |
| 35 | pub struct JsonCodec<Enc, Dec> { |
| 36 | enc: PhantomData<Enc>, |
| 37 | dec: PhantomData<Dec>, |
| 38 | } |
| 39 | |
| 40 | /// JSON Codec error enumeration |
| 41 | #[derive(Debug)] |
| 42 | pub enum JsonCodecError { |
| 43 | /// IO error |
| 44 | Io(std::io::Error), |
| 45 | /// JSON error |
| 46 | Json(serde_json::Error), |
| 47 | } |
| 48 | |
| 49 | impl From<std::io::Error> for JsonCodecError { |
| 50 | fn from(e: std::io::Error) -> JsonCodecError { |
| 51 | return JsonCodecError::Io(e); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | impl From<serde_json::Error> for JsonCodecError { |
| 56 | fn from(e: serde_json::Error) -> JsonCodecError { |
| 57 | return JsonCodecError::Json(e); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | impl<Enc, Dec> JsonCodec<Enc, Dec> |
| 62 | where |
| 63 | for<'de> Dec: Deserialize<'de> + 'static, |
| 64 | for<'de> Enc: Serialize + 'static, |
| 65 | { |
| 66 | /// Creates a new `JsonCodec` with the associated types |
| 67 | pub fn new() -> JsonCodec<Enc, Dec> { |
| 68 | JsonCodec { |
| 69 | enc: PhantomData, |
| 70 | dec: PhantomData, |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | impl<Enc, Dec> Clone for JsonCodec<Enc, Dec> |
| 76 | where |
| 77 | for<'de> Dec: Deserialize<'de> + 'static, |
| 78 | for<'de> Enc: Serialize + 'static, |
| 79 | { |
| 80 | /// Clone creates a new instance of the `JsonCodec` |
| 81 | fn clone(&self) -> JsonCodec<Enc, Dec> { |
| 82 | JsonCodec::new() |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Decoder impl parses json objects from bytes |
| 87 | impl<Enc, Dec> Decoder for JsonCodec<Enc, Dec> |
| 88 | where |
| 89 | for<'de> Dec: Deserialize<'de> + 'static, |
| 90 | for<'de> Enc: Serialize + 'static, |
| 91 | { |
| 92 | type Item = Dec; |
| 93 | type Error = JsonCodecError; |
| 94 | |
| 95 | fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { |
| 96 | // Build streaming JSON iterator over data |
| 97 | let de = serde_json::Deserializer::from_slice(&buf); |
| 98 | let mut iter = de.into_iter::<Dec>(); |
| 99 | |
| 100 | // Attempt to fetch an item and generate response |
| 101 | let res = match iter.next() { |
| 102 | Some(Ok(v)) => Ok(Some(v)), |
| 103 | Some(Err(ref e)) if e.is_eof() => Ok(None), |
| 104 | Some(Err(e)) => Err(e.into()), |
| 105 | None => Ok(None), |
| 106 | }; |
| 107 | |
| 108 | // Update offset from iterator |
| 109 | let offset = iter.byte_offset(); |
| 110 | |
| 111 | // Advance buffer |
| 112 | buf.advance(offset); |
| 113 | |
| 114 | res |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Encoder impl encodes object streams to bytes |
| 119 | impl<Enc, Dec> Encoder for JsonCodec<Enc, Dec> |
| 120 | where |
| 121 | for<'de> Dec: Deserialize<'de> + 'static, |
| 122 | for<'de> Enc: Serialize + 'static, |
| 123 | { |
| 124 | type Item = Enc; |
| 125 | type Error = JsonCodecError; |
| 126 | |
| 127 | fn encode(&mut self, data: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> { |
| 128 | // Encode json |
| 129 | let j = serde_json::to_string(&data)?; |
| 130 | |
| 131 | // Write to buffer |
| 132 | buf.reserve(j.len()); |
| 133 | buf.put_slice(&j.as_bytes()); |
| 134 | |
| 135 | Ok(()) |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | #[cfg(test)] |
| 140 | mod test { |
| 141 | use bytes::BytesMut; |
| 142 | use serde::{Deserialize, Serialize}; |
| 143 | |
| 144 | use super::JsonCodec; |
| 145 | use crate::{Decoder, Encoder}; |
| 146 | |
| 147 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] |
| 148 | struct TestStruct { |
| 149 | pub name: String, |
| 150 | pub data: u16, |
| 151 | } |
| 152 | |
| 153 | #[test] |
| 154 | fn json_codec_encode_decode() { |
| 155 | let mut codec = JsonCodec::<TestStruct, TestStruct>::new(); |
| 156 | let mut buff = BytesMut::new(); |
| 157 | |
| 158 | let item1 = TestStruct { |
| 159 | name: "Test name".to_owned(), |
| 160 | data: 16, |
| 161 | }; |
| 162 | codec.encode(item1.clone(), &mut buff).unwrap(); |
| 163 | |
| 164 | let item2 = codec.decode(&mut buff).unwrap().unwrap(); |
| 165 | assert_eq!(item1, item2); |
| 166 | |
| 167 | assert_eq!(codec.decode(&mut buff).unwrap(), None); |
| 168 | |
| 169 | assert_eq!(buff.len(), 0); |
| 170 | } |
| 171 | |
| 172 | #[test] |
| 173 | fn json_codec_partial_decode() { |
| 174 | let mut codec = JsonCodec::<TestStruct, TestStruct>::new(); |
| 175 | let mut buff = BytesMut::new(); |
| 176 | |
| 177 | let item1 = TestStruct { |
| 178 | name: "Test name".to_owned(), |
| 179 | data: 34, |
| 180 | }; |
| 181 | codec.encode(item1.clone(), &mut buff).unwrap(); |
| 182 | |
| 183 | let mut start = buff.clone().split_to(4); |
| 184 | assert_eq!(codec.decode(&mut start).unwrap(), None); |
| 185 | |
| 186 | codec.decode(&mut buff).unwrap().unwrap(); |
| 187 | |
| 188 | assert_eq!(buff.len(), 0); |
| 189 | } |
| 190 | } |