Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 0fd0d95

Browse files
gui1117kianenigma
authored andcommitted
Make decoding of compact<perthing> saturating instead of invalid (#7062)
* make decoding of cmopact<perthing> saturating * fix stable build * Update primitives/arithmetic/src/per_things.rs Co-authored-by: Kian Paimani <[email protected]> * Update primitives/arithmetic/src/per_things.rs Co-authored-by: Kian Paimani <[email protected]> Co-authored-by: Kian Paimani <[email protected]>
1 parent 0f61352 commit 0fd0d95

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

primitives/arithmetic/src/per_things.rs

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,9 +323,28 @@ macro_rules! implement_per_thing {
323323
///
324324
#[doc = $title]
325325
#[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)]
327327
pub struct $name($type);
328328

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+
329348
impl PerThing for $name {
330349
type Inner = $type;
331350
type Upper = $upper_type;
@@ -1166,6 +1185,17 @@ macro_rules! implement_per_thing {
11661185
// deconstruct is also const, hence it can be called in const rhs.
11671186
const C5: bool = C1.deconstruct() == 0;
11681187
}
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+
}
11691199
}
11701200
};
11711201
}

0 commit comments

Comments
 (0)