mod.rs 13.4 KB
Newer Older
Gav's avatar
Stuff.    
Gav committed
1
2
3
4
5
6
7
8
9
10
11
12
13
// Copyright 2017, 2018 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Gav Wood's avatar
Gav Wood committed
14

Bastian Köcher's avatar
Bastian Köcher committed
15
16
#[cfg(not(feature="derive"))]
use parity_scale_codec_derive::{Encode, Decode};
17
18
19
use parity_scale_codec::{
	Encode, Decode, HasCompact, Compact, EncodeAsRef, CompactAs, Error, Output,
};
Bastian Köcher's avatar
Bastian Köcher committed
20
use serde_derive::{Serialize, Deserialize};
Gav Wood's avatar
Gav Wood committed
21
22
23
24
25
26
27

#[derive(Debug, PartialEq, Encode, Decode)]
struct Unit;

#[derive(Debug, PartialEq, Encode, Decode)]
struct Indexed(u32, u64);

28
#[derive(Debug, PartialEq, Encode, Decode, Default)]
Gav Wood's avatar
Gav Wood committed
29
30
31
32
33
34
struct Struct<A, B, C> {
	pub a: A,
	pub b: B,
	pub c: C,
}

35
36
37
38
39
40
41
#[derive(Debug, PartialEq, Encode, Decode)]
struct StructWithPhantom {
	pub a: u32,
	pub b: u64,
	_c: ::std::marker::PhantomData<u8>,
}

Gav Wood's avatar
Gav Wood committed
42
43
44
45
46
47
48
49
50
51
type TestType = Struct<u32, u64, Vec<u8>>;

impl <A, B, C> Struct<A, B, C> {
	fn new(a: A, b: B, c: C) -> Self {
		Self { a, b, c }
	}
}

#[derive(Debug, PartialEq, Encode, Decode)]
enum EnumType {
52
	#[codec(index = 15)]
Gav Wood's avatar
Gav Wood committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
	A,
	B(u32, u64),
	C {
		a: u32,
		b: u64,
	},
}

#[derive(Debug, PartialEq, Encode, Decode)]
enum EnumWithDiscriminant {
	A = 1,
	B = 15,
	C = 255,
}

68
69
70
71
#[derive(Debug, PartialEq, Encode, Decode)]
struct TestHasCompact<T: HasCompact> {
	#[codec(encoded_as = "<T as HasCompact>::Type")]
	bar: T,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
72
73
}

thiolliere's avatar
tests    
thiolliere committed
74
75
76
77
78
79
#[derive(Debug, PartialEq, Encode, Decode)]
struct TestCompactHasCompact<T: HasCompact> {
	#[codec(compact)]
	bar: T,
}

Bastian Köcher's avatar
Bastian Köcher committed
80
81
82
83
84
85
86
#[derive(Debug, PartialEq, Encode, Decode)]
enum TestHasCompactEnum<T: HasCompact> {
	Unnamed(#[codec(encoded_as = "<T as HasCompact>::Type")] T),
	Named {
		#[codec(encoded_as = "<T as HasCompact>::Type")]
		bar: T
	},
thiolliere's avatar
tests    
thiolliere committed
87
88
89
90
91
	UnnamedCompact(#[codec(compact)] T),
	NamedCompact {
		#[codec(compact)]
		bar: T
	},
Bastian Köcher's avatar
Bastian Köcher committed
92
93
}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
94
#[derive(Debug, PartialEq, Encode, Decode)]
95
96
97
struct TestCompactAttribute {
	#[codec(compact)]
	bar: u64,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
98
99
}

Bastian Köcher's avatar
Bastian Köcher committed
100
101
102
103
104
105
106
107
108
#[derive(Debug, PartialEq, Encode, Decode)]
enum TestCompactAttributeEnum {
	Unnamed(#[codec(compact)] u64),
	Named {
		#[codec(compact)]
		bar: u64,
	},
}

Gav Wood's avatar
Gav Wood committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#[test]
fn should_work_for_simple_enum() {
	let a = EnumType::A;
	let b = EnumType::B(1, 2);
	let c = EnumType::C { a: 1, b: 2 };

	a.using_encoded(|ref slice| {
		assert_eq!(slice, &b"\x0f");
	});
	b.using_encoded(|ref slice| {
		assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0");
	});
	c.using_encoded(|ref slice| {
		assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0");
	});

	let mut da: &[u8] = b"\x0f";
126
	assert_eq!(EnumType::decode(&mut da).ok(), Some(a));
Gav Wood's avatar
Gav Wood committed
127
	let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0";
128
	assert_eq!(EnumType::decode(&mut db).ok(), Some(b));
Gav Wood's avatar
Gav Wood committed
129
	let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0";
130
	assert_eq!(EnumType::decode(&mut dc).ok(), Some(c));
Gav Wood's avatar
Gav Wood committed
131
	let mut dz: &[u8] = &[0];
132
	assert_eq!(EnumType::decode(&mut dz).ok(), None);
Gav Wood's avatar
Gav Wood committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
}

#[test]
fn should_work_for_enum_with_discriminant() {
	EnumWithDiscriminant::A.using_encoded(|ref slice| {
		assert_eq!(slice, &[1]);
	});
	EnumWithDiscriminant::B.using_encoded(|ref slice| {
		assert_eq!(slice, &[15]);
	});
	EnumWithDiscriminant::C.using_encoded(|ref slice| {
		assert_eq!(slice, &[255]);
	});

	let mut da: &[u8] = &[1];
148
	assert_eq!(EnumWithDiscriminant::decode(&mut da), Ok(EnumWithDiscriminant::A));
Gav Wood's avatar
Gav Wood committed
149
	let mut db: &[u8] = &[15];
150
	assert_eq!(EnumWithDiscriminant::decode(&mut db), Ok(EnumWithDiscriminant::B));
Gav Wood's avatar
Gav Wood committed
151
	let mut dc: &[u8] = &[255];
152
	assert_eq!(EnumWithDiscriminant::decode(&mut dc), Ok(EnumWithDiscriminant::C));
Gav Wood's avatar
Gav Wood committed
153
	let mut dz: &[u8] = &[2];
154
	assert_eq!(EnumWithDiscriminant::decode(&mut dz).ok(), None);
Gav Wood's avatar
Gav Wood committed
155
156
157
158
159
160
161
}

#[test]
fn should_derive_encode() {
	let v = TestType::new(15, 9, b"Hello world".to_vec());

	v.using_encoded(|ref slice| {
Bastian Köcher's avatar
Bastian Köcher committed
162
		assert_eq!(slice, &b"\x0f\0\0\0\x09\0\0\0\0\0\0\0\x2cHello world")
Gav Wood's avatar
Gav Wood committed
163
164
165
166
167
	});
}

#[test]
fn should_derive_decode() {
Bastian Köcher's avatar
Bastian Köcher committed
168
	let slice = b"\x0f\0\0\0\x09\0\0\0\0\0\0\0\x2cHello world".to_vec();
Gav Wood's avatar
Gav Wood committed
169

170
	let v = TestType::decode(&mut &*slice);
Gav Wood's avatar
Gav Wood committed
171

172
	assert_eq!(v, Ok(TestType::new(15, 9, b"Hello world".to_vec())));
Gav Wood's avatar
Gav Wood committed
173
174
175
176
177
178
179
180
181
182
183
}

#[test]
fn should_work_for_unit() {
	let v = Unit;

	v.using_encoded(|ref slice| {
		assert_eq!(slice, &[]);
	});

	let mut a: &[u8] = &[];
184
	assert_eq!(Unit::decode(&mut a), Ok(Unit));
Gav Wood's avatar
Gav Wood committed
185
186
187
188
189
190
191
192
193
194
195
}

#[test]
fn should_work_for_indexed() {
	let v = Indexed(1, 2);

	v.using_encoded(|ref slice| {
		assert_eq!(slice, &b"\x01\0\0\0\x02\0\0\0\0\0\0\0")
	});

	let mut v: &[u8] = b"\x01\0\0\0\x02\0\0\0\0\0\0\0";
196
	assert_eq!(Indexed::decode(&mut v), Ok(Indexed(1, 2)));
197
198
199
}

#[test]
thiolliere's avatar
thiolliere committed
200
#[should_panic(expected = "Not enough data to fill buffer")]
201
202
fn correct_error_for_indexed_0() {
	let mut wrong: &[u8] = b"\x08";
203
	Indexed::decode(&mut wrong).unwrap();
204
205
206
}

#[test]
thiolliere's avatar
thiolliere committed
207
#[should_panic(expected = "Not enough data to fill buffer")]
208
209
fn correct_error_for_indexed_1() {
	let mut wrong: &[u8] = b"\0\0\0\0\x01";
210
	Indexed::decode(&mut wrong).unwrap();
211
212
213
}

#[test]
thiolliere's avatar
thiolliere committed
214
#[should_panic(expected = "Not enough data to fill buffer")]
215
216
fn correct_error_for_enumtype() {
	let mut wrong: &[u8] = b"\x01";
217
	EnumType::decode(&mut wrong).unwrap();
218
219
220
}

#[test]
thiolliere's avatar
thiolliere committed
221
#[should_panic(expected = "Not enough data to fill buffer")]
222
223
fn correct_error_for_named_struct_1() {
	let mut wrong: &[u8] = b"\x01";
224
	Struct::<u32, u32, u32>::decode(&mut wrong).unwrap();
225
226
227
}

#[test]
thiolliere's avatar
thiolliere committed
228
#[should_panic(expected = "Not enough data to fill buffer")]
229
230
fn correct_error_for_named_struct_2() {
	let mut wrong: &[u8] = b"\0\0\0\0\x01";
231
	Struct::<u32, u32, u32>::decode(&mut wrong).unwrap();
Gav Wood's avatar
Gav Wood committed
232
}
Shawn Tabrizi's avatar
Shawn Tabrizi committed
233

234
235
236
237
238
239
240
241
242
243
244
245
246
247
const U64_TEST_COMPACT_VALUES: &[(u64, usize)] = &[
	(0u64, 1usize), (63, 1), (64, 2), (16383, 2),
	(16384, 4), (1073741823, 4),
	(1073741824, 5), (1 << 32 - 1, 5),
	(1 << 32, 6), (1 << 40, 7), (1 << 48, 8), (1 << 56 - 1, 8), (1 << 56, 9), (u64::max_value(), 9)
];

const U64_TEST_COMPACT_VALUES_FOR_ENUM: &[(u64, usize)] = &[
	(0u64, 2usize), (63, 2), (64, 3), (16383, 3),
	(16384, 5), (1073741823, 5),
	(1073741824, 6), (1 << 32 - 1, 6),
	(1 << 32, 7), (1 << 40, 8), (1 << 48, 9), (1 << 56 - 1, 9), (1 << 56, 10), (u64::max_value(), 10)
];

Shawn Tabrizi's avatar
Shawn Tabrizi committed
248
#[test]
249
fn encoded_as_with_has_compact_works() {
250
	for &(n, l) in U64_TEST_COMPACT_VALUES {
251
		let encoded = TestHasCompact { bar: n }.encode();
252
		println!("{}", n);
253
		assert_eq!(encoded.len(), l);
254
		assert_eq!(<TestHasCompact<u64>>::decode(&mut &encoded[..]).unwrap().bar, n);
255
256
257
	}
}

Bastian Köcher's avatar
Bastian Köcher committed
258
#[test]
thiolliere's avatar
tests    
thiolliere committed
259
260
261
262
263
fn compact_with_has_compact_works() {
	for &(n, l) in U64_TEST_COMPACT_VALUES {
		let encoded = TestHasCompact { bar: n }.encode();
		println!("{}", n);
		assert_eq!(encoded.len(), l);
264
		assert_eq!(<TestCompactHasCompact<u64>>::decode(&mut &encoded[..]).unwrap().bar, n);
thiolliere's avatar
tests    
thiolliere committed
265
266
267
268
269
	}
}

#[test]
fn enum_compact_and_encoded_as_with_has_compact_works() {
270
	for &(n, l) in U64_TEST_COMPACT_VALUES_FOR_ENUM {
thiolliere's avatar
tests    
thiolliere committed
271
272
273
274
275
276
		for value in [
			TestHasCompactEnum::Unnamed(n),
			TestHasCompactEnum::Named { bar: n },
			TestHasCompactEnum::UnnamedCompact(n),
			TestHasCompactEnum::NamedCompact { bar: n },
		].iter() {
Bastian Köcher's avatar
Bastian Köcher committed
277
			let encoded = value.encode();
278
			println!("{:?}", value);
Bastian Köcher's avatar
Bastian Köcher committed
279
			assert_eq!(encoded.len(), l);
280
			assert_eq!(&<TestHasCompactEnum<u64>>::decode(&mut &encoded[..]).unwrap(), value);
Bastian Köcher's avatar
Bastian Köcher committed
281
282
283
284
		}
	}
}

285
286
#[test]
fn compact_meta_attribute_works() {
287
	for &(n, l) in U64_TEST_COMPACT_VALUES {
288
		let encoded = TestCompactAttribute { bar: n }.encode();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
289
		assert_eq!(encoded.len(), l);
290
		assert_eq!(TestCompactAttribute::decode(&mut &encoded[..]).unwrap().bar, n);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
291
292
	}
}
Bastian Köcher's avatar
Bastian Köcher committed
293
294
295

#[test]
fn enum_compact_meta_attribute_works() {
296
	for &(n, l) in U64_TEST_COMPACT_VALUES_FOR_ENUM {
Bastian Köcher's avatar
Bastian Köcher committed
297
298
299
		for value in [ TestCompactAttributeEnum::Unnamed(n), TestCompactAttributeEnum::Named { bar: n } ].iter() {
			let encoded = value.encode();
			assert_eq!(encoded.len(), l);
300
			assert_eq!(&TestCompactAttributeEnum::decode(&mut &encoded[..]).unwrap(), value);
Bastian Köcher's avatar
Bastian Köcher committed
301
302
303
		}
	}
}
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319

#[test]
fn associated_type_bounds() {
	trait Trait {
		type EncodableType;
		type NonEncodableType;
	}

	#[derive(Encode, Decode, Debug, PartialEq)]
	struct Struct<T: Trait, Type> {
		field: (Vec<T::EncodableType>, Type),
	}

	#[derive(Debug, PartialEq)]
	struct TraitImplementor;

320
321
	struct NonEncodableType;

322
323
	impl Trait for TraitImplementor {
		type EncodableType = u32;
324
		type NonEncodableType = NonEncodableType;
325
326
327
328
	}

	let value: Struct<TraitImplementor, u64> = Struct { field: (vec![1, 2, 3], 42) };
	let encoded = value.encode();
329
	let decoded: Struct<TraitImplementor, u64> = Struct::decode(&mut &encoded[..]).unwrap();
330
331
	assert_eq!(value, decoded);
}
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373

#[test]
fn generic_bound_encoded_as() {
	// This struct does not impl Codec nor HasCompact
	struct StructEncodeAsRef;

	impl From<u32> for StructEncodeAsRef {
		fn from(_: u32) -> Self {
			StructEncodeAsRef
		}
	}

	impl<'a> From<&'a StructEncodeAsRef> for &'a u32 {
		fn from(_: &'a StructEncodeAsRef) -> Self {
			&0
		}
	}

	impl<'a> EncodeAsRef<'a, StructEncodeAsRef> for u32 {
		type RefType = &'a u32;
	}

	#[derive(Debug, PartialEq, Encode, Decode)]
	struct TestGeneric<A: From<u32>>
	where
		u32: for<'a> EncodeAsRef<'a, A>,
	{
		#[codec(encoded_as = "u32")]
		a: A,
	}

	let a = TestGeneric::<StructEncodeAsRef> {
		a: StructEncodeAsRef,
	};
	a.encode();
}

#[test]
fn generic_bound_hascompact() {
	#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
	#[derive(PartialEq, Eq, Clone)]
	// This struct does not impl Codec
374
	struct StructHasCompact(u32);
375
376
377
378
379
380

	impl CompactAs for StructHasCompact {
		type As = u32;
		fn encode_as(&self) -> &Self::As {
			&0
		}
381
382
		fn decode_from(_: Self::As) -> Result<Self, Error> {
			Ok(StructHasCompact(0))
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
		}
	}

	impl From<Compact<StructHasCompact>> for StructHasCompact {
		fn from(_: Compact<StructHasCompact>) -> Self {
			StructHasCompact(0)
		}
	}

	#[derive(Debug, PartialEq, Encode, Decode)]
	enum TestGenericHasCompact<T> {
		A {
			#[codec(compact)] a: T
		},
	}

	let a = TestGenericHasCompact::A::<StructHasCompact> {
		a: StructHasCompact(0),
	};

	a.encode();
}

#[test]
fn generic_trait() {
	trait TraitNoCodec {
		type Type;
	}

	struct StructNoCodec;

	#[derive(Debug, PartialEq, Encode, Decode)]
	struct StructCodec;

	impl TraitNoCodec for StructNoCodec {
		type Type = StructCodec;
	}

	#[derive(Debug, PartialEq, Encode, Decode)]
	struct TestGenericTrait<T: TraitNoCodec> {
		t: T::Type,
	}

	let a = TestGenericTrait::<StructNoCodec> {
		t: StructCodec,
	};

	a.encode();
}
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455

#[test]
fn recursive_variant_1_encode_works() {
	#[derive(Debug, PartialEq, Encode, Decode, Default)]
	struct Recursive<N> {
		data: N,
		other: Vec<Recursive<N>>,
	}

	let val: Recursive<u32> = Recursive::default();
	val.encode();
}

#[test]
fn recursive_variant_2_encode_works() {
	#[derive(Debug, PartialEq, Encode, Decode, Default)]
	struct Recursive<A, B, N> {
		data: N,
		other: Vec<Struct<A, B, Recursive<A, B, N>>>,
	}

	let val: Recursive<u32, i32, u32> = Recursive::default();
	val.encode();
}
456

457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
#[test]
fn private_type_in_where_bound() {
	// Make the `private type `private_type_in_where_bound::Private` in public interface` warning
	// an error.
	#![deny(warnings)]

	#[derive(Debug, PartialEq, Encode, Decode, Default)]
	struct Private;

	#[derive(Debug, PartialEq, Encode, Decode, Default)]
	#[codec(dumb_trait_bound)]
	pub struct Test<N> {
		data: Vec<(N, Private)>,
	}

	let val: Test<u32> = Test::default();
	val.encode();
}

476
477
478
479
480
#[test]
fn encode_decode_empty_enum() {
	#[derive(Encode, Decode, PartialEq, Debug)]
	enum EmptyEnumDerive {}

481
	fn impls_encode_decode<T: Encode + Decode>() {}
482
483
	impls_encode_decode::<EmptyEnumDerive>();

thiolliere's avatar
thiolliere committed
484
485
486
487
	assert_eq!(
		EmptyEnumDerive::decode(&mut &[1, 2, 3][..]),
		Err("Could not decode `EmptyEnumDerive`, variant doesn't exist".into())
	);
488
}
489
490
491
492
493
494
495
496

#[test]
fn codec_vec_u8() {
	for v in [
		vec![0u8; 0],
		vec![0u8; 10],
		vec![0u8; 100],
		vec![0u8; 1000],
497
	].iter() {
498
		let e = v.encode();
499
		assert_eq!(v, &Vec::<u8>::decode(&mut &e[..]).unwrap());
500
501
	}
}
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516

#[test]
fn recursive_type() {
	#[derive(Encode, Decode)]
	pub enum Foo {
		T(Box<Bar>),
		A,
	}

	#[derive(Encode, Decode)]
	pub struct Bar {
		field: Foo,
	}

}
517
518
519
520

#[test]
fn crafted_input_for_vec_u8() {
	assert_eq!(
thiolliere's avatar
thiolliere committed
521
		Vec::<u8>::decode(&mut &Compact(u32::max_value()).encode()[..]).err().unwrap().to_string(),
522
		"Not enough data to decode vector",
523
524
525
526
527
	);
}

#[test]
fn crafted_input_for_vec_t() {
thiolliere's avatar
thiolliere committed
528
	let msg: String = if cfg!(target_endian = "big") {
529
		// use unoptimize decode
thiolliere's avatar
thiolliere committed
530
		"Not enough data to fill buffer".into()
531
	} else {
thiolliere's avatar
thiolliere committed
532
		"Not enough data to decode vector".into()
533
534
	};

535
	assert_eq!(
thiolliere's avatar
thiolliere committed
536
		Vec::<u32>::decode(&mut &Compact(u32::max_value()).encode()[..]).err().unwrap().to_string(),
537
		msg,
538
539
	);
}
540

541
542
#[test]
fn weird_derive() {
543
544
545
546
547
548
549
550
551
552
	// Tests that compilation succeeds when the macro invocation
	// hygiene context is different from the field hygiene context.
	macro_rules! make_struct {
		(#[$attr:meta]) => (
			#[$attr]
			pub struct MyStruct {
				field: u8
			}
		)
	}
553

554
	make_struct!(#[derive(Encode, Decode)]);
555
}
556
557
558
559
560

#[test]
fn output_trait_object() {
	let _: Box<dyn Output>;
}
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588

#[test]
fn custom_trait_bound() {
	#[derive(Encode, Decode)]
	#[codec(encode_bound(N: Encode, T: Default))]
	#[codec(decode_bound(N: Decode, T: Default))]
	struct Something<T, N> {
		hello: Hello<T>,
		val: N,
	}

	#[derive(Encode, Decode)]
	#[codec(encode_bound())]
	#[codec(decode_bound())]
	struct Hello<T> {
		_phantom: std::marker::PhantomData<T>,
	}

	#[derive(Default)]
	struct NotEncode;

	let encoded = Something::<NotEncode, u32> {
		hello: Hello { _phantom: Default::default() },
		val: 32u32,
	}.encode();

	Something::<NotEncode, u32>::decode(&mut &encoded[..]).unwrap();
}