ser.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. use std::io::Write;
  2. use std::convert::TryFrom;
  3. use serde::{
  4. ser::{
  5. self,
  6. SerializeSeq,
  7. SerializeTuple,
  8. SerializeTupleStruct,
  9. SerializeTupleVariant,
  10. SerializeMap,
  11. SerializeStruct,
  12. SerializeStructVariant,
  13. },
  14. Serialize,
  15. };
  16. use super::error::{Error, Result, MapError};
  17. type Ok = ();
  18. pub struct Serializer<'w, W: Write> {
  19. output: &'w mut W,
  20. }
  21. impl<'w, W: Write> Serializer<'w, W> {
  22. pub fn new(write: &'w mut W) -> Serializer<'w, W> {
  23. Serializer { output: write }
  24. }
  25. }
  26. pub fn to_vec<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>> {
  27. let mut vec = Vec::new();
  28. let result = write_to(value, &mut vec);
  29. result?;
  30. Ok(vec)
  31. }
  32. pub fn write_to<T: Serialize + ?Sized, W: Write>(value: &T, write: &mut W) -> Result<()> {
  33. let mut serializer = Serializer::new(write);
  34. value.serialize(&mut serializer)
  35. }
  36. fn try_convert(len: Option<usize>) -> Result<u32> {
  37. match len {
  38. Some(count) => {
  39. let length = u32::try_from(count).map_err(|_| Error::SequenceTooLong(count))?;
  40. Ok(length)
  41. },
  42. None => Err(Error::UnknownLength),
  43. }
  44. }
  45. fn convert_variant_index(index: u32) -> Result<u16> {
  46. u16::try_from(index).map_err(|_| Error::TooManyVariants(index))
  47. }
  48. impl<'a, 'w, T: Write> ser::Serializer for &'a mut Serializer<'w, T> {
  49. type Ok = Ok;
  50. type Error = Error;
  51. type SerializeSeq = Self;
  52. type SerializeTuple = Self;
  53. type SerializeTupleVariant = Self;
  54. type SerializeTupleStruct = Self;
  55. type SerializeMap = Self;
  56. type SerializeStruct = Self;
  57. type SerializeStructVariant = Self;
  58. /// A bool is serialized by writing the byte 1 if true and 0 if false.
  59. fn serialize_bool(self, v: bool) -> Result<Self::Ok> {
  60. self.output.write_all(&[if v { 1 } else { 0 }]).map_error()?;
  61. Ok(())
  62. }
  63. /// The output format of a signed byte is two's complement, so we can just output
  64. /// Rust's binary representation.
  65. fn serialize_i8(self, v: i8) -> Result<Self::Ok> {
  66. self.output.write_all(&v.to_le_bytes()).map_error()?;
  67. Ok(())
  68. }
  69. /// The output format of a signed integer is two's complement, so we can just output
  70. /// Rust's binary representation in little endian order.
  71. fn serialize_i16(self, v: i16) -> Result<Self::Ok> {
  72. self.output.write_all(&v.to_le_bytes()).map_error()?;
  73. Ok(())
  74. }
  75. /// The output format of a signed integer is two's complement, so we can just output
  76. /// Rust's binary representation in little endian order.
  77. fn serialize_i32(self, v: i32) -> Result<Self::Ok> {
  78. self.output.write_all(&v.to_le_bytes()).map_error()?;
  79. Ok(())
  80. }
  81. /// The output format of a signed integer is two's complement, so we can just output
  82. /// Rust's binary representation in little endian order.
  83. fn serialize_i64(self, v: i64) -> Result<Self::Ok> {
  84. self.output.write_all(&v.to_le_bytes()).map_error()?;
  85. Ok(())
  86. }
  87. /// The output format of a signed integer is two's complement, so we can just output
  88. /// Rust's binary representation in little endian order.
  89. fn serialize_i128(self, v: i128) -> Result<Self::Ok> {
  90. self.output.write_all(&v.to_le_bytes()).map_error()?;
  91. Ok(())
  92. }
  93. /// The given byte is written directly to the output.
  94. fn serialize_u8(self, v: u8) -> Result<Self::Ok> {
  95. self.output.write_all(&[v]).map_error()?;
  96. Ok(())
  97. }
  98. /// The underlying bytes of the given unsigned integer are written to the output in little
  99. /// endian order.
  100. fn serialize_u16(self, v: u16) -> Result<Self::Ok> {
  101. self.output.write_all(&v.to_le_bytes()).map_error()?;
  102. Ok(())
  103. }
  104. /// The underlying bytes of the given unsigned integer are written to the output in little
  105. /// endian order.
  106. fn serialize_u32(self, v: u32) -> Result<Self::Ok> {
  107. self.output.write_all(&v.to_le_bytes()).map_error()?;
  108. Ok(())
  109. }
  110. /// The underlying bytes of the given unsigned integer are written to the output in little
  111. /// endian order.
  112. fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
  113. self.output.write_all(&v.to_le_bytes()).map_error()?;
  114. Ok(())
  115. }
  116. /// The underlying bytes of the given unsigned integer are written to the output in little
  117. /// endian order.
  118. fn serialize_u128(self, v: u128) -> Result<Self::Ok> {
  119. self.output.write_all(&v.to_le_bytes()).map_error()?;
  120. Ok(())
  121. }
  122. /// Since the output format is IEEE 754, we can just write the underlying bytes to the output
  123. /// in little endian order.
  124. fn serialize_f32(self, v: f32) -> Result<Self::Ok> {
  125. self.output.write_all(&v.to_le_bytes()).map_error()?;
  126. Ok(())
  127. }
  128. /// Since the output format is IEEE 754, we can just write the underlying bytes to the output
  129. /// in little endian order.
  130. fn serialize_f64(self, v: f64) -> Result<Self::Ok> {
  131. self.output.write_all(&v.to_le_bytes()).map_error()?;
  132. Ok(())
  133. }
  134. /// The given char is cast to a u8 then written to the output.
  135. fn serialize_char(self, c: char) -> Result<Self::Ok> {
  136. self.output.write_all(&[c as u8]).map_error()?;
  137. Ok(())
  138. }
  139. /// A slice of bytes is stored by first writing its length (in LE order) and then the slice.
  140. fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok> {
  141. let len = v.len() as u32;
  142. self.output.write_all(&len.to_le_bytes()).map_error()?;
  143. self.output.write_all(v).map_error()?;
  144. Ok(())
  145. }
  146. /// A str is just serialized as a sequence of UTF8 bytes.
  147. fn serialize_str(self, v: &str) -> Result<Self::Ok> {
  148. self.serialize_bytes(v.as_bytes())
  149. }
  150. /// The none variant is stored by serializing false.
  151. fn serialize_none(self) -> Result<Self::Ok> {
  152. self.serialize_bool(false)?;
  153. Ok(())
  154. }
  155. /// A some variant is stored by serializing true before the of its value.
  156. fn serialize_some<U: ?Sized + Serialize>(self, value: &U) -> Result<Self::Ok> {
  157. self.serialize_bool(true)?;
  158. value.serialize(self)?;
  159. Ok(())
  160. }
  161. /// The unit is a type which can be represented with zero bytes, so we faithfully represent it
  162. /// as nothing.
  163. fn serialize_unit(self) -> Result<()> {
  164. Ok(())
  165. }
  166. /// Forwards to serialize_unit.
  167. fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
  168. self.serialize_unit()
  169. }
  170. /// The index of the unit variant is written to the output.
  171. fn serialize_unit_variant(
  172. self, _name: &'static str, variant_index: u32, _variant: &'static str
  173. ) -> Result<Self::Ok> {
  174. let index = convert_variant_index(variant_index)?;
  175. self.serialize_u16(index)?;
  176. Ok(())
  177. }
  178. /// The value of the newtype struct is serialized and its name is ignored.
  179. fn serialize_newtype_struct<U: ?Sized + Serialize>(
  180. self, _name: &'static str, value: &U
  181. ) -> Result<Self::Ok> {
  182. value.serialize(self)?;
  183. Ok(())
  184. }
  185. /// The index of the variant is serialized and written out, followed by the serialization of
  186. /// its value.
  187. fn serialize_newtype_variant<U: ?Sized + Serialize>(
  188. self, _name: &'static str, variant_index: u32, _variant: &'static str, value: &U
  189. ) -> Result<Self::Ok> {
  190. let index = convert_variant_index(variant_index)?;
  191. self.serialize_u16(index)?;
  192. value.serialize(self)?;
  193. Ok(())
  194. }
  195. fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
  196. let length = try_convert(len)?;
  197. self.serialize_u32(length)?;
  198. Ok(self)
  199. }
  200. /// A tuple's length is not stored, only its entries.
  201. fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
  202. Ok(self)
  203. }
  204. /// A tuple struct is serialized the same way as a tuple, its name is ignore.
  205. fn serialize_tuple_struct(
  206. self, _name: &'static str, _len: usize
  207. ) -> Result<Self::SerializeTupleStruct> {
  208. Ok(self)
  209. }
  210. /// The variant index is stored before the tuples values.
  211. fn serialize_tuple_variant(
  212. self, _name: &'static str, variant_index: u32, _variant: &'static str, _len: usize
  213. ) -> Result<Self::SerializeTupleStruct> {
  214. let index = convert_variant_index(variant_index)?;
  215. self.serialize_u16(index)?;
  216. Ok(self)
  217. }
  218. /// The number of entries in the map is stored as a u32 prior to serializing the key value
  219. /// pairs in the map. If there are more entries than a u32 can represent, then an error is
  220. /// returned.
  221. fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
  222. let length = try_convert(len)?;
  223. self.serialize_u32(length)?;
  224. Ok(self)
  225. }
  226. /// Since the members of a struct a known at compile time, no additional information is stored.
  227. fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
  228. Ok(self)
  229. }
  230. /// The variant index is stored before the struct's members.
  231. fn serialize_struct_variant(
  232. self, _name: &'static str, variant_index: u32, _variant: &'static str, _len: usize
  233. ) -> Result<Self::SerializeStructVariant> {
  234. let index = convert_variant_index(variant_index)?;
  235. self.serialize_u16(index)?;
  236. Ok(self)
  237. }
  238. }
  239. impl<'a, 'w, W: Write> SerializeSeq for &'a mut Serializer<'w, W> {
  240. type Ok = Ok;
  241. type Error = Error;
  242. fn serialize_element<U: ?Sized + Serialize>(&mut self, value: &U) -> Result<Ok> {
  243. value.serialize(&mut **self)?;
  244. Ok(())
  245. }
  246. /// No marker is added to the end of the sequence because we know its length.
  247. fn end(self) -> Result<Ok> {
  248. Ok(())
  249. }
  250. }
  251. impl<'a, 'w, W: Write> SerializeTuple for &'a mut Serializer<'w, W> {
  252. type Ok = Ok;
  253. type Error = Error;
  254. fn serialize_element<U: ?Sized + Serialize>(&mut self, value: &U) -> Result<Ok> {
  255. value.serialize(&mut **self)?;
  256. Ok(())
  257. }
  258. fn end(self) -> Result<Ok> {
  259. Ok(())
  260. }
  261. }
  262. impl<'a, 'w, W: Write> SerializeTupleStruct for &'a mut Serializer<'w, W> {
  263. type Ok = Ok;
  264. type Error = Error;
  265. fn serialize_field<U: ?Sized + Serialize>(&mut self, value: &U) -> Result<Ok> {
  266. value.serialize(&mut **self)?;
  267. Ok(())
  268. }
  269. fn end(self) -> Result<Ok> {
  270. Ok(())
  271. }
  272. }
  273. impl<'a, 'w, W: Write> SerializeTupleVariant for &'a mut Serializer<'w, W> {
  274. type Ok = Ok;
  275. type Error = Error;
  276. fn serialize_field<U: ?Sized + Serialize>(&mut self, value: &U) -> Result<Ok> {
  277. value.serialize(&mut **self)?;
  278. Ok(())
  279. }
  280. fn end(self) -> Result<Ok> {
  281. Ok(())
  282. }
  283. }
  284. impl<'a, 'w, W: Write> SerializeMap for &'a mut Serializer<'w, W> {
  285. type Ok = Ok;
  286. type Error = Error;
  287. fn serialize_key<U: ?Sized + Serialize>(&mut self, key: &U) -> Result<Ok> {
  288. key.serialize(&mut **self)?;
  289. Ok(())
  290. }
  291. fn serialize_value<U: ?Sized + Serialize>(&mut self, value: &U) -> Result<Ok> {
  292. value.serialize(&mut **self)?;
  293. Ok(())
  294. }
  295. fn end(self) -> Result<Ok> {
  296. Ok(())
  297. }
  298. }
  299. impl<'a, 'w, W: Write> SerializeStruct for &'a mut Serializer<'w, W> {
  300. type Ok = Ok;
  301. type Error = Error;
  302. fn serialize_field<U: ?Sized + Serialize>(
  303. &mut self, _key: &'static str, value: &U) -> Result<Ok> {
  304. value.serialize(&mut **self)?;
  305. Ok(())
  306. }
  307. fn end(self) -> Result<Ok> {
  308. Ok(())
  309. }
  310. }
  311. impl<'a, 'w, W: Write> SerializeStructVariant for &'a mut Serializer<'w, W> {
  312. type Ok = Ok;
  313. type Error = Error;
  314. fn serialize_field<U: ?Sized + Serialize>(
  315. &mut self, _key: &'static str, value: &U) -> Result<Ok> {
  316. value.serialize(&mut **self)?;
  317. Ok(())
  318. }
  319. fn end(self) -> Result<Ok> {
  320. Ok(())
  321. }
  322. }
  323. #[cfg(test)]
  324. mod test {
  325. // This is actually used in every method below.
  326. use super::Result;
  327. // This is also used in several methods below.
  328. use serde::Serialize;
  329. #[test]
  330. fn serialize_bool() -> Result<()> {
  331. {
  332. let buffer = super::to_vec(&true)?;
  333. assert_eq!(vec![1], buffer);
  334. }
  335. {
  336. let buffer = super::to_vec(&false)?;
  337. assert_eq!(vec![0], buffer);
  338. }
  339. Ok(())
  340. }
  341. #[test]
  342. fn serialize_i8() -> Result<()> {
  343. {
  344. let buffer = super::to_vec(&5i8)?;
  345. assert_eq!(vec![0b00000101], buffer);
  346. }
  347. {
  348. let value: i8 = -1;
  349. let buffer = super::to_vec(&value)?;
  350. assert_eq!(vec![0b11111111], buffer);
  351. }
  352. Ok(())
  353. }
  354. #[test]
  355. fn serialize_i16() -> Result<()> {
  356. {
  357. let buffer = super::to_vec(&1i16)?;
  358. assert_eq!(vec![0x01, 0x00], buffer);
  359. }
  360. {
  361. let value: i16 = -2;
  362. let buffer = super::to_vec(&value)?;
  363. assert_eq!(vec![0xFE, 0xFF], buffer);
  364. }
  365. Ok(())
  366. }
  367. #[test]
  368. fn serialize_i32() -> Result<()> {
  369. {
  370. let buffer = super::to_vec(&1i32)?;
  371. assert_eq!(vec![0x01, 0x00, 0x00, 0x00], buffer);
  372. }
  373. {
  374. let value: i32 = -2;
  375. let buffer = super::to_vec(&value)?;
  376. assert_eq!(vec![0xFE, 0xFF, 0xFF, 0xFF], buffer);
  377. }
  378. Ok(())
  379. }
  380. #[test]
  381. fn serialize_i64() -> Result<()> {
  382. {
  383. let buffer = super::to_vec(&1i64)?;
  384. assert_eq!(vec![0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], buffer);
  385. }
  386. {
  387. let value: i64 = -2;
  388. let buffer = super::to_vec(&value)?;
  389. assert_eq!(vec![0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], buffer);
  390. }
  391. Ok(())
  392. }
  393. #[test]
  394. fn serialize_i128() -> Result<()> {
  395. {
  396. let buffer = super::to_vec(&1i128)?;
  397. assert_eq!(vec![0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], buffer);
  398. }
  399. {
  400. let value: i128 = -2;
  401. let buffer = super::to_vec(&value)?;
  402. assert_eq!(vec![0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], buffer);
  403. }
  404. Ok(())
  405. }
  406. #[test]
  407. fn serialize_u8() -> Result<()> {
  408. let value: u8 = 42;
  409. let buffer = super::to_vec(&value)?;
  410. assert_eq!(vec![value], buffer);
  411. Ok(())
  412. }
  413. #[test]
  414. fn serialize_u16() -> Result<()> {
  415. let buffer = super::to_vec(&1u16)?;
  416. assert_eq!(vec![0x01, 0x00], buffer);
  417. Ok(())
  418. }
  419. #[test]
  420. fn serialize_u32() -> Result<()> {
  421. let buffer = super::to_vec(&1u32)?;
  422. assert_eq!(vec![0x01, 0x00, 0x00, 0x00], buffer);
  423. Ok(())
  424. }
  425. #[test]
  426. fn serialize_u64() -> Result<()> {
  427. let buffer = super::to_vec(&1u64)?;
  428. assert_eq!(vec![0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], buffer);
  429. Ok(())
  430. }
  431. #[test]
  432. fn serialize_u128() -> Result<()> {
  433. let buffer = super::to_vec(&1u128)?;
  434. assert_eq!(vec![0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], buffer);
  435. Ok(())
  436. }
  437. #[test]
  438. fn serialize_f32() -> Result<()> {
  439. let buffer = super::to_vec(&0.15625f32)?;
  440. assert_eq!(vec![0x00, 0x00, 0x20, 0x3E], buffer);
  441. Ok(())
  442. }
  443. #[test]
  444. fn serialize_f64() -> Result<()> {
  445. let buffer = super::to_vec(&1f64)?;
  446. assert_eq!(vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F], buffer);
  447. Ok(())
  448. }
  449. #[test]
  450. fn serialize_char() -> Result<()> {
  451. let c: char = '*';
  452. let buffer = super::to_vec(&c)?;
  453. assert_eq!(vec![42], buffer);
  454. Ok(())
  455. }
  456. #[test]
  457. fn serialize_bytes() -> Result<()> {
  458. let mut bytes: Vec<u8> = vec![41, 23, 72, 61];
  459. let buffer = super::to_vec(bytes.as_slice())?;
  460. let length = bytes.len() as u32;
  461. let mut expected = length.to_le_bytes().to_vec();
  462. expected.append(&mut bytes);
  463. assert_eq!(expected, buffer);
  464. Ok(())
  465. }
  466. #[test]
  467. fn serialize_str() -> Result<()> {
  468. let message = "vapid 😑";
  469. let buffer = super::to_vec(message)?;
  470. assert_eq!(vec![10, 0, 0, 0, 118, 97, 112, 105, 100, 32, 240, 159, 152, 145], buffer);
  471. Ok(())
  472. }
  473. #[test]
  474. fn serialize_none() -> Result<()> {
  475. let none: Option<i32> = Option::None;
  476. let buffer = super::to_vec(&none)?;
  477. assert_eq!(vec![0], buffer);
  478. Ok(())
  479. }
  480. #[test]
  481. fn serialize_some() -> Result<()> {
  482. // Sometimes I use decimal, sometimes I use hex. So what, want to fight about it?
  483. let some: Option<i32> = Option::Some(0x02D8);
  484. let buffer = super::to_vec(&some)?;
  485. assert_eq!(vec![0x01, 0xD8, 0x02, 0x00, 0x00], buffer);
  486. Ok(())
  487. }
  488. #[test]
  489. fn serialize_unit() -> Result<()> {
  490. let buffer = super::to_vec(&())?;
  491. let expected: Vec<u8> = Vec::new();
  492. assert_eq!(expected, buffer);
  493. Ok(())
  494. }
  495. #[test]
  496. fn serialize_unit_struct() -> Result<()> {
  497. #[derive(Serialize)]
  498. struct UnitStruct;
  499. let test = UnitStruct {};
  500. let buffer = super::to_vec(&test)?;
  501. let expected: Vec<u8> = Vec::new();
  502. assert_eq!(expected, buffer);
  503. Ok(())
  504. }
  505. #[test]
  506. fn serialize_unit_variant() -> Result<()> {
  507. #[derive(Serialize)]
  508. #[allow(dead_code)]
  509. enum Matter {
  510. Condensate,
  511. Solid,
  512. Liquid,
  513. Gas,
  514. Plasma,
  515. Cat,
  516. }
  517. let test = Matter::Liquid;
  518. let buffer = super::to_vec(&test)?;
  519. assert_eq!(vec![0x02, 0x00], buffer);
  520. Ok(())
  521. }
  522. #[test]
  523. fn serialize_newtype_struct() -> Result<()> {
  524. #[derive(Serialize)]
  525. struct Score(u16);
  526. let score = Score(512);
  527. let buffer = super::to_vec(&score)?;
  528. assert_eq!(vec![0x00, 0x02], buffer);
  529. Ok(())
  530. }
  531. #[test]
  532. fn serialize_newtype_variant() -> Result<()> {
  533. #[derive(Serialize)]
  534. #[allow(dead_code)]
  535. enum Currency {
  536. Usd(i32),
  537. Btc(i32),
  538. Fil(i32),
  539. Eth(i32)
  540. }
  541. let value = Currency::Fil(1024);
  542. let buffer = super::to_vec(&value)?;
  543. let expected = vec![
  544. 0x02, 0x00, // The variant index.
  545. 0x00, 0x04, 0x00, 0x00 // The value contained within.
  546. ];
  547. assert_eq!(expected, buffer);
  548. Ok(())
  549. }
  550. #[test]
  551. fn serialize_unit_struct_variant() -> Result<()> {
  552. #[derive(Serialize)]
  553. #[allow(dead_code)]
  554. enum UnitStructVariant {
  555. Zeroth {},
  556. First {},
  557. Second {},
  558. Third {}
  559. }
  560. let test = UnitStructVariant::Second {};
  561. let buffer = super::to_vec(&test)?;
  562. assert_eq!(vec![2, 0], buffer);
  563. Ok(())
  564. }
  565. #[test]
  566. fn serialize_tuple() -> Result<()> {
  567. let value = (5u16, -1i8);
  568. let buffer = super::to_vec(&value)?;
  569. assert_eq!(vec![0x05, 0x00 /* == 5u16 */, 0xFF /* == -1i8 */], buffer);
  570. Ok(())
  571. }
  572. #[test]
  573. fn serialize_tuple_struct() -> Result<()> {
  574. #[derive(Serialize)]
  575. struct Contrived(i8, String);
  576. let value = Contrived(-2, "-2".to_string());
  577. let buffer = super::to_vec(&value)?;
  578. let expected = vec![
  579. 0xFE, // The value -2.
  580. 0x02, 0x00, 0x00, 0x00, // The length of the string.
  581. 0x2D, 0x32 // The characters '-' and '2'.
  582. ];
  583. assert_eq!(expected, buffer);
  584. Ok(())
  585. }
  586. #[test]
  587. fn serialize_tuple_variant() -> Result<()> {
  588. #[derive(Serialize)]
  589. #[allow(dead_code)]
  590. enum ByteVector {
  591. Dim2(u8, u8),
  592. Dim3(u8, u8, u8),
  593. }
  594. let value = ByteVector::Dim3(5, 9, 42);
  595. let buffer = super::to_vec(&value)?;
  596. let expected = vec![
  597. 0x01, 0x00, // The variant index.
  598. 0x05, // The first entry.
  599. 0x09, // The second entry.
  600. 0x2A, // The last entry.
  601. ];
  602. assert_eq!(expected, buffer);
  603. Ok(())
  604. }
  605. #[test]
  606. fn serialize_map() -> Result<()> {
  607. use std::collections::HashMap;
  608. #[derive(PartialEq, Eq, Hash, Serialize)]
  609. enum Color { Red, Blue }
  610. let mut map: HashMap<Color, u16> = HashMap::new();
  611. map.insert(Color::Red, 5);
  612. map.insert(Color::Blue, 256);
  613. let buffer = super::to_vec(&map)?;
  614. assert_eq!(12, buffer.len());
  615. assert_eq!(vec![0x02, 0x00, 0x00, 0x00], &buffer[..4]);
  616. // The entries could be output in an arbitrary order.
  617. let mut expected_map: HashMap<[u8; 2], [u8; 2]> = HashMap::new();
  618. expected_map.insert([0x00, 0x00], [0x05, 0x00]);
  619. expected_map.insert([0x01, 0x00], [0x00, 0x01]);
  620. assert_eq!(expected_map.get(&buffer[4..6]).unwrap(), &buffer[6..8]);
  621. assert_eq!(expected_map.get(&buffer[8..10]).unwrap(), &buffer[10..12]);
  622. Ok(())
  623. }
  624. #[test]
  625. fn serialize_struct() -> Result<()> {
  626. #[derive(Serialize)]
  627. struct Bag {
  628. name: &'static str,
  629. weight: u16,
  630. value: i8
  631. }
  632. let value = Bag { name: "box", weight: 10, value: -1 };
  633. let buffer = super::to_vec(&value)?;
  634. let expected = vec![
  635. 0x03, 0x00, 0x00, 0x00, 'b' as u8, 'o' as u8, 'x' as u8, // name
  636. 0x0A, 0x00, // weight
  637. 0xFF // value
  638. ];
  639. assert_eq!(expected, buffer);
  640. Ok(())
  641. }
  642. #[test]
  643. fn serialize_struct_variant() -> Result<()> {
  644. #[derive(Serialize)]
  645. #[allow(dead_code)]
  646. enum Shape {
  647. Rectangle { upper_left_corner: (u16, u16), width: u16, height: u16 },
  648. Circle { center: (u16, u16), radius: u16 },
  649. }
  650. let value = Shape::Circle { center: (0x1D42, 0x9FE0), radius: 0xA100 };
  651. let buffer = super::to_vec(&value)?;
  652. let expected = vec![
  653. 0x01, 0x00, // The variant index.
  654. 0x42, 0x1D, 0xE0, 0x9F, // The center.
  655. 0x00, 0xA1, // The radius.
  656. ];
  657. assert_eq!(expected, buffer);
  658. Ok(())
  659. }
  660. }