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

Commit

Permalink
Make decoding of compact<perthing> saturating instead of invalid (#…
Browse files Browse the repository at this point in the history
…7062)

* make decoding of cmopact<perthing> saturating

* fix stable build

* Update primitives/arithmetic/src/per_things.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

* Update primitives/arithmetic/src/per_things.rs

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
  • Loading branch information
2 people authored and bkchr committed Sep 18, 2020
1 parent 0f61352 commit 0fd0d95
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion primitives/arithmetic/src/per_things.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,9 +323,28 @@ macro_rules! implement_per_thing {
///
#[doc = $title]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RuntimeDebug, CompactAs)]
#[derive(Encode, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RuntimeDebug)]
pub struct $name($type);

/// Implementation makes any compact encoding of `PerThing::Inner` valid,
/// when decoding it will saturate up to `PerThing::ACCURACY`.
impl CompactAs for $name {
type As = $type;
fn encode_as(&self) -> &Self::As {
&self.0
}
fn decode_from(x: Self::As) -> Self {
// Saturates if `x` is more than `$max` internally.
Self::from_parts(x)
}
}

impl From<codec::Compact<$name>> for $name {
fn from(x: codec::Compact<$name>) -> $name {
x.0
}
}

impl PerThing for $name {
type Inner = $type;
type Upper = $upper_type;
Expand Down Expand Up @@ -1166,6 +1185,17 @@ macro_rules! implement_per_thing {
// deconstruct is also const, hence it can be called in const rhs.
const C5: bool = C1.deconstruct() == 0;
}

#[test]
fn compact_decoding_saturate_when_beyond_accuracy() {
use num_traits::Bounded;
use codec::Compact;

let p = Compact::<$name>::decode(&mut &Compact(<$type>::max_value()).encode()[..])
.unwrap();
assert_eq!((p.0).0, $max);
assert_eq!($name::from(p), $name::max_value());
}
}
};
}
Expand Down

0 comments on commit 0fd0d95

Please sign in to comment.