ser.rs 23 KB

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