serial.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. use std::{
  2. borrow::Cow,
  3. io,
  4. io::{Cursor, Read, Write},
  5. mem,
  6. net::{IpAddr, SocketAddr},
  7. };
  8. use crate::{
  9. endian,
  10. error::{Error, Result},
  11. };
  12. /// Encode an object into a vector
  13. pub fn serialize<T: Encodable + ?Sized>(data: &T) -> Vec<u8> {
  14. let mut encoder = Vec::new();
  15. let len = data.encode(&mut encoder).unwrap();
  16. assert_eq!(len, encoder.len());
  17. encoder
  18. }
  19. /// Encode an object into a hex-encoded string
  20. pub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String {
  21. hex::encode(serialize(data))
  22. }
  23. /// Deserialize an object from a vector, will error if said deserialization
  24. /// doesn't consume the entire vector.
  25. pub fn deserialize<T: Decodable>(data: &[u8]) -> Result<T> {
  26. let (rv, consumed) = deserialize_partial(data)?;
  27. // Fail if data are not consumed entirely.
  28. if consumed == data.len() {
  29. Ok(rv)
  30. } else {
  31. Err(Error::ParseFailed("data not consumed entirely when explicitly deserializing"))
  32. }
  33. }
  34. /// Deserialize an object from a vector, but will not report an error if said
  35. /// deserialization doesn't consume the entire vector.
  36. pub fn deserialize_partial<T: Decodable>(data: &[u8]) -> Result<(T, usize)> {
  37. let mut decoder = Cursor::new(data);
  38. let rv = Decodable::decode(&mut decoder)?;
  39. let consumed = decoder.position() as usize;
  40. Ok((rv, consumed))
  41. }
  42. /// Extensions of `Write` to encode data as per Bitcoin consensus
  43. pub trait WriteExt {
  44. /// Output a 64-bit uint
  45. fn write_u64(&mut self, v: u64) -> Result<()>;
  46. /// Output a 32-bit uint
  47. fn write_u32(&mut self, v: u32) -> Result<()>;
  48. /// Output a 16-bit uint
  49. fn write_u16(&mut self, v: u16) -> Result<()>;
  50. /// Output a 8-bit uint
  51. fn write_u8(&mut self, v: u8) -> Result<()>;
  52. /// Output a 64-bit int
  53. fn write_i64(&mut self, v: i64) -> Result<()>;
  54. /// Output a 32-bit int
  55. fn write_i32(&mut self, v: i32) -> Result<()>;
  56. /// Output a 16-bit int
  57. fn write_i16(&mut self, v: i16) -> Result<()>;
  58. /// Output a 8-bit int
  59. fn write_i8(&mut self, v: i8) -> Result<()>;
  60. /// Output a boolean
  61. fn write_bool(&mut self, v: bool) -> Result<()>;
  62. /// Output a byte slice
  63. fn write_slice(&mut self, v: &[u8]) -> Result<()>;
  64. }
  65. /// Extensions of `Read` to decode data as per Bitcoin consensus
  66. pub trait ReadExt {
  67. /// Read a 64-bit uint
  68. fn read_u64(&mut self) -> Result<u64>;
  69. /// Read a 32-bit uint
  70. fn read_u32(&mut self) -> Result<u32>;
  71. /// Read a 16-bit uint
  72. fn read_u16(&mut self) -> Result<u16>;
  73. /// Read a 8-bit uint
  74. fn read_u8(&mut self) -> Result<u8>;
  75. /// Read a 64-bit int
  76. fn read_i64(&mut self) -> Result<i64>;
  77. /// Read a 32-bit int
  78. fn read_i32(&mut self) -> Result<i32>;
  79. /// Read a 16-bit int
  80. fn read_i16(&mut self) -> Result<i16>;
  81. /// Read a 8-bit int
  82. fn read_i8(&mut self) -> Result<i8>;
  83. /// Read a boolean
  84. fn read_bool(&mut self) -> Result<bool>;
  85. /// Read a byte slice
  86. fn read_slice(&mut self, slice: &mut [u8]) -> Result<()>;
  87. }
  88. macro_rules! encoder_fn {
  89. ($name:ident, $val_type:ty, $writefn:ident) => {
  90. #[inline]
  91. fn $name(&mut self, v: $val_type) -> Result<()> {
  92. self.write_all(&endian::$writefn(v)).map_err(|e| Error::Io(e.kind()))
  93. }
  94. };
  95. }
  96. macro_rules! decoder_fn {
  97. ($name:ident, $val_type:ty, $readfn:ident, $byte_len: expr) => {
  98. #[inline]
  99. fn $name(&mut self) -> Result<$val_type> {
  100. assert_eq!(::std::mem::size_of::<$val_type>(), $byte_len); // size_of isn't a constfn in 1.22
  101. let mut val = [0; $byte_len];
  102. self.read_exact(&mut val[..]).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 length(&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. impl<const N: usize> Encodable for [u8; N] {
  322. #[inline]
  323. fn encode<S: WriteExt>(&self, mut s: S) -> Result<usize> {
  324. s.write_slice(&self[..])?;
  325. Ok(self.len())
  326. }
  327. }
  328. impl<const N: usize> Decodable for [u8; N] {
  329. #[inline]
  330. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  331. let mut ret = [0; N];
  332. d.read_slice(&mut ret)?;
  333. Ok(ret)
  334. }
  335. }
  336. // Options
  337. impl<T: Encodable> Encodable for Option<T> {
  338. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  339. let mut len = 0;
  340. if let Some(v) = self {
  341. len += true.encode(&mut s)?;
  342. len += v.encode(&mut s)?;
  343. } else {
  344. len += false.encode(&mut s)?;
  345. }
  346. Ok(len)
  347. }
  348. }
  349. impl<T: Decodable> Decodable for Option<T> {
  350. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  351. let valid: bool = Decodable::decode(&mut d)?;
  352. let mut val: Option<T> = None;
  353. if valid {
  354. val = Some(Decodable::decode(&mut d)?);
  355. }
  356. Ok(val)
  357. }
  358. }
  359. impl<T: Encodable> Encodable for Vec<Option<T>> {
  360. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  361. let mut len = 0;
  362. len += VarInt(self.len() as u64).encode(&mut s)?;
  363. for val in self {
  364. len += val.encode(&mut s)?;
  365. }
  366. Ok(len)
  367. }
  368. }
  369. impl<T: Decodable> Decodable for Vec<Option<T>> {
  370. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  371. let len = VarInt::decode(&mut d)?.0;
  372. let mut ret = Vec::with_capacity(len as usize);
  373. for _ in 0..len {
  374. ret.push(Decodable::decode(&mut d)?);
  375. }
  376. Ok(ret)
  377. }
  378. }
  379. // Vectors
  380. #[macro_export]
  381. macro_rules! impl_vec {
  382. ($type: ty) => {
  383. impl Encodable for Vec<$type> {
  384. #[inline]
  385. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  386. let mut len = 0;
  387. len += VarInt(self.len() as u64).encode(&mut s)?;
  388. for c in self.iter() {
  389. len += c.encode(&mut s)?;
  390. }
  391. Ok(len)
  392. }
  393. }
  394. impl Decodable for Vec<$type> {
  395. #[inline]
  396. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  397. let len = VarInt::decode(&mut d)?.0;
  398. let mut ret = Vec::with_capacity(len as usize);
  399. for _ in 0..len {
  400. ret.push(Decodable::decode(&mut d)?);
  401. }
  402. Ok(ret)
  403. }
  404. }
  405. };
  406. }
  407. impl_vec!(SocketAddr);
  408. impl_vec!([u8; 32]);
  409. impl Encodable for IpAddr {
  410. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  411. let mut len = 0;
  412. match self {
  413. IpAddr::V4(ip) => {
  414. let version: u8 = 4;
  415. len += version.encode(&mut s)?;
  416. len += ip.octets().encode(s)?;
  417. }
  418. IpAddr::V6(ip) => {
  419. let version: u8 = 6;
  420. len += version.encode(&mut s)?;
  421. len += ip.octets().encode(s)?;
  422. }
  423. }
  424. Ok(len)
  425. }
  426. }
  427. impl Decodable for IpAddr {
  428. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  429. let version: u8 = Decodable::decode(&mut d)?;
  430. match version {
  431. 4 => {
  432. let addr: [u8; 4] = Decodable::decode(&mut d)?;
  433. Ok(IpAddr::from(addr))
  434. }
  435. 6 => {
  436. let addr: [u8; 16] = Decodable::decode(&mut d)?;
  437. Ok(IpAddr::from(addr))
  438. }
  439. _ => Err(Error::ParseFailed("couldn't decode IpAddr")),
  440. }
  441. }
  442. }
  443. impl Encodable for SocketAddr {
  444. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  445. let mut len = 0;
  446. len += self.ip().encode(&mut s)?;
  447. len += self.port().encode(s)?;
  448. Ok(len)
  449. }
  450. }
  451. impl Decodable for SocketAddr {
  452. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  453. let ip = Decodable::decode(&mut d)?;
  454. let port: u16 = Decodable::decode(d)?;
  455. Ok(SocketAddr::new(ip, port))
  456. }
  457. }
  458. pub fn encode_with_size<S: io::Write>(data: &[u8], mut s: S) -> Result<usize> {
  459. let vi_len = VarInt(data.len() as u64).encode(&mut s)?;
  460. s.write_slice(data)?;
  461. Ok(vi_len + data.len())
  462. }
  463. impl Encodable for Vec<u8> {
  464. #[inline]
  465. fn encode<S: io::Write>(&self, s: S) -> Result<usize> {
  466. encode_with_size(self, s)
  467. }
  468. }
  469. impl Decodable for Vec<u8> {
  470. #[inline]
  471. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  472. let len = VarInt::decode(&mut d)?.0 as usize;
  473. let mut ret = vec![0u8; len];
  474. d.read_slice(&mut ret)?;
  475. Ok(ret)
  476. }
  477. }
  478. impl Encodable for Box<[u8]> {
  479. #[inline]
  480. fn encode<S: io::Write>(&self, s: S) -> Result<usize> {
  481. encode_with_size(self, s)
  482. }
  483. }
  484. impl Decodable for Box<[u8]> {
  485. #[inline]
  486. fn decode<D: io::Read>(d: D) -> Result<Self> {
  487. <Vec<u8>>::decode(d).map(From::from)
  488. }
  489. }
  490. // Tuples
  491. macro_rules! tuple_encode {
  492. ($($x:ident),*) => (
  493. impl <$($x: Encodable),*> Encodable for ($($x),*) {
  494. #[inline]
  495. #[allow(non_snake_case)]
  496. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  497. let &($(ref $x),*) = self;
  498. let mut len = 0;
  499. $(len += $x.encode(&mut s)?;)*
  500. Ok(len)
  501. }
  502. }
  503. impl<$($x: Decodable),*> Decodable for ($($x),*) {
  504. #[inline]
  505. #[allow(non_snake_case)]
  506. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  507. Ok(($({let $x = Decodable::decode(&mut d)?; $x }),*))
  508. }
  509. }
  510. );
  511. }
  512. tuple_encode!(T0, T1);
  513. tuple_encode!(T0, T1, T2, T3);
  514. tuple_encode!(T0, T1, T2, T3, T4, T5);
  515. tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);
  516. #[cfg(test)]
  517. mod tests {
  518. use super::{deserialize, deserialize_partial, serialize, Encodable, Error, Result, VarInt};
  519. use crate::endian::{u16_to_array_le, u32_to_array_le, u64_to_array_le};
  520. use std::{io, mem::discriminant};
  521. #[test]
  522. fn serialize_int_test() {
  523. // bool
  524. assert_eq!(serialize(&false), vec![0u8]);
  525. assert_eq!(serialize(&true), vec![1u8]);
  526. // u8
  527. assert_eq!(serialize(&1u8), vec![1u8]);
  528. assert_eq!(serialize(&0u8), vec![0u8]);
  529. assert_eq!(serialize(&255u8), vec![255u8]);
  530. // u16
  531. assert_eq!(serialize(&1u16), vec![1u8, 0]);
  532. assert_eq!(serialize(&256u16), vec![0u8, 1]);
  533. assert_eq!(serialize(&5000u16), vec![136u8, 19]);
  534. // u32
  535. assert_eq!(serialize(&1u32), vec![1u8, 0, 0, 0]);
  536. assert_eq!(serialize(&256u32), vec![0u8, 1, 0, 0]);
  537. assert_eq!(serialize(&5000u32), vec![136u8, 19, 0, 0]);
  538. assert_eq!(serialize(&500000u32), vec![32u8, 161, 7, 0]);
  539. assert_eq!(serialize(&168430090u32), vec![10u8, 10, 10, 10]);
  540. // i32
  541. assert_eq!(serialize(&-1i32), vec![255u8, 255, 255, 255]);
  542. assert_eq!(serialize(&-256i32), vec![0u8, 255, 255, 255]);
  543. assert_eq!(serialize(&-5000i32), vec![120u8, 236, 255, 255]);
  544. assert_eq!(serialize(&-500000i32), vec![224u8, 94, 248, 255]);
  545. assert_eq!(serialize(&-168430090i32), vec![246u8, 245, 245, 245]);
  546. assert_eq!(serialize(&1i32), vec![1u8, 0, 0, 0]);
  547. assert_eq!(serialize(&256i32), vec![0u8, 1, 0, 0]);
  548. assert_eq!(serialize(&5000i32), vec![136u8, 19, 0, 0]);
  549. assert_eq!(serialize(&500000i32), vec![32u8, 161, 7, 0]);
  550. assert_eq!(serialize(&168430090i32), vec![10u8, 10, 10, 10]);
  551. // u64
  552. assert_eq!(serialize(&1u64), vec![1u8, 0, 0, 0, 0, 0, 0, 0]);
  553. assert_eq!(serialize(&256u64), vec![0u8, 1, 0, 0, 0, 0, 0, 0]);
  554. assert_eq!(serialize(&5000u64), vec![136u8, 19, 0, 0, 0, 0, 0, 0]);
  555. assert_eq!(serialize(&500000u64), vec![32u8, 161, 7, 0, 0, 0, 0, 0]);
  556. assert_eq!(serialize(&723401728380766730u64), vec![10u8, 10, 10, 10, 10, 10, 10, 10]);
  557. // i64
  558. assert_eq!(serialize(&-1i64), vec![255u8, 255, 255, 255, 255, 255, 255, 255]);
  559. assert_eq!(serialize(&-256i64), vec![0u8, 255, 255, 255, 255, 255, 255, 255]);
  560. assert_eq!(serialize(&-5000i64), vec![120u8, 236, 255, 255, 255, 255, 255, 255]);
  561. assert_eq!(serialize(&-500000i64), vec![224u8, 94, 248, 255, 255, 255, 255, 255]);
  562. assert_eq!(
  563. serialize(&-723401728380766730i64),
  564. vec![246u8, 245, 245, 245, 245, 245, 245, 245]
  565. );
  566. assert_eq!(serialize(&1i64), vec![1u8, 0, 0, 0, 0, 0, 0, 0]);
  567. assert_eq!(serialize(&256i64), vec![0u8, 1, 0, 0, 0, 0, 0, 0]);
  568. assert_eq!(serialize(&5000i64), vec![136u8, 19, 0, 0, 0, 0, 0, 0]);
  569. assert_eq!(serialize(&500000i64), vec![32u8, 161, 7, 0, 0, 0, 0, 0]);
  570. assert_eq!(serialize(&723401728380766730i64), vec![10u8, 10, 10, 10, 10, 10, 10, 10]);
  571. }
  572. #[test]
  573. fn serialize_varint_test() {
  574. assert_eq!(serialize(&VarInt(10)), vec![10u8]);
  575. assert_eq!(serialize(&VarInt(0xFC)), vec![0xFCu8]);
  576. assert_eq!(serialize(&VarInt(0xFD)), vec![0xFDu8, 0xFD, 0]);
  577. assert_eq!(serialize(&VarInt(0xFFF)), vec![0xFDu8, 0xFF, 0xF]);
  578. assert_eq!(serialize(&VarInt(0xF0F0F0F)), vec![0xFEu8, 0xF, 0xF, 0xF, 0xF]);
  579. assert_eq!(
  580. serialize(&VarInt(0xF0F0F0F0F0E0)),
  581. vec![0xFFu8, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0, 0]
  582. );
  583. assert_eq!(
  584. test_varint_encode(0xFF, &u64_to_array_le(0x100000000)).unwrap(),
  585. VarInt(0x100000000)
  586. );
  587. assert_eq!(test_varint_encode(0xFE, &u64_to_array_le(0x10000)).unwrap(), VarInt(0x10000));
  588. assert_eq!(test_varint_encode(0xFD, &u64_to_array_le(0xFD)).unwrap(), VarInt(0xFD));
  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.length(), 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!(serialize(&"Andrew".to_string()), vec![6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]);
  678. }
  679. #[test]
  680. fn deserialize_int_test() {
  681. // bool
  682. assert!((deserialize(&[58u8, 0]) as Result<bool>).is_err());
  683. assert_eq!(deserialize(&[58u8]).ok(), Some(true));
  684. assert_eq!(deserialize(&[1u8]).ok(), Some(true));
  685. assert_eq!(deserialize(&[0u8]).ok(), Some(false));
  686. assert!((deserialize(&[0u8, 1]) as Result<bool>).is_err());
  687. // u8
  688. assert_eq!(deserialize(&[58u8]).ok(), Some(58u8));
  689. // u16
  690. assert_eq!(deserialize(&[0x01u8, 0x02]).ok(), Some(0x0201u16));
  691. assert_eq!(deserialize(&[0xABu8, 0xCD]).ok(), Some(0xCDABu16));
  692. assert_eq!(deserialize(&[0xA0u8, 0x0D]).ok(), Some(0xDA0u16));
  693. let failure16: Result<u16> = deserialize(&[1u8]);
  694. assert!(failure16.is_err());
  695. // u32
  696. assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABu32));
  697. assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD]).ok(), Some(0xCDAB0DA0u32));
  698. let failure32: Result<u32> = deserialize(&[1u8, 2, 3]);
  699. assert!(failure32.is_err());
  700. // TODO: test negative numbers
  701. assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0]).ok(), Some(0xCDABi32));
  702. assert_eq!(deserialize(&[0xA0u8, 0x0D, 0xAB, 0x2D]).ok(), Some(0x2DAB0DA0i32));
  703. let failurei32: Result<i32> = deserialize(&[1u8, 2, 3]);
  704. assert!(failurei32.is_err());
  705. // u64
  706. assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0, 0, 0, 0, 0]).ok(), Some(0xCDABu64));
  707. assert_eq!(
  708. deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD, 0x99, 0, 0, 0x99]).ok(),
  709. Some(0x99000099CDAB0DA0u64)
  710. );
  711. let failure64: Result<u64> = deserialize(&[1u8, 2, 3, 4, 5, 6, 7]);
  712. assert!(failure64.is_err());
  713. // TODO: test negative numbers
  714. assert_eq!(deserialize(&[0xABu8, 0xCD, 0, 0, 0, 0, 0, 0]).ok(), Some(0xCDABi64));
  715. assert_eq!(
  716. deserialize(&[0xA0u8, 0x0D, 0xAB, 0xCD, 0x99, 0, 0, 0x99]).ok(),
  717. Some(-0x66ffff663254f260i64)
  718. );
  719. let failurei64: Result<i64> = deserialize(&[1u8, 2, 3, 4, 5, 6, 7]);
  720. assert!(failurei64.is_err());
  721. }
  722. #[test]
  723. fn deserialize_vec_test() {
  724. assert_eq!(deserialize(&[3u8, 2, 3, 4]).ok(), Some(vec![2u8, 3, 4]));
  725. assert!((deserialize(&[4u8, 2, 3, 4, 5, 6]) as Result<Vec<u8>>).is_err());
  726. }
  727. #[test]
  728. fn deserialize_strbuf_test() {
  729. assert_eq!(
  730. deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(),
  731. Some("Andrew".to_string())
  732. );
  733. assert_eq!(
  734. deserialize(&[6u8, 0x41, 0x6e, 0x64, 0x72, 0x65, 0x77]).ok(),
  735. Some(::std::borrow::Cow::Borrowed("Andrew"))
  736. );
  737. }
  738. }