serial.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. use bls12_381 as bls;
  2. use std::borrow::Cow;
  3. use std::io::{Cursor, Read, Write};
  4. use std::net::{IpAddr, SocketAddr};
  5. use std::{io, mem};
  6. use crate::endian;
  7. use crate::error::{Error, Result};
  8. /// Encode an object into a vector
  9. pub fn serialize<T: Encodable + ?Sized>(data: &T) -> Vec<u8> {
  10. let mut encoder = Vec::new();
  11. let len = data.encode(&mut encoder).unwrap();
  12. assert_eq!(len, encoder.len());
  13. encoder
  14. }
  15. /// Encode an object into a hex-encoded string
  16. pub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String {
  17. hex::encode(serialize(data))
  18. }
  19. /// Deserialize an object from a vector, will error if said deserialization
  20. /// doesn't consume the entire vector.
  21. pub fn deserialize<T: Decodable>(data: &[u8]) -> Result<T> {
  22. let (rv, consumed) = deserialize_partial(data)?;
  23. // Fail if data are not consumed entirely.
  24. if consumed == data.len() {
  25. Ok(rv)
  26. } else {
  27. Err(Error::ParseFailed(
  28. "data not consumed entirely when explicitly deserializing",
  29. ))
  30. }
  31. }
  32. /// Deserialize an object from a vector, but will not report an error if said deserialization
  33. /// doesn't consume the entire vector.
  34. pub fn deserialize_partial<T: Decodable>(data: &[u8]) -> Result<(T, usize)> {
  35. let mut decoder = Cursor::new(data);
  36. let rv = Decodable::decode(&mut decoder)?;
  37. let consumed = decoder.position() as usize;
  38. Ok((rv, consumed))
  39. }
  40. /// Extensions of `Write` to encode data as per Bitcoin consensus
  41. pub trait WriteExt {
  42. /// Output a 64-bit uint
  43. fn write_u64(&mut self, v: u64) -> Result<()>;
  44. /// Output a 32-bit uint
  45. fn write_u32(&mut self, v: u32) -> Result<()>;
  46. /// Output a 16-bit uint
  47. fn write_u16(&mut self, v: u16) -> Result<()>;
  48. /// Output a 8-bit uint
  49. fn write_u8(&mut self, v: u8) -> Result<()>;
  50. /// Output a 64-bit int
  51. fn write_i64(&mut self, v: i64) -> Result<()>;
  52. /// Output a 32-bit int
  53. fn write_i32(&mut self, v: i32) -> Result<()>;
  54. /// Output a 16-bit int
  55. fn write_i16(&mut self, v: i16) -> Result<()>;
  56. /// Output a 8-bit int
  57. fn write_i8(&mut self, v: i8) -> Result<()>;
  58. /// Output a boolean
  59. fn write_bool(&mut self, v: bool) -> Result<()>;
  60. /// Output a byte slice
  61. fn write_slice(&mut self, v: &[u8]) -> Result<()>;
  62. }
  63. /// Extensions of `Read` to decode data as per Bitcoin consensus
  64. pub trait ReadExt {
  65. /// Read a 64-bit uint
  66. fn read_u64(&mut self) -> Result<u64>;
  67. /// Read a 32-bit uint
  68. fn read_u32(&mut self) -> Result<u32>;
  69. /// Read a 16-bit uint
  70. fn read_u16(&mut self) -> Result<u16>;
  71. /// Read a 8-bit uint
  72. fn read_u8(&mut self) -> Result<u8>;
  73. /// Read a 64-bit int
  74. fn read_i64(&mut self) -> Result<i64>;
  75. /// Read a 32-bit int
  76. fn read_i32(&mut self) -> Result<i32>;
  77. /// Read a 16-bit int
  78. fn read_i16(&mut self) -> Result<i16>;
  79. /// Read a 8-bit int
  80. fn read_i8(&mut self) -> Result<i8>;
  81. /// Read a boolean
  82. fn read_bool(&mut self) -> Result<bool>;
  83. /// Read a byte slice
  84. fn read_slice(&mut self, slice: &mut [u8]) -> Result<()>;
  85. }
  86. macro_rules! encoder_fn {
  87. ($name:ident, $val_type:ty, $writefn:ident) => {
  88. #[inline]
  89. fn $name(&mut self, v: $val_type) -> Result<()> {
  90. self.write_all(&endian::$writefn(v)).map_err(Error::Io)
  91. }
  92. };
  93. }
  94. macro_rules! decoder_fn {
  95. ($name:ident, $val_type:ty, $readfn:ident, $byte_len: expr) => {
  96. #[inline]
  97. fn $name(&mut self) -> Result<$val_type> {
  98. assert_eq!(::std::mem::size_of::<$val_type>(), $byte_len); // size_of isn't a constfn in 1.22
  99. let mut val = [0; $byte_len];
  100. self.read_exact(&mut val[..]).map_err(Error::Io)?;
  101. Ok(endian::$readfn(&val))
  102. }
  103. };
  104. }
  105. impl<W: Write> WriteExt for W {
  106. encoder_fn!(write_u64, u64, u64_to_array_le);
  107. encoder_fn!(write_u32, u32, u32_to_array_le);
  108. encoder_fn!(write_u16, u16, u16_to_array_le);
  109. encoder_fn!(write_i64, i64, i64_to_array_le);
  110. encoder_fn!(write_i32, i32, i32_to_array_le);
  111. encoder_fn!(write_i16, i16, i16_to_array_le);
  112. #[inline]
  113. fn write_i8(&mut self, v: i8) -> Result<()> {
  114. self.write_all(&[v as u8]).map_err(Error::Io)
  115. }
  116. #[inline]
  117. fn write_u8(&mut self, v: u8) -> Result<()> {
  118. self.write_all(&[v]).map_err(Error::Io)
  119. }
  120. #[inline]
  121. fn write_bool(&mut self, v: bool) -> Result<()> {
  122. self.write_all(&[v as u8]).map_err(Error::Io)
  123. }
  124. #[inline]
  125. fn write_slice(&mut self, v: &[u8]) -> Result<()> {
  126. self.write_all(v).map_err(Error::Io)
  127. }
  128. }
  129. impl<R: Read> ReadExt for R {
  130. decoder_fn!(read_u64, u64, slice_to_u64_le, 8);
  131. decoder_fn!(read_u32, u32, slice_to_u32_le, 4);
  132. decoder_fn!(read_u16, u16, slice_to_u16_le, 2);
  133. decoder_fn!(read_i64, i64, slice_to_i64_le, 8);
  134. decoder_fn!(read_i32, i32, slice_to_i32_le, 4);
  135. decoder_fn!(read_i16, i16, slice_to_i16_le, 2);
  136. #[inline]
  137. fn read_u8(&mut self) -> Result<u8> {
  138. let mut slice = [0u8; 1];
  139. self.read_exact(&mut slice)?;
  140. Ok(slice[0])
  141. }
  142. #[inline]
  143. fn read_i8(&mut self) -> Result<i8> {
  144. let mut slice = [0u8; 1];
  145. self.read_exact(&mut slice)?;
  146. Ok(slice[0] as i8)
  147. }
  148. #[inline]
  149. fn read_bool(&mut self) -> Result<bool> {
  150. ReadExt::read_i8(self).map(|bit| bit != 0)
  151. }
  152. #[inline]
  153. fn read_slice(&mut self, slice: &mut [u8]) -> Result<()> {
  154. self.read_exact(slice).map_err(Error::Io)
  155. }
  156. }
  157. /// Data which can be encoded in a consensus-consistent way
  158. pub trait Encodable {
  159. /// Encode an object with a well-defined format, should only ever error if
  160. /// the underlying `Write` errors. Returns the number of bytes written on
  161. /// success
  162. fn encode<W: io::Write>(&self, e: W) -> Result<usize>;
  163. }
  164. /// Data which can be encoded in a consensus-consistent way
  165. pub trait Decodable: Sized {
  166. /// Decode an object with a well-defined format
  167. fn decode<D: io::Read>(d: D) -> Result<Self>;
  168. }
  169. #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
  170. pub struct VarInt(pub u64);
  171. // Primitive types
  172. macro_rules! impl_int_encodable {
  173. ($ty:ident, $meth_dec:ident, $meth_enc:ident) => {
  174. impl Decodable for $ty {
  175. #[inline]
  176. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  177. ReadExt::$meth_dec(&mut d).map($ty::from_le)
  178. }
  179. }
  180. impl Encodable for $ty {
  181. #[inline]
  182. fn encode<S: WriteExt>(&self, mut s: S) -> Result<usize> {
  183. s.$meth_enc(self.to_le())?;
  184. Ok(mem::size_of::<$ty>())
  185. }
  186. }
  187. };
  188. }
  189. impl_int_encodable!(u8, read_u8, write_u8);
  190. impl_int_encodable!(u16, read_u16, write_u16);
  191. impl_int_encodable!(u32, read_u32, write_u32);
  192. impl_int_encodable!(u64, read_u64, write_u64);
  193. impl_int_encodable!(i8, read_i8, write_i8);
  194. impl_int_encodable!(i16, read_i16, write_i16);
  195. impl_int_encodable!(i32, read_i32, write_i32);
  196. impl_int_encodable!(i64, read_i64, write_i64);
  197. impl VarInt {
  198. /// Gets the length of this VarInt when encoded.
  199. /// Returns 1 for 0...0xFC, 3 for 0xFD...(2^16-1), 5 for 0x10000...(2^32-1),
  200. /// and 9 otherwise.
  201. #[inline]
  202. pub fn len(&self) -> usize {
  203. match self.0 {
  204. 0..=0xFC => 1,
  205. 0xFD..=0xFFFF => 3,
  206. 0x10000..=0xFFFFFFFF => 5,
  207. _ => 9,
  208. }
  209. }
  210. }
  211. impl Encodable for VarInt {
  212. #[inline]
  213. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  214. match self.0 {
  215. 0..=0xFC => {
  216. (self.0 as u8).encode(s)?;
  217. Ok(1)
  218. }
  219. 0xFD..=0xFFFF => {
  220. s.write_u8(0xFD)?;
  221. (self.0 as u16).encode(s)?;
  222. Ok(3)
  223. }
  224. 0x10000..=0xFFFFFFFF => {
  225. s.write_u8(0xFE)?;
  226. (self.0 as u32).encode(s)?;
  227. Ok(5)
  228. }
  229. _ => {
  230. s.write_u8(0xFF)?;
  231. (self.0 as u64).encode(s)?;
  232. Ok(9)
  233. }
  234. }
  235. }
  236. }
  237. impl Decodable for VarInt {
  238. #[inline]
  239. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  240. let n = ReadExt::read_u8(&mut d)?;
  241. match n {
  242. 0xFF => {
  243. let x = ReadExt::read_u64(&mut d)?;
  244. if x < 0x100000000 {
  245. Err(self::Error::NonMinimalVarInt)
  246. } else {
  247. Ok(VarInt(x))
  248. }
  249. }
  250. 0xFE => {
  251. let x = ReadExt::read_u32(&mut d)?;
  252. if x < 0x10000 {
  253. Err(self::Error::NonMinimalVarInt)
  254. } else {
  255. Ok(VarInt(x as u64))
  256. }
  257. }
  258. 0xFD => {
  259. let x = ReadExt::read_u16(&mut d)?;
  260. if x < 0xFD {
  261. Err(self::Error::NonMinimalVarInt)
  262. } else {
  263. Ok(VarInt(x as u64))
  264. }
  265. }
  266. n => Ok(VarInt(n as u64)),
  267. }
  268. }
  269. }
  270. // Booleans
  271. impl Encodable for bool {
  272. #[inline]
  273. fn encode<S: WriteExt>(&self, mut s: S) -> Result<usize> {
  274. s.write_bool(*self)?;
  275. Ok(1)
  276. }
  277. }
  278. impl Decodable for bool {
  279. #[inline]
  280. fn decode<D: io::Read>(mut d: D) -> Result<bool> {
  281. ReadExt::read_bool(&mut d)
  282. }
  283. }
  284. // Strings
  285. impl Encodable for String {
  286. #[inline]
  287. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  288. let b = self.as_bytes();
  289. let vi_len = VarInt(b.len() as u64).encode(&mut s)?;
  290. s.write_slice(&b)?;
  291. Ok(vi_len + b.len())
  292. }
  293. }
  294. impl Decodable for String {
  295. #[inline]
  296. fn decode<D: io::Read>(d: D) -> Result<String> {
  297. String::from_utf8(Decodable::decode(d)?)
  298. .map_err(|_| self::Error::ParseFailed("String was not valid UTF8"))
  299. }
  300. }
  301. // Cow<'static, str>
  302. impl Encodable for Cow<'static, str> {
  303. #[inline]
  304. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  305. let b = self.as_bytes();
  306. let vi_len = VarInt(b.len() as u64).encode(&mut s)?;
  307. s.write_slice(&b)?;
  308. Ok(vi_len + b.len())
  309. }
  310. }
  311. impl Decodable for Cow<'static, str> {
  312. #[inline]
  313. fn decode<D: io::Read>(d: D) -> Result<Cow<'static, str>> {
  314. String::from_utf8(Decodable::decode(d)?)
  315. .map_err(|_| self::Error::ParseFailed("String was not valid UTF8"))
  316. .map(Cow::Owned)
  317. }
  318. }
  319. // Arrays
  320. macro_rules! impl_array {
  321. ( $size:expr ) => {
  322. impl Encodable for [u8; $size] {
  323. #[inline]
  324. fn encode<S: WriteExt>(&self, mut s: S) -> Result<usize> {
  325. s.write_slice(&self[..])?;
  326. Ok(self.len())
  327. }
  328. }
  329. impl Decodable for [u8; $size] {
  330. #[inline]
  331. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  332. let mut ret = [0; $size];
  333. d.read_slice(&mut ret)?;
  334. Ok(ret)
  335. }
  336. }
  337. };
  338. }
  339. impl_array!(2);
  340. impl_array!(4);
  341. impl_array!(8);
  342. impl_array!(12);
  343. impl_array!(16);
  344. impl_array!(32);
  345. impl_array!(33);
  346. // Vectors
  347. #[macro_export]
  348. macro_rules! impl_vec {
  349. ($type: ty) => {
  350. impl Encodable for Vec<$type> {
  351. #[inline]
  352. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  353. let mut len = 0;
  354. len += VarInt(self.len() as u64).encode(&mut s)?;
  355. for c in self.iter() {
  356. len += c.encode(&mut s)?;
  357. }
  358. Ok(len)
  359. }
  360. }
  361. impl Decodable for Vec<$type> {
  362. #[inline]
  363. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  364. let len = VarInt::decode(&mut d)?.0;
  365. let mut ret = Vec::with_capacity(len as usize);
  366. for _ in 0..len {
  367. ret.push(Decodable::decode(&mut d)?);
  368. }
  369. Ok(ret)
  370. }
  371. }
  372. };
  373. }
  374. impl_vec!(bls::Scalar);
  375. impl_vec!(SocketAddr);
  376. impl_vec!([u8; 32]);
  377. impl Encodable for IpAddr {
  378. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  379. let mut len = 0;
  380. match self {
  381. IpAddr::V4(ip) => {
  382. let version: u8 = 4;
  383. len += version.encode(&mut s)?;
  384. len += ip.octets().encode(s)?;
  385. }
  386. IpAddr::V6(ip) => {
  387. let version: u8 = 6;
  388. len += version.encode(&mut s)?;
  389. len += ip.octets().encode(s)?;
  390. }
  391. }
  392. Ok(len)
  393. }
  394. }
  395. impl Decodable for IpAddr {
  396. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  397. let version: u8 = Decodable::decode(&mut d)?;
  398. match version {
  399. 4 => {
  400. let addr: [u8; 4] = Decodable::decode(&mut d)?;
  401. Ok(IpAddr::from(addr))
  402. }
  403. 6 => {
  404. let addr: [u8; 16] = Decodable::decode(&mut d)?;
  405. Ok(IpAddr::from(addr))
  406. }
  407. _ => Err(Error::ParseFailed("couldn't decode IpAddr")),
  408. }
  409. }
  410. }
  411. impl Encodable for SocketAddr {
  412. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  413. let mut len = 0;
  414. len += self.ip().encode(&mut s)?;
  415. len += self.port().encode(s)?;
  416. Ok(len)
  417. }
  418. }
  419. impl Decodable for SocketAddr {
  420. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  421. let ip = Decodable::decode(&mut d)?;
  422. let port: u16 = Decodable::decode(d)?;
  423. Ok(SocketAddr::new(ip, port))
  424. }
  425. }
  426. pub fn encode_with_size<S: io::Write>(data: &[u8], mut s: S) -> Result<usize> {
  427. let vi_len = VarInt(data.len() as u64).encode(&mut s)?;
  428. s.write_slice(&data)?;
  429. Ok(vi_len + data.len())
  430. }
  431. impl Encodable for Vec<u8> {
  432. #[inline]
  433. fn encode<S: io::Write>(&self, s: S) -> Result<usize> {
  434. encode_with_size(self, s)
  435. }
  436. }
  437. impl Decodable for Vec<u8> {
  438. #[inline]
  439. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  440. let len = VarInt::decode(&mut d)?.0 as usize;
  441. let mut ret = vec![0u8; len];
  442. d.read_slice(&mut ret)?;
  443. Ok(ret)
  444. }
  445. }
  446. impl Encodable for Box<[u8]> {
  447. #[inline]
  448. fn encode<S: io::Write>(&self, s: S) -> Result<usize> {
  449. encode_with_size(self, s)
  450. }
  451. }
  452. impl Decodable for Box<[u8]> {
  453. #[inline]
  454. fn decode<D: io::Read>(d: D) -> Result<Self> {
  455. <Vec<u8>>::decode(d).map(From::from)
  456. }
  457. }
  458. // Tuples
  459. macro_rules! tuple_encode {
  460. ($($x:ident),*) => (
  461. impl <$($x: Encodable),*> Encodable for ($($x),*) {
  462. #[inline]
  463. #[allow(non_snake_case)]
  464. fn encode<S: io::Write>(
  465. &self,
  466. mut s: S,
  467. ) -> Result<usize> {
  468. let &($(ref $x),*) = self;
  469. let mut len = 0;
  470. $(len += $x.encode(&mut s)?;)*
  471. Ok(len)
  472. }
  473. }
  474. impl<$($x: Decodable),*> Decodable for ($($x),*) {
  475. #[inline]
  476. #[allow(non_snake_case)]
  477. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  478. Ok(($({let $x = Decodable::decode(&mut d)?; $x }),*))
  479. }
  480. }
  481. );
  482. }
  483. tuple_encode!(T0, T1);
  484. tuple_encode!(T0, T1, T2, T3);
  485. tuple_encode!(T0, T1, T2, T3, T4, T5);
  486. tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);
  487. #[cfg(test)]
  488. mod tests {
  489. use super::{deserialize, serialize, Error, Result, VarInt};
  490. use super::{deserialize_partial, Encodable};
  491. use crate::endian::{u16_to_array_le, u32_to_array_le, u64_to_array_le};
  492. use std::io;
  493. use std::mem::discriminant;
  494. #[test]
  495. fn serialize_int_test() {
  496. // bool
  497. assert_eq!(serialize(&false), vec![0u8]);
  498. assert_eq!(serialize(&true), vec![1u8]);
  499. // u8
  500. assert_eq!(serialize(&1u8), vec![1u8]);
  501. assert_eq!(serialize(&0u8), vec![0u8]);
  502. assert_eq!(serialize(&255u8), vec![255u8]);
  503. // u16
  504. assert_eq!(serialize(&1u16), vec![1u8, 0]);
  505. assert_eq!(serialize(&256u16), vec![0u8, 1]);
  506. assert_eq!(serialize(&5000u16), vec![136u8, 19]);
  507. // u32
  508. assert_eq!(serialize(&1u32), vec![1u8, 0, 0, 0]);
  509. assert_eq!(serialize(&256u32), vec![0u8, 1, 0, 0]);
  510. assert_eq!(serialize(&5000u32), vec![136u8, 19, 0, 0]);
  511. assert_eq!(serialize(&500000u32), vec![32u8, 161, 7, 0]);
  512. assert_eq!(serialize(&168430090u32), vec![10u8, 10, 10, 10]);
  513. // i32
  514. assert_eq!(serialize(&-1i32), vec![255u8, 255, 255, 255]);
  515. assert_eq!(serialize(&-256i32), vec![0u8, 255, 255, 255]);
  516. assert_eq!(serialize(&-5000i32), vec![120u8, 236, 255, 255]);
  517. assert_eq!(serialize(&-500000i32), vec![224u8, 94, 248, 255]);
  518. assert_eq!(serialize(&-168430090i32), vec![246u8, 245, 245, 245]);
  519. assert_eq!(serialize(&1i32), vec![1u8, 0, 0, 0]);
  520. assert_eq!(serialize(&256i32), vec![0u8, 1, 0, 0]);
  521. assert_eq!(serialize(&5000i32), vec![136u8, 19, 0, 0]);
  522. assert_eq!(serialize(&500000i32), vec![32u8, 161, 7, 0]);
  523. assert_eq!(serialize(&168430090i32), vec![10u8, 10, 10, 10]);
  524. // u64
  525. assert_eq!(serialize(&1u64), vec![1u8, 0, 0, 0, 0, 0, 0, 0]);
  526. assert_eq!(serialize(&256u64), vec![0u8, 1, 0, 0, 0, 0, 0, 0]);
  527. assert_eq!(serialize(&5000u64), vec![136u8, 19, 0, 0, 0, 0, 0, 0]);
  528. assert_eq!(serialize(&500000u64), vec![32u8, 161, 7, 0, 0, 0, 0, 0]);
  529. assert_eq!(
  530. serialize(&723401728380766730u64),
  531. vec![10u8, 10, 10, 10, 10, 10, 10, 10]
  532. );
  533. // i64
  534. assert_eq!(
  535. serialize(&-1i64),
  536. vec![255u8, 255, 255, 255, 255, 255, 255, 255]
  537. );
  538. assert_eq!(
  539. serialize(&-256i64),
  540. vec![0u8, 255, 255, 255, 255, 255, 255, 255]
  541. );
  542. assert_eq!(
  543. serialize(&-5000i64),
  544. vec![120u8, 236, 255, 255, 255, 255, 255, 255]
  545. );
  546. assert_eq!(
  547. serialize(&-500000i64),
  548. vec![224u8, 94, 248, 255, 255, 255, 255, 255]
  549. );
  550. assert_eq!(
  551. serialize(&-723401728380766730i64),
  552. vec![246u8, 245, 245, 245, 245, 245, 245, 245]
  553. );
  554. assert_eq!(serialize(&1i64), vec![1u8, 0, 0, 0, 0, 0, 0, 0]);
  555. assert_eq!(serialize(&256i64), vec![0u8, 1, 0, 0, 0, 0, 0, 0]);
  556. assert_eq!(serialize(&5000i64), vec![136u8, 19, 0, 0, 0, 0, 0, 0]);
  557. assert_eq!(serialize(&500000i64), vec![32u8, 161, 7, 0, 0, 0, 0, 0]);
  558. assert_eq!(
  559. serialize(&723401728380766730i64),
  560. vec![10u8, 10, 10, 10, 10, 10, 10, 10]
  561. );
  562. }
  563. #[test]
  564. fn serialize_varint_test() {
  565. assert_eq!(serialize(&VarInt(10)), vec![10u8]);
  566. assert_eq!(serialize(&VarInt(0xFC)), vec![0xFCu8]);
  567. assert_eq!(serialize(&VarInt(0xFD)), vec![0xFDu8, 0xFD, 0]);
  568. assert_eq!(serialize(&VarInt(0xFFF)), vec![0xFDu8, 0xFF, 0xF]);
  569. assert_eq!(
  570. serialize(&VarInt(0xF0F0F0F)),
  571. vec![0xFEu8, 0xF, 0xF, 0xF, 0xF]
  572. );
  573. assert_eq!(
  574. serialize(&VarInt(0xF0F0F0F0F0E0)),
  575. vec![0xFFu8, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0, 0]
  576. );
  577. assert_eq!(
  578. test_varint_encode(0xFF, &u64_to_array_le(0x100000000)).unwrap(),
  579. VarInt(0x100000000)
  580. );
  581. assert_eq!(
  582. test_varint_encode(0xFE, &u64_to_array_le(0x10000)).unwrap(),
  583. VarInt(0x10000)
  584. );
  585. assert_eq!(
  586. test_varint_encode(0xFD, &u64_to_array_le(0xFD)).unwrap(),
  587. VarInt(0xFD)
  588. );
  589. // Test that length calc is working correctly
  590. test_varint_len(VarInt(0), 1);
  591. test_varint_len(VarInt(0xFC), 1);
  592. test_varint_len(VarInt(0xFD), 3);
  593. test_varint_len(VarInt(0xFFFF), 3);
  594. test_varint_len(VarInt(0x10000), 5);
  595. test_varint_len(VarInt(0xFFFFFFFF), 5);
  596. test_varint_len(VarInt(0xFFFFFFFF + 1), 9);
  597. test_varint_len(VarInt(u64::max_value()), 9);
  598. }
  599. fn test_varint_len(varint: VarInt, expected: usize) {
  600. let mut encoder = io::Cursor::new(vec![]);
  601. assert_eq!(varint.encode(&mut encoder).unwrap(), expected);
  602. assert_eq!(varint.len(), expected);
  603. }
  604. fn test_varint_encode(n: u8, x: &[u8]) -> Result<VarInt> {
  605. let mut input = [0u8; 9];
  606. input[0] = n;
  607. input[1..x.len() + 1].copy_from_slice(x);
  608. deserialize_partial::<VarInt>(&input).map(|t| t.0)
  609. }
  610. #[test]
  611. fn deserialize_nonminimal_vec() {
  612. // Check the edges for variant int
  613. assert_eq!(
  614. discriminant(&test_varint_encode(0xFF, &u64_to_array_le(0x100000000 - 1)).unwrap_err()),
  615. discriminant(&Error::NonMinimalVarInt)
  616. );
  617. assert_eq!(
  618. discriminant(&test_varint_encode(0xFE, &u32_to_array_le(0x10000 - 1)).unwrap_err()),
  619. discriminant(&Error::NonMinimalVarInt)
  620. );
  621. assert_eq!(
  622. discriminant(&test_varint_encode(0xFD, &u16_to_array_le(0xFD - 1)).unwrap_err()),
  623. discriminant(&Error::NonMinimalVarInt)
  624. );
  625. assert_eq!(
  626. discriminant(&deserialize::<Vec<u8>>(&[0xfd, 0x00, 0x00]).unwrap_err()),
  627. discriminant(&Error::NonMinimalVarInt)
  628. );
  629. assert_eq!(
  630. discriminant(&deserialize::<Vec<u8>>(&[0xfd, 0xfc, 0x00]).unwrap_err()),
  631. discriminant(&Error::NonMinimalVarInt)
  632. );
  633. assert_eq!(
  634. discriminant(&deserialize::<Vec<u8>>(&[0xfd, 0xfc, 0x00]).unwrap_err()),
  635. discriminant(&Error::NonMinimalVarInt)
  636. );
  637. assert_eq!(
  638. discriminant(&deserialize::<Vec<u8>>(&[0xfe, 0xff, 0x00, 0x00, 0x00]).unwrap_err()),
  639. discriminant(&Error::NonMinimalVarInt)
  640. );
  641. assert_eq!(
  642. discriminant(&deserialize::<Vec<u8>>(&[0xfe, 0xff, 0xff, 0x00, 0x00]).unwrap_err()),
  643. discriminant(&Error::NonMinimalVarInt)
  644. );
  645. assert_eq!(
  646. discriminant(
  647. &deserialize::<Vec<u8>>(&[0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
  648. .unwrap_err()
  649. ),
  650. discriminant(&Error::NonMinimalVarInt)
  651. );
  652. assert_eq!(
  653. discriminant(
  654. &deserialize::<Vec<u8>>(&[0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00])
  655. .unwrap_err()
  656. ),
  657. discriminant(&Error::NonMinimalVarInt)
  658. );
  659. let mut vec_256 = vec![0; 259];
  660. vec_256[0] = 0xfd;
  661. vec_256[1] = 0x00;
  662. vec_256[2] = 0x01;
  663. assert!(deserialize::<Vec<u8>>(&vec_256).is_ok());
  664. let mut vec_253 = vec![0; 256];
  665. vec_253[0] = 0xfd;
  666. vec_253[1] = 0xfd;
  667. vec_253[2] = 0x00;
  668. assert!(deserialize::<Vec<u8>>(&vec_253).is_ok());
  669. }
  670. #[test]
  671. fn serialize_vector_test() {
  672. assert_eq!(serialize(&vec![1u8, 2, 3]), vec![3u8, 1, 2, 3]);
  673. // TODO: test vectors of more interesting objects
  674. }
  675. #[test]
  676. fn serialize_strbuf_test() {
  677. assert_eq!(
  678. serialize(&"Andrew".to_string()),
  679. vec![6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]
  680. );
  681. }
  682. #[test]
  683. fn deserialize_int_test() {
  684. // bool
  685. assert!((deserialize(&[58u8, 0]) as Result<bool>).is_err());
  686. assert_eq!(deserialize(&[58u8]).ok(), Some(true));
  687. assert_eq!(deserialize(&[1u8]).ok(), Some(true));
  688. assert_eq!(deserialize(&[0u8]).ok(), Some(false));
  689. assert!((deserialize(&[0u8, 1]) as Result<bool>).is_err());
  690. // u8
  691. assert_eq!(deserialize(&[58u8]).ok(), Some(58u8));
  692. // u16
  693. assert_eq!(deserialize(&[0x01u8, 0x02]).ok(), Some(0x0201u16));
  694. assert_eq!(deserialize(&[0xABu8, 0xCD]).ok(), Some(0xCDABu16));
  695. assert_eq!(deserialize(&[0xA0u8, 0x0D]).ok(), Some(0xDA0u16));
  696. let failure16: Result<u16> = deserialize(&[1u8]);
  697. assert!(failure16.is_err());
  698. // u32
  699. assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABu32));
  700. assert_eq!(
  701. deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD]).ok(),
  702. Some(0xCDAB0DA0u32)
  703. );
  704. let failure32: Result<u32> = deserialize(&[1u8, 2, 3]);
  705. assert!(failure32.is_err());
  706. // TODO: test negative numbers
  707. assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABi32));
  708. assert_eq!(
  709. deserialize(&[0xA0u8, 0x0D, 0xAB, 0x2D]).ok(),
  710. Some(0x2DAB0DA0i32)
  711. );
  712. let failurei32: Result<i32> = deserialize(&[1u8, 2, 3]);
  713. assert!(failurei32.is_err());
  714. // u64
  715. assert_eq!(
  716. deserialize(&[0xABu8, 0xCD, 0, 0, 0, 0, 0, 0]).ok(),
  717. Some(0xCDABu64)
  718. );
  719. assert_eq!(
  720. deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD, 0x99, 0, 0, 0x99]).ok(),
  721. Some(0x99000099CDAB0DA0u64)
  722. );
  723. let failure64: Result<u64> = deserialize(&[1u8, 2, 3, 4, 5, 6, 7]);
  724. assert!(failure64.is_err());
  725. // TODO: test negative numbers
  726. assert_eq!(
  727. deserialize(&[0xABu8, 0xCD, 0, 0, 0, 0, 0, 0]).ok(),
  728. Some(0xCDABi64)
  729. );
  730. assert_eq!(
  731. deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD, 0x99, 0, 0, 0x99]).ok(),
  732. Some(-0x66ffff663254f260i64)
  733. );
  734. let failurei64: Result<i64> = deserialize(&[1u8, 2, 3, 4, 5, 6, 7]);
  735. assert!(failurei64.is_err());
  736. }
  737. #[test]
  738. fn deserialize_vec_test() {
  739. assert_eq!(deserialize(&[3u8, 2, 3, 4]).ok(), Some(vec![2u8, 3, 4]));
  740. assert!((deserialize(&[4u8, 2, 3, 4, 5, 6]) as Result<Vec<u8>>).is_err());
  741. }
  742. #[test]
  743. fn deserialize_strbuf_test() {
  744. assert_eq!(
  745. deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(),
  746. Some("Andrew".to_string())
  747. );
  748. assert_eq!(
  749. deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(),
  750. Some(::std::borrow::Cow::Borrowed("Andrew"))
  751. );
  752. }
  753. }