referrerpolicy=no-referrer-when-downgrade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
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
374
375
376
377
378
379
380
381
382
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// 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.

//! Provides a type that wraps another type and provides a default value.

use crate::traits::{Bounded, One, Zero};
use codec::{Compact, CompactAs, Decode, Encode, HasCompact, MaxEncodedLen};
use core::{
	fmt::Display,
	marker::PhantomData,
	ops::{
		Add, AddAssign, BitAnd, BitOr, BitXor, Deref, Div, DivAssign, Mul, MulAssign, Not, Rem,
		RemAssign, Shl, Shr, Sub, SubAssign,
	},
};
use num_traits::{
	CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedRem, CheckedShl, CheckedShr, CheckedSub,
	Num, NumCast, PrimInt, Saturating, ToPrimitive,
};
use scale_info::{StaticTypeInfo, TypeInfo};
use sp_core::Get;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// A type that wraps another type and provides a default value.
///
/// Passes through arithmetical and many other operations to the inner value.
/// Type information for metadata is the same as the inner value's type.
#[derive(Encode, Decode, Debug, MaxEncodedLen)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TypeWithDefault<T, D: Get<T>>(T, PhantomData<D>);

impl<T, D: Get<T>> TypeWithDefault<T, D> {
	fn new(value: T) -> Self {
		Self(value, PhantomData)
	}
}

// Hides implementation details from the outside (for metadata type information).
//
// The type info showed in metadata is the one of the inner value's type.
impl<T: StaticTypeInfo, D: Get<T> + 'static> TypeInfo for TypeWithDefault<T, D> {
	type Identity = Self;

	fn type_info() -> scale_info::Type {
		T::type_info()
	}
}

impl<T: Clone, D: Get<T>> Clone for TypeWithDefault<T, D> {
	fn clone(&self) -> Self {
		Self(self.0.clone(), PhantomData)
	}
}

impl<T: Copy, D: Get<T>> Copy for TypeWithDefault<T, D> {}

impl<T: PartialEq, D: Get<T>> PartialEq for TypeWithDefault<T, D> {
	fn eq(&self, other: &Self) -> bool {
		self.0 == other.0
	}
}

impl<T: Eq, D: Get<T>> Eq for TypeWithDefault<T, D> {}

impl<T: PartialOrd, D: Get<T>> PartialOrd for TypeWithDefault<T, D> {
	fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
		self.0.partial_cmp(&other.0)
	}
}

impl<T: Ord, D: Get<T>> Ord for TypeWithDefault<T, D> {
	fn cmp(&self, other: &Self) -> core::cmp::Ordering {
		self.0.cmp(&other.0)
	}
}

impl<T, D: Get<T>> Deref for TypeWithDefault<T, D> {
	type Target = T;
	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

impl<T, D: Get<T>> Default for TypeWithDefault<T, D> {
	fn default() -> Self {
		Self::new(D::get())
	}
}

impl<T: CheckedNeg, D: Get<T>> CheckedNeg for TypeWithDefault<T, D> {
	fn checked_neg(&self) -> Option<Self> {
		self.0.checked_neg().map(Self::new)
	}
}

impl<T: CheckedRem, D: Get<T>> CheckedRem for TypeWithDefault<T, D> {
	fn checked_rem(&self, rhs: &Self) -> Option<Self> {
		self.0.checked_rem(&rhs.0).map(Self::new)
	}
}

impl<T: CheckedShr, D: Get<T>> CheckedShr for TypeWithDefault<T, D> {
	fn checked_shr(&self, n: u32) -> Option<Self> {
		self.0.checked_shr(n).map(Self::new)
	}
}

impl<T: CheckedShl, D: Get<T>> CheckedShl for TypeWithDefault<T, D> {
	fn checked_shl(&self, n: u32) -> Option<Self> {
		self.0.checked_shl(n).map(Self::new)
	}
}

impl<T: Rem<Output = T>, D: Get<T>> Rem for TypeWithDefault<T, D> {
	type Output = Self;
	fn rem(self, rhs: Self) -> Self {
		Self::new(self.0 % rhs.0)
	}
}

impl<T: Rem<u32, Output = T>, D: Get<T>> Rem<u32> for TypeWithDefault<T, D> {
	type Output = Self;
	fn rem(self, rhs: u32) -> Self {
		Self::new(self.0 % (rhs.into()))
	}
}

impl<T: Shr<u32, Output = T>, D: Get<T>> Shr<u32> for TypeWithDefault<T, D> {
	type Output = Self;
	fn shr(self, rhs: u32) -> Self {
		Self::new(self.0 >> rhs)
	}
}

impl<T: Shr<usize, Output = T>, D: Get<T>> Shr<usize> for TypeWithDefault<T, D> {
	type Output = Self;
	fn shr(self, rhs: usize) -> Self {
		Self::new(self.0 >> rhs)
	}
}

impl<T: Shl<u32, Output = T>, D: Get<T>> Shl<u32> for TypeWithDefault<T, D> {
	type Output = Self;
	fn shl(self, rhs: u32) -> Self {
		Self::new(self.0 << rhs)
	}
}

impl<T: Shl<usize, Output = T>, D: Get<T>> Shl<usize> for TypeWithDefault<T, D> {
	type Output = Self;
	fn shl(self, rhs: usize) -> Self {
		Self::new(self.0 << rhs)
	}
}

impl<T: RemAssign, D: Get<T>> RemAssign for TypeWithDefault<T, D> {
	fn rem_assign(&mut self, rhs: Self) {
		self.0 %= rhs.0
	}
}

impl<T: DivAssign, D: Get<T>> DivAssign for TypeWithDefault<T, D> {
	fn div_assign(&mut self, rhs: Self) {
		self.0 /= rhs.0
	}
}

impl<T: MulAssign, D: Get<T>> MulAssign for TypeWithDefault<T, D> {
	fn mul_assign(&mut self, rhs: Self) {
		self.0 *= rhs.0
	}
}

impl<T: SubAssign, D: Get<T>> SubAssign for TypeWithDefault<T, D> {
	fn sub_assign(&mut self, rhs: Self) {
		self.0 -= rhs.0
	}
}

impl<T: AddAssign, D: Get<T>> AddAssign for TypeWithDefault<T, D> {
	fn add_assign(&mut self, rhs: Self) {
		self.0 += rhs.0
	}
}

impl<T: Display, D: Get<T>> Display for TypeWithDefault<T, D> {
	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
		write!(f, "{}", self.0)
	}
}

macro_rules! impl_from {
    ($for_type:ty $(, $from_type:ty)*) => {
		$(
			impl<D: Get<$for_type>> From<$from_type> for TypeWithDefault<$for_type, D> {
				fn from(value: $from_type) -> Self {
					Self::new(value.into())
				}
			}
		)*
    }
}
impl_from!(u128, u128, u64, u32, u16, u8);
impl_from!(u64, u64, u32, u16, u8);
impl_from!(u32, u32, u16, u8);
impl_from!(u16, u16, u8);
impl_from!(u8, u8);

macro_rules! impl_try_from {
    ($for_type:ty $(, $try_from_type:ty)*) => {
		$(
			impl<D: Get<$for_type>> TryFrom<$try_from_type> for TypeWithDefault<$for_type, D> {
				type Error = <$for_type as TryFrom<$try_from_type>>::Error;
				fn try_from(n: $try_from_type) -> Result<TypeWithDefault<$for_type, D>, Self::Error> {
					<$for_type as TryFrom<$try_from_type>>::try_from(n).map(Self::new)
				}
			}
		)*
    }
}
impl_try_from!(u8, u16, u32, u64, u128);
impl_try_from!(u16, u32, u64, u128);
impl_try_from!(u32, u64, u128);
impl_try_from!(u64, u128);

impl<T: TryFrom<usize>, D: Get<T>> TryFrom<usize> for TypeWithDefault<T, D> {
	type Error = <T as TryFrom<usize>>::Error;
	fn try_from(n: usize) -> Result<TypeWithDefault<T, D>, Self::Error> {
		T::try_from(n).map(Self::new)
	}
}

impl<T: TryInto<u8>, D: Get<T>> TryFrom<TypeWithDefault<T, D>> for u8 {
	type Error = <T as TryInto<u8>>::Error;
	fn try_from(value: TypeWithDefault<T, D>) -> Result<Self, Self::Error> {
		value.0.try_into()
	}
}

impl<T: TryInto<u16>, D: Get<T>> TryFrom<TypeWithDefault<T, D>> for u16 {
	type Error = <T as TryInto<u16>>::Error;
	fn try_from(value: TypeWithDefault<T, D>) -> Result<Self, Self::Error> {
		value.0.try_into()
	}
}

impl<T: TryInto<u32>, D: Get<T>> TryFrom<TypeWithDefault<T, D>> for u32 {
	type Error = <T as TryInto<u32>>::Error;
	fn try_from(value: TypeWithDefault<T, D>) -> Result<Self, Self::Error> {
		value.0.try_into()
	}
}

impl<T: TryInto<u64>, D: Get<T>> TryFrom<TypeWithDefault<T, D>> for u64 {
	type Error = <T as TryInto<u64>>::Error;
	fn try_from(value: TypeWithDefault<T, D>) -> Result<Self, Self::Error> {
		value.0.try_into()
	}
}

impl<T: TryInto<u128>, D: Get<T>> TryFrom<TypeWithDefault<T, D>> for u128 {
	type Error = <T as TryInto<u128>>::Error;
	fn try_from(value: TypeWithDefault<T, D>) -> Result<Self, Self::Error> {
		value.0.try_into()
	}
}

impl<T: TryInto<usize>, D: Get<T>> TryFrom<TypeWithDefault<T, D>> for usize {
	type Error = <T as TryInto<usize>>::Error;
	fn try_from(value: TypeWithDefault<T, D>) -> Result<Self, Self::Error> {
		value.0.try_into()
	}
}

impl<T: Zero + PartialEq, D: Get<T>> Zero for TypeWithDefault<T, D> {
	fn zero() -> Self {
		Self::new(T::zero())
	}

	fn is_zero(&self) -> bool {
		self.0 == T::zero()
	}
}

impl<T: Bounded, D: Get<T>> Bounded for TypeWithDefault<T, D> {
	fn min_value() -> Self {
		Self::new(T::min_value())
	}

	fn max_value() -> Self {
		Self::new(T::max_value())
	}
}

impl<T: PrimInt, D: Get<T>> PrimInt for TypeWithDefault<T, D> {
	fn count_ones(self) -> u32 {
		self.0.count_ones()
	}

	fn leading_zeros(self) -> u32 {
		self.0.leading_zeros()
	}

	fn trailing_zeros(self) -> u32 {
		self.0.trailing_zeros()
	}

	fn rotate_left(self, n: u32) -> Self {
		Self::new(self.0.rotate_left(n))
	}

	fn rotate_right(self, n: u32) -> Self {
		Self::new(self.0.rotate_right(n))
	}

	fn swap_bytes(self) -> Self {
		Self::new(self.0.swap_bytes())
	}

	fn from_be(x: Self) -> Self {
		Self::new(T::from_be(x.0))
	}

	fn from_le(x: Self) -> Self {
		Self::new(T::from_le(x.0))
	}

	fn to_be(self) -> Self {
		Self::new(self.0.to_be())
	}

	fn to_le(self) -> Self {
		Self::new(self.0.to_le())
	}

	fn count_zeros(self) -> u32 {
		self.0.count_zeros()
	}

	fn signed_shl(self, n: u32) -> Self {
		Self::new(self.0.signed_shl(n))
	}

	fn signed_shr(self, n: u32) -> Self {
		Self::new(self.0.signed_shr(n))
	}

	fn unsigned_shl(self, n: u32) -> Self {
		Self::new(self.0.unsigned_shl(n))
	}

	fn unsigned_shr(self, n: u32) -> Self {
		Self::new(self.0.unsigned_shr(n))
	}

	fn pow(self, exp: u32) -> Self {
		Self::new(self.0.pow(exp))
	}
}

impl<T: Saturating, D: Get<T>> Saturating for TypeWithDefault<T, D> {
	fn saturating_add(self, rhs: Self) -> Self {
		Self::new(self.0.saturating_add(rhs.0))
	}

	fn saturating_sub(self, rhs: Self) -> Self {
		Self::new(self.0.saturating_sub(rhs.0))
	}
}

impl<T: Div<Output = T>, D: Get<T>> Div for TypeWithDefault<T, D> {
	type Output = Self;
	fn div(self, rhs: Self) -> Self {
		Self::new(self.0 / rhs.0)
	}
}

impl<T: Mul<Output = T>, D: Get<T>> Mul for TypeWithDefault<T, D> {
	type Output = Self;
	fn mul(self, rhs: Self) -> Self {
		Self::new(self.0 * rhs.0)
	}
}

impl<T: CheckedDiv, D: Get<T>> CheckedDiv for TypeWithDefault<T, D> {
	fn checked_div(&self, rhs: &Self) -> Option<Self> {
		self.0.checked_div(&rhs.0).map(Self::new)
	}
}

impl<T: CheckedMul, D: Get<T>> CheckedMul for TypeWithDefault<T, D> {
	fn checked_mul(&self, rhs: &Self) -> Option<Self> {
		self.0.checked_mul(&rhs.0).map(Self::new)
	}
}

impl<T: Sub<Output = T>, D: Get<T>> Sub for TypeWithDefault<T, D> {
	type Output = Self;
	fn sub(self, rhs: Self) -> Self {
		Self::new(self.0 - rhs.0)
	}
}

impl<T: CheckedSub, D: Get<T>> CheckedSub for TypeWithDefault<T, D> {
	fn checked_sub(&self, rhs: &Self) -> Option<Self> {
		self.0.checked_sub(&rhs.0).map(Self::new)
	}
}

impl<T: Add<Output = T>, D: Get<T>> Add for TypeWithDefault<T, D> {
	type Output = Self;
	fn add(self, rhs: Self) -> Self {
		Self::new(self.0 + rhs.0)
	}
}

impl<T: CheckedAdd, D: Get<T>> CheckedAdd for TypeWithDefault<T, D> {
	fn checked_add(&self, rhs: &Self) -> Option<Self> {
		self.0.checked_add(&rhs.0).map(Self::new)
	}
}

impl<T: BitAnd<Output = T>, D: Get<T>> BitAnd for TypeWithDefault<T, D> {
	type Output = Self;
	fn bitand(self, rhs: Self) -> Self {
		Self::new(self.0 & rhs.0)
	}
}

impl<T: BitOr<Output = T>, D: Get<T>> BitOr for TypeWithDefault<T, D> {
	type Output = Self;
	fn bitor(self, rhs: Self) -> Self {
		Self::new(self.0 | rhs.0)
	}
}

impl<T: BitXor<Output = T>, D: Get<T>> BitXor for TypeWithDefault<T, D> {
	type Output = Self;
	fn bitxor(self, rhs: Self) -> Self {
		Self::new(self.0 ^ rhs.0)
	}
}

impl<T: One, D: Get<T>> One for TypeWithDefault<T, D> {
	fn one() -> Self {
		Self::new(T::one())
	}
}

impl<T: Not<Output = T>, D: Get<T>> Not for TypeWithDefault<T, D> {
	type Output = Self;
	fn not(self) -> Self {
		Self::new(self.0.not())
	}
}

impl<T: NumCast, D: Get<T>> NumCast for TypeWithDefault<T, D> {
	fn from<P: ToPrimitive>(n: P) -> Option<Self> {
		<T as NumCast>::from(n).map_or(None, |n| Some(Self::new(n)))
	}
}

impl<T: Num, D: Get<T>> Num for TypeWithDefault<T, D> {
	type FromStrRadixErr = <T as Num>::FromStrRadixErr;

	fn from_str_radix(s: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
		T::from_str_radix(s, radix).map(Self::new)
	}
}

impl<T: ToPrimitive, D: Get<T>> ToPrimitive for TypeWithDefault<T, D> {
	fn to_i64(&self) -> Option<i64> {
		self.0.to_i64()
	}

	fn to_u64(&self) -> Option<u64> {
		self.0.to_u64()
	}

	fn to_i128(&self) -> Option<i128> {
		self.0.to_i128()
	}

	fn to_u128(&self) -> Option<u128> {
		self.0.to_u128()
	}
}

impl<T, D: Get<T>> From<Compact<TypeWithDefault<T, D>>> for TypeWithDefault<T, D> {
	fn from(c: Compact<TypeWithDefault<T, D>>) -> Self {
		c.0
	}
}

impl<T: HasCompact, D: Get<T>> CompactAs for TypeWithDefault<T, D> {
	type As = T;

	fn encode_as(&self) -> &Self::As {
		&self.0
	}

	fn decode_from(val: Self::As) -> Result<Self, codec::Error> {
		Ok(Self::new(val))
	}
}

#[cfg(test)]
mod tests {
	use super::TypeWithDefault;
	use scale_info::TypeInfo;
	use sp_arithmetic::traits::{AtLeast16Bit, AtLeast32Bit, AtLeast8Bit};
	use sp_core::Get;

	#[test]
	#[allow(dead_code)]
	fn test_type_with_default_impl_base_arithmetic() {
		trait WrapAtLeast8Bit: AtLeast8Bit {}
		trait WrapAtLeast16Bit: AtLeast16Bit {}
		trait WrapAtLeast32Bit: AtLeast32Bit {}

		struct Getu8;
		impl Get<u8> for Getu8 {
			fn get() -> u8 {
				0
			}
		}
		type U8WithDefault = TypeWithDefault<u8, Getu8>;
		impl WrapAtLeast8Bit for U8WithDefault {}

		struct Getu16;
		impl Get<u16> for Getu16 {
			fn get() -> u16 {
				0
			}
		}
		type U16WithDefault = TypeWithDefault<u16, Getu16>;
		impl WrapAtLeast16Bit for U16WithDefault {}

		struct Getu32;
		impl Get<u32> for Getu32 {
			fn get() -> u32 {
				0
			}
		}
		type U32WithDefault = TypeWithDefault<u32, Getu32>;
		impl WrapAtLeast32Bit for U32WithDefault {}

		struct Getu64;
		impl Get<u64> for Getu64 {
			fn get() -> u64 {
				0
			}
		}
		type U64WithDefault = TypeWithDefault<u64, Getu64>;
		impl WrapAtLeast32Bit for U64WithDefault {}

		struct Getu128;
		impl Get<u128> for Getu128 {
			fn get() -> u128 {
				0
			}
		}
		type U128WithDefault = TypeWithDefault<u128, Getu128>;
		impl WrapAtLeast32Bit for U128WithDefault {}

		assert_eq!(U8WithDefault::type_info(), <u8 as TypeInfo>::type_info());
		assert_eq!(U16WithDefault::type_info(), <u16 as TypeInfo>::type_info());
		assert_eq!(U32WithDefault::type_info(), <u32 as TypeInfo>::type_info());
		assert_eq!(U64WithDefault::type_info(), <u64 as TypeInfo>::type_info());
		assert_eq!(U128WithDefault::type_info(), <u128 as TypeInfo>::type_info());
	}
}