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