tetsy_wasm/elements/
primitives.rs

1use alloc::{string::String, vec::Vec};
2use crate::{io, elements};
3use super::{Error, Deserialize, Serialize};
4
5/// Unsigned variable-length integer, limited to 32 bits,
6/// represented by at most 5 bytes that may contain padding 0x80 bytes.
7#[derive(Debug, Copy, Clone, PartialEq)]
8pub struct VarUint32(u32);
9
10impl From<VarUint32> for usize {
11	fn from(var: VarUint32) -> usize {
12		var.0 as usize
13	}
14}
15
16impl From<VarUint32> for u32 {
17	fn from(var: VarUint32) -> u32 {
18		var.0
19	}
20}
21
22impl From<u32> for VarUint32 {
23	fn from(i: u32) -> VarUint32 {
24		VarUint32(i)
25	}
26}
27
28impl From<usize> for VarUint32 {
29	fn from(i: usize) -> VarUint32 {
30		assert!(i <= u32::max_value() as usize);
31		VarUint32(i as u32)
32	}
33}
34
35impl Deserialize for VarUint32 {
36	type Error = Error;
37
38	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
39		let mut res = 0;
40		let mut shift = 0;
41		let mut u8buf = [0u8; 1];
42		loop {
43			if shift > 31 { return Err(Error::InvalidVarUint32); }
44
45			reader.read(&mut u8buf)?;
46			let b = u8buf[0] as u32;
47			res |= (b & 0x7f).checked_shl(shift).ok_or(Error::InvalidVarUint32)?;
48			shift += 7;
49			if (b >> 7) == 0 {
50				if shift >= 32 && (b as u8).leading_zeros() < 4 {
51					return Err(Error::InvalidVarInt32);
52				}
53				break;
54			}
55		}
56		Ok(VarUint32(res))
57	}
58}
59
60impl Serialize for VarUint32 {
61	type Error = Error;
62
63	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
64		let mut buf = [0u8; 1];
65		let mut v = self.0;
66		loop {
67			buf[0] = (v & 0b0111_1111) as u8;
68			v >>= 7;
69			if v > 0 {
70				buf[0] |= 0b1000_0000;
71			}
72			writer.write(&buf[..])?;
73			if v == 0 { break; }
74		}
75
76		Ok(())
77	}
78}
79
80/// Unsigned variable-length integer, limited to 64 bits,
81/// represented by at most 9 bytes that may contain padding 0x80 bytes.
82#[derive(Debug, Copy, Clone, PartialEq)]
83pub struct VarUint64(u64);
84
85impl From<VarUint64> for u64 {
86	fn from(var: VarUint64) -> u64 {
87		var.0
88	}
89}
90
91impl Deserialize for VarUint64 {
92	type Error = Error;
93
94	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
95		let mut res = 0;
96		let mut shift = 0;
97		let mut u8buf = [0u8; 1];
98		loop {
99			if shift > 63 { return Err(Error::InvalidVarUint64); }
100
101			reader.read(&mut u8buf)?;
102			let b = u8buf[0] as u64;
103			res |= (b & 0x7f).checked_shl(shift).ok_or(Error::InvalidVarUint64)?;
104			shift += 7;
105			if (b >> 7) == 0 {
106				if shift >= 64 && (b as u8).leading_zeros() < 7 {
107					return Err(Error::InvalidVarInt64);
108				}
109				break;
110			}
111		}
112		Ok(VarUint64(res))
113	}
114}
115
116impl Serialize for VarUint64 {
117	type Error = Error;
118
119	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
120		let mut buf = [0u8; 1];
121		let mut v = self.0;
122		loop {
123			buf[0] = (v & 0b0111_1111) as u8;
124			v >>= 7;
125			if v > 0 {
126				buf[0] |= 0b1000_0000;
127			}
128			writer.write(&buf[..])?;
129			if v == 0 { break; }
130		}
131
132		Ok(())
133	}
134}
135
136impl From<u64> for VarUint64 {
137	fn from(u: u64) -> VarUint64 {
138		VarUint64(u)
139	}
140}
141
142/// 7-bit unsigned integer, encoded in LEB128 (always 1 byte length).
143#[derive(Debug, Copy, Clone, PartialEq)]
144pub struct VarUint7(u8);
145
146impl From<VarUint7> for u8 {
147	fn from(v: VarUint7) -> u8 {
148		v.0
149	}
150}
151
152impl From<u8> for VarUint7 {
153	fn from(v: u8) -> Self {
154		VarUint7(v)
155	}
156}
157
158impl Deserialize for VarUint7 {
159	type Error = Error;
160
161	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
162		let mut u8buf = [0u8; 1];
163		reader.read(&mut u8buf)?;
164		Ok(VarUint7(u8buf[0]))
165	}
166}
167
168impl Serialize for VarUint7 {
169	type Error = Error;
170
171	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
172		// todo check range?
173		writer.write(&[self.0])?;
174		Ok(())
175	}
176}
177
178/// 7-bit signed integer, encoded in LEB128 (always 1 byte length)
179#[derive(Debug, Copy, Clone, PartialEq)]
180pub struct VarInt7(i8);
181
182impl From<VarInt7> for i8 {
183	fn from(v: VarInt7) -> i8 {
184		v.0
185	}
186}
187
188impl From<i8> for VarInt7 {
189	fn from(v: i8) -> VarInt7 {
190		VarInt7(v)
191	}
192}
193
194impl Deserialize for VarInt7 {
195	type Error = Error;
196
197	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
198		let mut u8buf = [0u8; 1];
199		reader.read(&mut u8buf)?;
200
201		// check if number is not continued!
202		if u8buf[0] & 0b1000_0000 != 0 {
203			return Err(Error::InvalidVarInt7(u8buf[0]));
204		}
205
206		// expand sign
207		if u8buf[0] & 0b0100_0000 == 0b0100_0000 { u8buf[0] |= 0b1000_0000 }
208
209		Ok(VarInt7(u8buf[0] as i8))
210	}
211}
212
213impl Serialize for VarInt7 {
214	type Error = Error;
215
216	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
217		// todo check range?
218		let mut b: u8 = self.0 as u8;
219		if self.0 < 0 { b |= 0b0100_0000; b &= 0b0111_1111; }
220		writer.write(&[b])?;
221		Ok(())
222	}
223}
224
225/// 8-bit unsigned integer, NOT encoded in LEB128;
226/// it's just a single byte.
227#[derive(Debug, Copy, Clone, PartialEq)]
228pub struct Uint8(u8);
229
230impl From<Uint8> for u8 {
231	fn from(v: Uint8) -> u8 {
232		v.0
233	}
234}
235
236impl From<u8> for Uint8 {
237	fn from(v: u8) -> Self {
238		Uint8(v)
239	}
240}
241
242impl Deserialize for Uint8 {
243	type Error = Error;
244
245	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
246		let mut u8buf = [0u8; 1];
247		reader.read(&mut u8buf)?;
248		Ok(Uint8(u8buf[0]))
249	}
250}
251
252impl Serialize for Uint8 {
253	type Error = Error;
254
255	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
256		writer.write(&[self.0])?;
257		Ok(())
258	}
259}
260
261
262/// 32-bit signed integer, encoded in LEB128 (can be 1-5 bytes length).
263#[derive(Debug, Copy, Clone, PartialEq)]
264pub struct VarInt32(i32);
265
266impl From<VarInt32> for i32 {
267	fn from(v: VarInt32) -> i32 {
268		v.0
269	}
270}
271
272impl From<i32> for VarInt32 {
273	fn from(v: i32) -> VarInt32 {
274		VarInt32(v)
275	}
276}
277
278impl Deserialize for VarInt32 {
279	type Error = Error;
280
281	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
282		let mut res = 0;
283		let mut shift = 0;
284		let mut u8buf = [0u8; 1];
285		loop {
286			if shift > 31 { return Err(Error::InvalidVarInt32); }
287			reader.read(&mut u8buf)?;
288			let b = u8buf[0];
289
290			res |= ((b & 0x7f) as i32).checked_shl(shift).ok_or(Error::InvalidVarInt32)?;
291
292			shift += 7;
293			if (b >> 7) == 0 {
294				if shift < 32 && b & 0b0100_0000 == 0b0100_0000 {
295					res |= (1i32 << shift).wrapping_neg();
296				} else if shift >= 32 && b & 0b0100_0000 == 0b0100_0000 {
297					if (!(b | 0b1000_0000)).leading_zeros() < 5 {
298						return Err(Error::InvalidVarInt32);
299					}
300				} else if shift >= 32 && b & 0b0100_0000 == 0 {
301					if b.leading_zeros() < 5 {
302						return Err(Error::InvalidVarInt32);
303					}
304				}
305				break;
306			}
307		}
308		Ok(VarInt32(res))
309	}
310}
311
312impl Serialize for VarInt32 {
313	type Error = Error;
314
315	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
316		let mut buf = [0u8; 1];
317		let mut v = self.0;
318		let mut more = true;
319		while more {
320			buf[0] = (v & 0b0111_1111) as u8;
321			v >>= 7;
322			if (v == 0 && buf[0] & 0b0100_0000 == 0) || (v == -1 && buf[0] & 0b0100_0000 == 0b0100_0000)  {
323				more = false
324			} else {
325				buf[0] |= 0b1000_0000
326			}
327
328			writer.write(&buf[..])?;
329		}
330
331		Ok(())
332	}
333}
334
335/// 64-bit signed integer, encoded in LEB128 (can be 1-9 bytes length).
336#[derive(Debug, Copy, Clone, PartialEq)]
337pub struct VarInt64(i64);
338
339impl From<VarInt64> for i64 {
340	fn from(v: VarInt64) -> i64 {
341		v.0
342	}
343}
344
345impl From<i64> for VarInt64 {
346	fn from(v: i64) -> VarInt64 {
347		VarInt64(v)
348	}
349}
350
351impl Deserialize for VarInt64 {
352	type Error = Error;
353
354	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
355		let mut res = 0i64;
356		let mut shift = 0;
357		let mut u8buf = [0u8; 1];
358
359		loop {
360			if shift > 63 { return Err(Error::InvalidVarInt64); }
361			reader.read(&mut u8buf)?;
362			let b = u8buf[0];
363
364			res |= ((b & 0x7f) as i64).checked_shl(shift).ok_or(Error::InvalidVarInt64)?;
365
366			shift += 7;
367			if (b >> 7) == 0 {
368				if shift < 64 && b & 0b0100_0000 == 0b0100_0000 {
369					res |= (1i64 << shift).wrapping_neg();
370				} else if shift >= 64 && b & 0b0100_0000 == 0b0100_0000 {
371					if (b | 0b1000_0000) as i8 != -1 {
372						return Err(Error::InvalidVarInt64);
373					}
374				} else if shift >= 64 && b != 0 {
375					return Err(Error::InvalidVarInt64);
376				}
377				break;
378			}
379		}
380		Ok(VarInt64(res))
381	}
382}
383
384impl Serialize for VarInt64 {
385	type Error = Error;
386
387	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
388		let mut buf = [0u8; 1];
389		let mut v = self.0;
390		let mut more = true;
391		while more {
392			buf[0] = (v & 0b0111_1111) as u8;
393			v >>= 7;
394			if (v == 0 && buf[0] & 0b0100_0000 == 0) || (v == -1 && buf[0] & 0b0100_0000 == 0b0100_0000)  {
395				more = false
396			} else {
397				buf[0] |= 0b1000_0000
398			}
399
400			writer.write(&buf[..])?;
401		}
402
403		Ok(())
404	}
405}
406
407/// 32-bit unsigned integer, encoded in little endian.
408#[derive(Debug, Copy, Clone, PartialEq)]
409pub struct Uint32(u32);
410
411impl Deserialize for Uint32 {
412	type Error = Error;
413
414	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
415		let mut buf = [0u8; 4];
416		reader.read(&mut buf)?;
417		// todo check range
418		Ok(u32::from_le_bytes(buf).into())
419	}
420}
421
422impl From<Uint32> for u32 {
423	fn from(var: Uint32) -> u32 {
424		var.0
425	}
426}
427
428impl Serialize for Uint32 {
429	type Error = Error;
430
431	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
432		writer.write(&self.0.to_le_bytes())?;
433		Ok(())
434	}
435}
436
437impl From<u32> for Uint32 {
438	fn from(u: u32) -> Self { Uint32(u) }
439}
440
441/// 64-bit unsigned integer, encoded in little endian.
442#[derive(Debug, Copy, Clone, PartialEq)]
443pub struct Uint64(u64);
444
445impl Deserialize for Uint64 {
446	type Error = Error;
447
448	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
449		let mut buf = [0u8; 8];
450		reader.read(&mut buf)?;
451		// todo check range
452		Ok(u64::from_le_bytes(buf).into())
453	}
454}
455
456impl Serialize for Uint64 {
457	type Error = Error;
458
459	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
460		writer.write(&self.0.to_le_bytes())?;
461		Ok(())
462	}
463}
464
465impl From<u64> for Uint64 {
466	fn from(u: u64) -> Self { Uint64(u) }
467}
468
469impl From<Uint64> for u64 {
470	fn from(var: Uint64) -> u64 {
471		var.0
472	}
473}
474
475
476/// VarUint1, 1-bit value (0/1).
477#[derive(Debug, Copy, Clone, PartialEq)]
478pub struct VarUint1(bool);
479
480impl From<VarUint1> for bool {
481	fn from(v: VarUint1) -> bool {
482		v.0
483	}
484}
485
486impl From<bool> for VarUint1 {
487	fn from(b: bool) -> Self {
488		VarUint1(b)
489	}
490}
491
492impl Deserialize for VarUint1 {
493	type Error = Error;
494
495	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
496		let mut u8buf = [0u8; 1];
497		reader.read(&mut u8buf)?;
498		match u8buf[0] {
499			0 => Ok(VarUint1(false)),
500			1 => Ok(VarUint1(true)),
501			v @ _ => Err(Error::InvalidVarUint1(v)),
502		}
503	}
504}
505
506impl Serialize for VarUint1 {
507	type Error = Error;
508
509	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
510		writer.write(&[
511			if self.0 { 1u8 } else { 0u8 }
512		])?;
513		Ok(())
514	}
515}
516
517impl Deserialize for String {
518	type Error = Error;
519
520	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
521		let length = u32::from(VarUint32::deserialize(reader)?) as usize;
522		if length > 0 {
523			String::from_utf8(buffered_read!(1024, length, reader)).map_err(|_| Error::NonUtf8String)
524		}
525		else {
526			Ok(String::new())
527		}
528	}
529}
530
531impl Serialize for String {
532	type Error = Error;
533
534	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Error> {
535		VarUint32::from(self.len()).serialize(writer)?;
536		writer.write(&self.into_bytes()[..])?;
537		Ok(())
538	}
539}
540
541/// List for reading sequence of elements typed `T`, given
542/// they are preceded by length (serialized as VarUint32).
543#[derive(Debug, Clone)]
544pub struct CountedList<T: Deserialize>(Vec<T>);
545
546impl<T: Deserialize> CountedList<T> {
547	/// Destroy counted list returing inner vector.
548	pub fn into_inner(self) -> Vec<T> { self.0 }
549}
550
551impl<T: Deserialize> Deserialize for CountedList<T> where T::Error: From<Error> {
552	type Error = T::Error;
553
554	fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
555		let count: usize = VarUint32::deserialize(reader)?.into();
556		let mut result = Vec::new();
557		for _ in 0..count { result.push(T::deserialize(reader)?); }
558		Ok(CountedList(result))
559	}
560}
561
562/// Helper struct to write payload which is preceded by
563/// it's own length in bytes.
564#[derive(Debug)]
565pub struct CountedWriter<'a, W: 'a + io::Write> {
566	writer: &'a mut W,
567	data: Vec<u8>,
568}
569
570impl<'a, W: 'a + io::Write> CountedWriter<'a, W> {
571	/// New counted writer on top of the given serial writer.
572	pub fn new(writer: &'a mut W) -> Self {
573		CountedWriter {
574			writer: writer,
575			data: Vec::new(),
576		}
577	}
578
579	/// Finish counted writer routing, which writes accumulated length
580	/// and actual payload.
581	pub fn done(self) -> io::Result<()> {
582		let writer = self.writer;
583		let data = self.data;
584		VarUint32::from(data.len())
585			.serialize(writer)
586			.map_err(|_| io::Error::InvalidData)?;
587		writer.write(&data[..])?;
588		Ok(())
589	}
590}
591
592impl<'a, W: 'a + io::Write> io::Write for CountedWriter<'a, W> {
593	fn write(&mut self, buf: &[u8]) -> io::Result<()> {
594		self.data.extend_from_slice(buf);
595		Ok(())
596	}
597}
598
599/// Helper struct to write series of `T` preceded by the length of the sequence
600/// serialized as VarUint32.
601#[derive(Debug, Clone)]
602pub struct CountedListWriter<I: Serialize<Error=elements::Error>, T: IntoIterator<Item=I>>(pub usize, pub T);
603
604impl<I: Serialize<Error=elements::Error>, T: IntoIterator<Item=I>> Serialize for CountedListWriter<I, T> {
605	type Error = Error;
606
607	fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
608		let len_us = self.0;
609		let data = self.1;
610		let len: VarUint32 = len_us.into();
611		len.serialize(writer)?;
612		for data_element in data { data_element.serialize(writer)? }
613
614		Ok(())
615	}
616}
617
618
619#[cfg(test)]
620mod tests {
621
622	use super::super::{deserialize_buffer, Serialize};
623	use super::{CountedList, VarInt7, VarUint32, VarInt32, VarInt64, VarUint64};
624	use crate::elements::Error;
625
626	fn varuint32_ser_test(val: u32, expected: Vec<u8>) {
627		let mut buf = Vec::new();
628		let v1: VarUint32 = val.into();
629		v1.serialize(&mut buf).expect("to be serialized ok");
630		assert_eq!(expected, buf);
631	}
632
633	fn varuint32_de_test(dt: Vec<u8>, expected: u32) {
634		let val: VarUint32 = super::super::deserialize_buffer(&dt).expect("buf to be serialized");
635		assert_eq!(expected, val.into());
636	}
637
638	fn varuint32_serde_test(dt: Vec<u8>, val: u32) {
639		varuint32_de_test(dt.clone(), val);
640		varuint32_ser_test(val, dt);
641	}
642
643	fn varint32_ser_test(val: i32, expected: Vec<u8>) {
644		let mut buf = Vec::new();
645		let v1: VarInt32 = val.into();
646		v1.serialize(&mut buf).expect("to be serialized ok");
647		assert_eq!(expected, buf);
648	}
649
650	fn varint32_de_test(dt: Vec<u8>, expected: i32) {
651		let val: VarInt32 = super::super::deserialize_buffer(&dt).expect("buf to be serialized");
652		assert_eq!(expected, val.into());
653	}
654
655	fn varint32_serde_test(dt: Vec<u8>, val: i32) {
656		varint32_de_test(dt.clone(), val);
657		varint32_ser_test(val, dt);
658	}
659
660	fn varuint64_ser_test(val: u64, expected: Vec<u8>) {
661		let mut buf = Vec::new();
662		let v1: VarUint64 = val.into();
663		v1.serialize(&mut buf).expect("to be serialized ok");
664		assert_eq!(expected, buf);
665	}
666
667	fn varuint64_de_test(dt: Vec<u8>, expected: u64) {
668		let val: VarUint64 = super::super::deserialize_buffer(&dt).expect("buf to be serialized");
669		assert_eq!(expected, val.into());
670	}
671
672	fn varuint64_serde_test(dt: Vec<u8>, val: u64) {
673		varuint64_de_test(dt.clone(), val);
674		varuint64_ser_test(val, dt);
675	}
676
677	fn varint64_ser_test(val: i64, expected: Vec<u8>) {
678		let mut buf = Vec::new();
679		let v1: VarInt64 = val.into();
680		v1.serialize(&mut buf).expect("to be serialized ok");
681		assert_eq!(expected, buf);
682	}
683
684	fn varint64_de_test(dt: Vec<u8>, expected: i64) {
685		let val: VarInt64 = super::super::deserialize_buffer(&dt).expect("buf to be serialized");
686		assert_eq!(expected, val.into());
687	}
688
689	fn varint64_serde_test(dt: Vec<u8>, val: i64) {
690		varint64_de_test(dt.clone(), val);
691		varint64_ser_test(val, dt);
692	}
693
694	#[test]
695	fn varuint32_0() {
696		varuint32_serde_test(vec![0u8; 1], 0);
697	}
698
699	#[test]
700	fn varuint32_1() {
701		varuint32_serde_test(vec![1u8; 1], 1);
702	}
703
704	#[test]
705	fn varuint32_135() {
706		varuint32_serde_test(vec![135u8, 0x01], 135);
707	}
708
709	#[test]
710	fn varuint32_8192() {
711		varuint32_serde_test(vec![0x80, 0x40], 8192);
712	}
713
714	#[test]
715	fn varint32_8192() {
716		varint32_serde_test(vec![0x80, 0xc0, 0x00], 8192);
717	}
718
719	#[test]
720	fn varint32_neg_8192() {
721		varint32_serde_test(vec![0x80, 0x40], -8192);
722	}
723
724	#[test]
725	fn varuint64_0() {
726		varuint64_serde_test(vec![0u8; 1], 0);
727	}
728
729	#[test]
730	fn varuint64_1() {
731		varuint64_serde_test(vec![1u8; 1], 1);
732	}
733
734	#[test]
735	fn varuint64_135() {
736		varuint64_serde_test(vec![135u8, 0x01], 135);
737	}
738
739	#[test]
740	fn varuint64_8192() {
741		varuint64_serde_test(vec![0x80, 0x40], 8192);
742	}
743
744	#[test]
745	fn varint64_8192() {
746		varint64_serde_test(vec![0x80, 0xc0, 0x00], 8192);
747	}
748
749	#[test]
750	fn varint64_neg_8192() {
751		varint64_serde_test(vec![0x80, 0x40], -8192);
752	}
753
754	#[test]
755	fn varint64_min() {
756		varint64_serde_test(
757			vec![0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f],
758			-9223372036854775808,
759		);
760	}
761
762	#[test]
763	fn varint64_bad_extended() {
764		let res = deserialize_buffer::<VarInt64>(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x6f][..]);
765		assert!(res.is_err());
766	}
767
768	#[test]
769	fn varint32_bad_extended() {
770		let res = deserialize_buffer::<VarInt32>(&[0x80, 0x80, 0x80, 0x80, 0x6f][..]);
771		assert!(res.is_err());
772	}
773
774	#[test]
775	fn varint32_bad_extended2() {
776		let res = deserialize_buffer::<VarInt32>(&[0x80, 0x80, 0x80, 0x80, 0x41][..]);
777		assert!(res.is_err());
778	}
779
780	#[test]
781	fn varint64_max() {
782		varint64_serde_test(
783			vec![0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00],
784			9223372036854775807,
785		);
786	}
787
788	#[test]
789	fn varint64_too_long() {
790		assert!(
791			deserialize_buffer::<VarInt64>(
792				&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00][..],
793			).is_err()
794		);
795	}
796
797	#[test]
798	fn varint32_too_long() {
799		assert!(
800			deserialize_buffer::<VarInt32>(
801				&[0xff, 0xff, 0xff, 0xff, 0xff, 0x00][..],
802			).is_err()
803		);
804	}
805
806	#[test]
807	fn varuint64_too_long() {
808		assert!(
809			deserialize_buffer::<VarUint64>(
810				&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00][..],
811			).is_err()
812		);
813	}
814
815	#[test]
816	fn varuint32_too_long() {
817		assert!(
818			deserialize_buffer::<VarUint32>(
819				&[0xff, 0xff, 0xff, 0xff, 0xff, 0x00][..],
820			).is_err()
821		);
822	}
823
824	#[test]
825	fn varuint32_too_long_trailing() {
826		assert!(
827			deserialize_buffer::<VarUint32>(
828				&[0xff, 0xff, 0xff, 0xff, 0x7f][..],
829			).is_err()
830		);
831	}
832
833	#[test]
834	fn varuint64_too_long_trailing() {
835		assert!(
836			deserialize_buffer::<VarUint64>(
837				&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x04][..],
838			).is_err()
839		);
840	}
841
842	#[test]
843	fn varint32_min() {
844		varint32_serde_test(
845			vec![0x80, 0x80, 0x80, 0x80, 0x78],
846			-2147483648,
847		);
848	}
849
850	#[test]
851	fn varint7_invalid() {
852		match deserialize_buffer::<VarInt7>(&[240]) {
853			Err(Error::InvalidVarInt7(_)) => {},
854			_ => panic!("Should be invalid varint7 error!")
855		}
856	}
857
858	#[test]
859	fn varint7_neg() {
860		assert_eq!(-0x10i8, deserialize_buffer::<VarInt7>(&[0x70]).expect("fail").into());
861	}
862
863	#[test]
864	fn varuint32_too_long_nulled() {
865		match deserialize_buffer::<VarUint32>(
866			&[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x78]
867		) {
868			Err(Error::InvalidVarUint32) => {},
869			_ => panic!("Should be invalid varuint32"),
870		}
871	}
872
873	#[test]
874	fn varint32_max() {
875		varint32_serde_test(
876			vec![0xff, 0xff, 0xff, 0xff, 0x07],
877			2147483647,
878		);
879	}
880
881
882	#[test]
883	fn counted_list() {
884		let payload = [
885			133u8, //(128+5), length is 5
886				0x80, 0x80, 0x80, 0x0, // padding
887			0x01,
888			0x7d,
889			0x05,
890			0x07,
891			0x09,
892		];
893
894		let list: CountedList<VarInt7> =
895			deserialize_buffer(&payload).expect("type_section be deserialized");
896
897		let vars = list.into_inner();
898		assert_eq!(5, vars.len());
899		let v3: i8 = (*vars.get(1).unwrap()).into();
900		assert_eq!(-0x03i8, v3);
901	}
902}