Add `DefensiveTruncateFrom`
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:
TruncateFromtrait and implementation forBoundedVec+BoundedSliceDefensiveTruncateFromtraitDebugimpl forBoundedSlicePartialEq<&'a [T]>impl forBoundedSlice
Changes:
- Error type of
TryFrom<&'a [T]>forBoundedSlicefrom()to&[T]analogous toBoundedVec
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
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.
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.
bot rebase
Rebased
bot rebase
Rebased
bot merge