substrate icon indicating copy to clipboard operation
substrate copied to clipboard

Add `DefensiveTruncateFrom`

Open ggwpez opened this issue 3 years ago • 1 comments

Introduces a defensive_truncate_from trait function to defensively truncate if TryFrom failed because of length bounds. Example:

use frame_support::{BoundedVec, traits::DefensiveTruncateFrom};
use sp_runtime::traits::ConstU32;

let unbound = vec![1, 2, 3];
let bound = BoundedVec::<u8, ConstU32<2>>::defensive_truncate_from(unbound);

assert_eq!(bound, vec![1, 2]); // Truncated to two elements.

cc @kianenigma hopefully we can use this in the staking code to easily remove some expects :smile:.

Adds:

  • TruncateFrom trait and implementation for BoundedVec+BoundedSlice
  • DefensiveTruncateFrom trait
  • Debug impl for BoundedSlice
  • PartialEq<&'a [T]> impl for BoundedSlice

Changes:

  • Error type of TryFrom<&'a [T]> for BoundedSlice from () to &[T] analogous to BoundedVec

ggwpez avatar Oct 17 '22 22:10 ggwpez

This pull request has been mentioned on Polkadot Forum. There might be relevant details there:

https://forum.polkadot.network/t/testing-complex-frame-pallets-discussion-tools/356/7

Polkadot-Forum avatar Oct 18 '22 11:10 Polkadot-Forum

Was discussing it with @Ank4n: can you add a defensive_min() and defensive_max as well? I think there are a LOT of use cases where we do these operations defensively.

kianenigma avatar Oct 19 '22 12:10 kianenigma

LGTM, although it is worth noting whether these defensive ops need to be in frame-support anyway.

The defensive! macro uses frame_support::log::error, but it seems to just be a re-export of the log crate, so could be moved IIUC.

ggwpez avatar Oct 19 '22 15:10 ggwpez

bot rebase

shawntabrizi avatar Oct 20 '22 14:10 shawntabrizi

Rebased

bot rebase

ggwpez avatar Oct 20 '22 20:10 ggwpez

Rebased

bot merge

ggwpez avatar Oct 20 '22 21:10 ggwpez