serial.rs 27 KB

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