de.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. use std::convert::TryFrom;
  2. use std::str;
  3. use std::io::Read;
  4. use super::error::{Error, Result};
  5. use serde::de::{
  6. self,
  7. Deserialize,
  8. DeserializeOwned,
  9. Visitor,
  10. DeserializeSeed,
  11. IntoDeserializer
  12. };
  13. // This lint is disabled because deserializing from a `&[u8]` is handled by `read_from`.
  14. #[allow(clippy::ptr_arg)]
  15. pub fn from_vec<T: DeserializeOwned>(vec: &Vec<u8>) -> Result<T> {
  16. let mut slice = vec.as_slice();
  17. read_from(&mut slice)
  18. }
  19. pub fn read_from<T: DeserializeOwned, R: Read>(read: &mut R) -> Result<T> {
  20. let mut de = Deserializer::new(read);
  21. Deserialize::deserialize(&mut de)
  22. }
  23. pub struct Deserializer<'de, T: Read + ?Sized> {
  24. input: &'de mut T,
  25. }
  26. fn try_from<TSource, TDest: TryFrom<TSource>>(value: TSource) -> Result<TDest> {
  27. let cast = TDest::try_from(value).map_err(|_| Error::TypeConversion)?;
  28. Ok(cast)
  29. }
  30. /// Returns the number of bytes needed to store the unicode character in UTF-8 whose
  31. /// encoding begins with the given byte. If the given byte is not valid as the first byte
  32. /// for any character, then a failed result with Error::InvalidUtf8Char is returned.
  33. fn num_bytes_for_char(first_byte: u8) -> Result<usize> {
  34. if first_byte & 128u8 == 0 {
  35. return Ok(1);
  36. }
  37. for bit in 2..5 {
  38. let mask = 128u8 >> bit;
  39. if mask & first_byte == 0 {
  40. return Ok(bit);
  41. }
  42. }
  43. Err(Error::InvalidUtf8Char)
  44. }
  45. /// Returns the unicode code point of the character that is encoded in UTF-8 in the given buffer
  46. /// as a u32. If the given buffer is not of a valid length then a failed result is returned.
  47. /// No other verification is performed.
  48. fn u32_from_utf8(buf: &[u8]) -> Result<u32> {
  49. const MASK: u8 = 0b0011_1111;
  50. fn mask(byte: u8, mask: u8) -> u32 {
  51. (byte & mask) as u32
  52. }
  53. fn two_bytes(buf: &[u8]) -> u32 {
  54. mask(buf[0], 0b0001_1111) << 6 | mask(buf[1], MASK)
  55. }
  56. fn three_bytes(buf: &[u8]) -> u32 {
  57. mask(buf[0], 0b0000_1111) << 12 | mask(buf[1], MASK) << 6 | mask(buf[2], MASK)
  58. }
  59. fn four_bytes(buf: &[u8]) -> u32 {
  60. mask(buf[0], 0b0000_0111) << 18 | mask(buf[1], MASK) << 12 | mask(buf[2], MASK) << 6
  61. | mask(buf[3], MASK)
  62. }
  63. let code_point = match buf.len() {
  64. 1 => Some(buf[0] as u32),
  65. 2 => Some(two_bytes(buf)),
  66. 3 => Some(three_bytes(buf)),
  67. 4 => Some(four_bytes(buf)),
  68. _ => None
  69. };
  70. code_point.ok_or(Error::InvalidUtf8Char)
  71. }
  72. fn char_from_utf8(buf: &[u8]) -> Result<char> {
  73. let result = u32_from_utf8(buf);
  74. let option = char::from_u32(result?);
  75. option.ok_or(Error::InvalidUtf8Char)
  76. }
  77. impl<'de, T: Read + ?Sized> Deserializer<'de, T> {
  78. pub fn new(input: &'de mut T) -> Self {
  79. Deserializer { input }
  80. }
  81. fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
  82. self.input.read_exact(buf).map_err(Error::Io)?;
  83. Ok(())
  84. }
  85. fn read_u8(&mut self) -> Result<u8> {
  86. let mut buf = [0u8; 1];
  87. self.read_exact(&mut buf)?;
  88. Ok(buf[0])
  89. }
  90. fn read_u16(&mut self) -> Result<u16> {
  91. let mut buf = [0u8; 2];
  92. self.read_exact(&mut buf)?;
  93. Ok(u16::from_le_bytes(buf))
  94. }
  95. fn read_u32(&mut self) -> Result<u32> {
  96. let mut buf = [0u8; 4];
  97. self.read_exact(&mut buf)?;
  98. Ok(u32::from_le_bytes(buf))
  99. }
  100. fn read_u64(&mut self) -> Result<u64> {
  101. let mut buf = [0u8; 8];
  102. self.read_exact(&mut buf)?;
  103. Ok(u64::from_le_bytes(buf))
  104. }
  105. fn read_i8(&mut self) -> Result<i8> {
  106. let value = self.read_u8()?;
  107. Ok(value as i8)
  108. }
  109. fn read_i16(&mut self) -> Result<i16> {
  110. let value = self.read_u16()?;
  111. Ok(value as i16)
  112. }
  113. fn read_i32(&mut self) -> Result<i32> {
  114. let value = self.read_u32()?;
  115. Ok(value as i32)
  116. }
  117. fn read_bool(&mut self) -> Result<bool> {
  118. let byte = self.read_u8()?;
  119. Ok(byte > 0)
  120. }
  121. fn read_vec(&mut self) -> Result<Vec<u8>> {
  122. let len = try_from(self.read_u32()?)?;
  123. let mut vec = vec![0; len];
  124. self.read_exact(vec.as_mut_slice())?;
  125. Ok(vec)
  126. }
  127. fn read_string(&mut self) -> Result<String> {
  128. let vec = self.read_vec()?;
  129. let value = String::from_utf8(vec).map_err(|_| Error::TypeConversion)?;
  130. Ok(value)
  131. }
  132. }
  133. impl<'de, 'a, T: Read> de::Deserializer<'de> for &'a mut Deserializer<'de, T> {
  134. type Error = Error;
  135. fn deserialize_any<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value> {
  136. Err(Error::Message("deserialize_any is not supported".to_string()))
  137. }
  138. fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  139. let value = self.read_bool()?;
  140. visitor.visit_bool(value)
  141. }
  142. fn deserialize_i8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  143. let value = self.read_i8()?;
  144. visitor.visit_i8(value)
  145. }
  146. fn deserialize_i16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  147. let value = self.read_i16()?;
  148. visitor.visit_i16(value)
  149. }
  150. fn deserialize_i32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  151. let value = self.read_i32()?;
  152. visitor.visit_i32(value)
  153. }
  154. fn deserialize_i64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  155. let unsigned = self.read_u64()?;
  156. let signed = unsigned as i64;
  157. visitor.visit_i64(signed)
  158. }
  159. fn deserialize_u8<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  160. let value = self.read_u8()?;
  161. visitor.visit_u8(value)
  162. }
  163. fn deserialize_u16<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  164. let value = self.read_u16()?;
  165. visitor.visit_u16(value)
  166. }
  167. fn deserialize_u32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  168. let value = self.read_u32()?;
  169. visitor.visit_u32(value)
  170. }
  171. fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  172. let value = self.read_u64()?;
  173. visitor.visit_u64(value)
  174. }
  175. fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  176. let mut buf = [0u8; 4];
  177. self.read_exact(&mut buf)?;
  178. let value = f32::from_le_bytes(buf);
  179. visitor.visit_f32(value)
  180. }
  181. fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  182. let mut buf = [0u8; 8];
  183. self.read_exact(&mut buf)?;
  184. let value = f64::from_le_bytes(buf);
  185. visitor.visit_f64(value)
  186. }
  187. fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  188. let byte = self.read_u8()?;
  189. let buf_len = num_bytes_for_char(byte);
  190. let mut buf = vec![0; buf_len?];
  191. buf[0] = byte;
  192. self.read_exact(&mut buf[1..])?;
  193. let result = char_from_utf8(&buf);
  194. visitor.visit_char(result?)
  195. }
  196. fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  197. let value = self.read_string()?;
  198. visitor.visit_str(value.as_str())
  199. }
  200. fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  201. let value = self.read_string()?;
  202. visitor.visit_string(value)
  203. }
  204. fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  205. let value = self.read_vec()?;
  206. visitor.visit_bytes(value.as_slice())
  207. }
  208. fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  209. let value = self.read_vec()?;
  210. visitor.visit_byte_buf(value)
  211. }
  212. fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  213. let some = self.read_bool()?;
  214. if some {
  215. visitor.visit_some(self)
  216. }
  217. else {
  218. visitor.visit_none()
  219. }
  220. }
  221. fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  222. visitor.visit_unit()
  223. }
  224. fn deserialize_unit_struct<V: Visitor<'de>>(
  225. self, _name: &'static str, visitor: V
  226. ) -> Result<V::Value> {
  227. visitor.visit_unit()
  228. }
  229. fn deserialize_newtype_struct<V: Visitor<'de>>(
  230. self, _name: &'static str, visitor: V
  231. ) -> Result<V::Value> {
  232. visitor.visit_newtype_struct(self)
  233. }
  234. fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  235. let len = self.read_u32()?;
  236. visitor.visit_seq(SeqAccess { elements_left: len, deserializer: self})
  237. }
  238. fn deserialize_tuple<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value> {
  239. visitor.visit_seq(SeqAccess { elements_left: try_from(len)?, deserializer: self})
  240. }
  241. fn deserialize_tuple_struct<V: Visitor<'de>>(
  242. self, _name: &'static str, len: usize, visitor: V
  243. ) -> Result<V::Value> {
  244. self.deserialize_tuple(len, visitor)
  245. }
  246. fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
  247. let len = self.read_u32()?;
  248. visitor.visit_map(SeqAccess { elements_left: len, deserializer: self})
  249. }
  250. fn deserialize_struct<V: Visitor<'de>>(
  251. self, _name: &'static str, fields: &'static [&'static str], visitor: V
  252. ) -> Result<V::Value> {
  253. self.deserialize_tuple(fields.len(), visitor)
  254. }
  255. fn deserialize_enum<V: Visitor<'de>>(
  256. self, _name: &'static str, _variants: &'static [&'static str], visitor: V
  257. ) -> Result<V::Value> {
  258. visitor.visit_enum(self)
  259. }
  260. fn deserialize_identifier<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value> {
  261. Err(Error::NotSupported("Deserializer::deserialize_identifier"))
  262. }
  263. fn deserialize_ignored_any<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value> {
  264. Err(Error::NotSupported("Deserializer::deserialize_ignored_any"))
  265. }
  266. fn is_human_readable(&self) -> bool {
  267. false
  268. }
  269. }
  270. struct SeqAccess<'a, 'de, T: Read> {
  271. elements_left: u32,
  272. deserializer: &'a mut Deserializer<'de, T>
  273. }
  274. impl<'a, 'de, T: Read> de::SeqAccess<'de> for SeqAccess<'a, 'de, T> {
  275. type Error = Error;
  276. fn next_element_seed<S: DeserializeSeed<'de>>(&mut self, seed: S) -> Result<Option<S::Value>> {
  277. if 0 == self.elements_left {
  278. return Ok(None)
  279. }
  280. self.elements_left -= 1;
  281. seed.deserialize(&mut *self.deserializer).map(Some)
  282. }
  283. }
  284. impl<'a, 'de, T: Read> de::MapAccess<'de> for SeqAccess<'a, 'de, T> {
  285. type Error = Error;
  286. fn next_key_seed<S: DeserializeSeed<'de>>(&mut self, seed: S) -> Result<Option<S::Value>> {
  287. if 0 == self.elements_left {
  288. return Ok(None)
  289. }
  290. self.elements_left -= 1;
  291. seed.deserialize(&mut *self.deserializer).map(Some)
  292. }
  293. fn next_value_seed<U: DeserializeSeed<'de>>(&mut self, seed: U) -> Result<U::Value> {
  294. seed.deserialize(&mut *self.deserializer)
  295. }
  296. }
  297. impl<'de, T: Read> de::VariantAccess<'de> for &mut Deserializer<'de, T> {
  298. type Error = Error;
  299. fn unit_variant(self) -> Result<()> {
  300. Ok(())
  301. }
  302. fn newtype_variant_seed<S: DeserializeSeed<'de>>(self, seed: S) -> Result<S::Value> {
  303. seed.deserialize(self)
  304. }
  305. fn tuple_variant<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value> {
  306. de::Deserializer::deserialize_tuple(self, len, visitor)
  307. }
  308. fn struct_variant<V: Visitor<'de>>(
  309. self, fields: &'static [&'static str], visitor: V
  310. ) -> Result<V::Value> {
  311. de::Deserializer::deserialize_struct(self, "", fields, visitor)
  312. }
  313. }
  314. impl<'a, 'de, T: Read> de::EnumAccess<'de> for &mut Deserializer<'de, T> {
  315. type Error = Error;
  316. type Variant = Self;
  317. fn variant_seed<S: DeserializeSeed<'de>>(self, seed: S) -> Result<(S::Value, Self::Variant)> {
  318. let int = self.read_u16()?;
  319. let index: u32 = try_from(int)?;
  320. let value = seed.deserialize(index.into_deserializer())?;
  321. Ok((value, self))
  322. }
  323. }
  324. #[cfg(test)]
  325. mod test {
  326. use serde::Deserialize;
  327. use super::{
  328. from_vec,
  329. num_bytes_for_char,
  330. Result,
  331. Deserializer
  332. };
  333. use std::collections::HashMap;
  334. #[test]
  335. fn new() -> Result<()> {
  336. let vec: Vec<u8> = vec![0xA1, 0x42, 0x71, 0xAC];
  337. let mut slice = vec.as_slice();
  338. let de = Deserializer::new(&mut slice);
  339. assert_eq!(&vec.as_slice(), de.input);
  340. Ok(())
  341. }
  342. #[test]
  343. fn test_num_bytes_for_char() -> Result<()> {
  344. fn test_case(c: char) -> Result<()> {
  345. let len = c.len_utf8();
  346. let mut buf: Vec<u8> = vec![0; len];
  347. c.encode_utf8(buf.as_mut_slice());
  348. let result = num_bytes_for_char(buf[0]);
  349. assert_eq!(len, result?);
  350. Ok(())
  351. }
  352. test_case('$')?;
  353. test_case('£')?;
  354. test_case('€')?;
  355. test_case('😑')?;
  356. Ok(())
  357. }
  358. #[test]
  359. fn deserialize_false() -> Result<()> {
  360. let vec: Vec<u8> = vec![0x00];
  361. let result = from_vec(&vec);
  362. assert_eq!(false, result?);
  363. Ok(())
  364. }
  365. #[test]
  366. fn deserialize_true() -> Result<()> {
  367. let vec: Vec<u8> = vec![0x01];
  368. let result = from_vec(&vec);
  369. assert_eq!(true, result?);
  370. Ok(())
  371. }
  372. #[test]
  373. fn deserialize_i8() -> Result<()> {
  374. let vec: Vec<u8> = vec![0xFE];
  375. let result = from_vec(&vec);
  376. assert_eq!(-2i8, result?);
  377. Ok(())
  378. }
  379. #[test]
  380. fn deserialize_i16() -> Result<()> {
  381. let vec: Vec<u8> = vec![0xFD, 0xFF];
  382. let result = from_vec(&vec);
  383. assert_eq!(-3i16, result?);
  384. Ok(())
  385. }
  386. #[test]
  387. fn deserialize_i32() -> Result<()> {
  388. let vec: Vec<u8> = vec![0xFE, 0xFF, 0xFF, 0xFF];
  389. let result = from_vec(&vec);
  390. assert_eq!(-2i32, result?);
  391. Ok(())
  392. }
  393. #[test]
  394. fn deserialize_i64() -> Result<()> {
  395. let vec: Vec<u8> = vec![0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
  396. let result = from_vec(&vec);
  397. assert_eq!(-2i64, result?);
  398. Ok(())
  399. }
  400. #[test]
  401. fn deserialize_u8() -> Result<()> {
  402. let vec: Vec<u8> = vec![0xFF];
  403. let result = from_vec(&vec);
  404. assert_eq!(255u8, result?);
  405. Ok(())
  406. }
  407. #[test]
  408. fn deserialize_u16() -> Result<()> {
  409. let vec: Vec<u8> = vec![0xFE, 0xFF];
  410. let result = from_vec(&vec);
  411. assert_eq!(0xFFFEu16, result?);
  412. Ok(())
  413. }
  414. #[test]
  415. fn deserialize_u32() -> Result<()> {
  416. let vec: Vec<u8> = vec![0xFE, 0xFF, 0xFF, 0xFF];
  417. let result = from_vec(&vec);
  418. assert_eq!(0xFFFFFFFEu32, result?);
  419. Ok(())
  420. }
  421. #[test]
  422. fn deserialize_u64() -> Result<()> {
  423. let vec: Vec<u8> = vec![0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
  424. let result = from_vec(&vec);
  425. assert_eq!(0xFFFFFFFFFFFFFFFEu64, result?);
  426. Ok(())
  427. }
  428. #[test]
  429. fn deserialize_f32() -> Result<()> {
  430. let vec: Vec<u8> = vec![0x00, 0x00, 0x20, 0x3E];
  431. let result = from_vec(&vec);
  432. assert_eq!(0.15625f32, result?);
  433. Ok(())
  434. }
  435. #[test]
  436. fn deserialize_f64() -> Result<()> {
  437. let vec: Vec<u8> = vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F];
  438. let result = from_vec(&vec);
  439. assert_eq!(1f64, result?);
  440. Ok(())
  441. }
  442. #[test]
  443. fn deserialize_char() -> Result<()> {
  444. fn test_case(c: char, vec: Vec<u8>) -> Result<()> {
  445. let result = from_vec(&vec);
  446. assert_eq!(c, result?);
  447. Ok(())
  448. }
  449. test_case('*', vec![0x2A])?;
  450. test_case('£', vec![0xC2, 0xA3])?;
  451. test_case('€', vec![0xE2, 0x82, 0xAC])?;
  452. test_case('😎', vec![0xF0, 0x9F, 0x98, 0x8E])?;
  453. Ok(())
  454. }
  455. #[test]
  456. fn deserialize_string() -> Result<()> {
  457. let vec: Vec<u8> = vec![
  458. 0x06, 0x00, 0x00, 0x00,
  459. 'l' as u8, 'o' as u8, 'c' as u8, 'a' as u8, 's' as u8, 'h' as u8
  460. ];
  461. let result: Result<String> = from_vec(&vec);
  462. assert_eq!("locash", result?);
  463. Ok(())
  464. }
  465. #[test]
  466. fn deserialize_byte_buf() -> Result<()> {
  467. let vec: Vec<u8> = vec![0x04, 0x00, 0x00, 0x00, 0x42, 0x91, 0xBE, 0xEF];
  468. let result: Result<Vec<u8>> = from_vec(&vec);
  469. assert_eq!(&vec[4..], result?);
  470. Ok(())
  471. }
  472. #[test]
  473. fn deserialize_none() -> Result<()> {
  474. let vec: Vec<u8> = vec![0x00];
  475. let result: Result<Option<u8>> = from_vec(&vec);
  476. assert_eq!(None, result?);
  477. Ok(())
  478. }
  479. #[test]
  480. fn deserialize_some() -> Result<()> {
  481. let vec: Vec<u8> = vec![0x01, 0xD5];
  482. let result: Result<Option<u8>> = from_vec(&vec);
  483. assert_eq!(Some(0xD5u8), result?);
  484. Ok(())
  485. }
  486. #[test]
  487. fn deserialize_tuple() -> Result<()> {
  488. let expected = ("orb".to_string(), 12u16);
  489. let vec: Vec<u8> = vec![
  490. 0x03, 0x00, 0x00, 0x00, 'o' as u8, 'r' as u8, 'b' as u8,
  491. 0x0C, 0x00
  492. ];
  493. let result = from_vec(&vec);
  494. assert_eq!(expected, result?);
  495. Ok(())
  496. }
  497. #[test]
  498. fn deserialize_map() -> Result<()> {
  499. let expected: HashMap<String, u8> = HashMap::from([
  500. ("blue".to_string(), 5), ("red".to_string(), 7)
  501. ]);
  502. let vec: Vec<u8> = vec![
  503. 0x02, 0x00, 0x00, 0x00, // Number of entries in the map.
  504. 0x04, 0x00, 0x00, 0x00, 'b' as u8, 'l' as u8, 'u' as u8, 'e' as u8, // First key.
  505. 0x05, // First value.
  506. 0x03, 0x00, 0x00, 0x00, 'r' as u8, 'e' as u8, 'd' as u8, // Second key.
  507. 0x07, // Second value.
  508. ];
  509. let result = from_vec(&vec);
  510. assert_eq!(expected, result?);
  511. Ok(())
  512. }
  513. #[test]
  514. fn deserialize_struct() -> Result<()> {
  515. #[derive(Debug, PartialEq, Deserialize)]
  516. struct Order {
  517. customer: String,
  518. item_id: u16,
  519. quantity: u8
  520. }
  521. let expected = Order {
  522. customer: "Bob".to_string(),
  523. item_id: 256,
  524. quantity: 255
  525. };
  526. let vec: Vec<u8> = vec![
  527. 0x03, 0x00, 0x00, 0x00, 'B' as u8, 'o' as u8, 'b' as u8,
  528. 0x00, 0x01,
  529. 0xFF
  530. ];
  531. let result = from_vec(&vec);
  532. assert_eq!(expected, result?);
  533. Ok(())
  534. }
  535. #[test]
  536. fn deserialize_enum() -> Result<()> {
  537. #[derive(Debug, PartialEq, Deserialize)]
  538. enum Emotions { Anguish, Catharsis }
  539. let vec: Vec<u8> = vec![0x01, 0x00];
  540. let result = from_vec(&vec);
  541. assert_eq!(Emotions::Catharsis, result?);
  542. Ok(())
  543. }
  544. #[test]
  545. fn deserialize_struct_variant() -> Result<()> {
  546. #[derive(Debug, PartialEq, Deserialize)]
  547. enum Vector {
  548. Dim2(i32, i32),
  549. Dim3(i32, i32, i32)
  550. }
  551. let expected = Vector::Dim3(1, -1, -2);
  552. let vec: Vec<u8> = vec![
  553. 0x01, 0x00, // The variant index.
  554. 0x01, 0x00, 0x00, 0x00, // The first entry.
  555. 0xFF, 0xFF, 0xFF, 0xFF, // The second entry.
  556. 0xFE, 0xFF, 0xFF, 0xFF // The last entry.
  557. ];
  558. let result = from_vec(&vec);
  559. assert_eq!(expected, result?);
  560. Ok(())
  561. }
  562. }