serial.rs 27 KB

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