@@ -323,9 +323,28 @@ macro_rules! implement_per_thing {
323
323
///
324
324
#[ doc = $title]
325
325
#[ cfg_attr( feature = "std" , derive( Serialize , Deserialize ) ) ]
326
- #[ derive( Encode , Copy , Clone , PartialEq , Eq , PartialOrd , Ord , RuntimeDebug , CompactAs ) ]
326
+ #[ derive( Encode , Copy , Clone , PartialEq , Eq , PartialOrd , Ord , RuntimeDebug ) ]
327
327
pub struct $name( $type) ;
328
328
329
+ /// Implementation makes any compact encoding of `PerThing::Inner` valid,
330
+ /// when decoding it will saturate up to `PerThing::ACCURACY`.
331
+ impl CompactAs for $name {
332
+ type As = $type;
333
+ fn encode_as( & self ) -> & Self :: As {
334
+ & self . 0
335
+ }
336
+ fn decode_from( x: Self :: As ) -> Self {
337
+ // Saturates if `x` is more than `$max` internally.
338
+ Self :: from_parts( x)
339
+ }
340
+ }
341
+
342
+ impl From <codec:: Compact <$name>> for $name {
343
+ fn from( x: codec:: Compact <$name>) -> $name {
344
+ x. 0
345
+ }
346
+ }
347
+
329
348
impl PerThing for $name {
330
349
type Inner = $type;
331
350
type Upper = $upper_type;
@@ -1166,6 +1185,17 @@ macro_rules! implement_per_thing {
1166
1185
// deconstruct is also const, hence it can be called in const rhs.
1167
1186
const C5 : bool = C1 . deconstruct( ) == 0 ;
1168
1187
}
1188
+
1189
+ #[ test]
1190
+ fn compact_decoding_saturate_when_beyond_accuracy( ) {
1191
+ use num_traits:: Bounded ;
1192
+ use codec:: Compact ;
1193
+
1194
+ let p = Compact :: <$name>:: decode( & mut & Compact ( <$type>:: max_value( ) ) . encode( ) [ ..] )
1195
+ . unwrap( ) ;
1196
+ assert_eq!( ( p. 0 ) . 0 , $max) ;
1197
+ assert_eq!( $name:: from( p) , $name:: max_value( ) ) ;
1198
+ }
1169
1199
}
1170
1200
} ;
1171
1201
}
0 commit comments