Skip to content

Commit

Permalink
removes TryIntoBoundedSupports trait and impl coversion directly in S…
Browse files Browse the repository at this point in the history
…upportedBounds
  • Loading branch information
gpestana committed Nov 14, 2024
1 parent 825984b commit 93d6bda
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 28 deletions.
6 changes: 3 additions & 3 deletions substrate/frame/election-provider-multi-phase/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ use codec::{Decode, Encode};
use frame_election_provider_support::{
bounds::{CountBound, ElectionBounds, ElectionBoundsBuilder, SizeBound},
BoundedSupports, BoundedSupportsOf, DataProviderBounds, ElectionDataProvider, ElectionProvider,
InstantElectionProvider, NposSolution, PageIndex, TryIntoBoundedSupports,
InstantElectionProvider, NposSolution, PageIndex,
};
use frame_support::{
dispatch::DispatchClass,
Expand Down Expand Up @@ -1007,7 +1007,7 @@ pub mod pallet {

// bound supports with T::MaxWinners.
let supports: BoundedSupportsOf<Pallet<T>> =
supports.try_into_bounded_supports().map_err(|_| Error::<T>::TooManyWinners)?;
supports.try_into().map_err(|_| Error::<T>::TooManyWinners)?;

// Note: we don't `rotate_round` at this point; the next call to
// `ElectionProvider::elect` will succeed and take care of that.
Expand Down Expand Up @@ -2534,7 +2534,7 @@ mod tests {
(30, Support { total: 40, voters: vec![(2, 5), (4, 5), (30, 30)] }),
(40, Support { total: 60, voters: vec![(2, 5), (3, 10), (4, 5), (40, 40)] }),
]
.try_into_bounded_supports()
.try_into()
.unwrap();

assert_eq!(supports, expected_supports);
Expand Down
6 changes: 2 additions & 4 deletions substrate/frame/election-provider-multi-phase/src/unsigned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ use crate::{
};
use alloc::{boxed::Box, vec::Vec};
use codec::Encode;
use frame_election_provider_support::{
NposSolution, NposSolver, PerThing128, TryIntoBoundedSupports, VoteWeight,
};
use frame_election_provider_support::{NposSolution, NposSolver, PerThing128, VoteWeight};
use frame_support::{
dispatch::DispatchResult,
ensure,
Expand Down Expand Up @@ -823,7 +821,7 @@ impl<T: MinerConfig> Miner<T> {

// Size of winners in miner solution is equal to `desired_targets` <= `MaxWinners`.
let supports = supports
.try_into_bounded_supports()
.try_into()
.defensive_map_err(|_| FeasibilityError::BoundedConversionFailed)?;

Ok(ReadySolution { supports, compute, score })
Expand Down
23 changes: 10 additions & 13 deletions substrate/frame/election-provider-support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -849,33 +849,30 @@ impl<AccountId, BOuter: Get<u32>, BInner: Get<u32>> IntoIterator
}
}

/// An extension trait to convert from [`sp_npos_elections::Supports<AccountId>`] into
/// [`BoundedSupports`].
pub trait TryIntoBoundedSupports<AccountId, BOuter: Get<u32>, BInner: Get<u32>> {
/// Perform the conversion.
fn try_into_bounded_supports(self) -> Result<BoundedSupports<AccountId, BOuter, BInner>, ()>;
}

impl<AccountId, BOuter: Get<u32>, BInner: Get<u32>>
TryIntoBoundedSupports<AccountId, BOuter, BInner> for sp_npos_elections::Supports<AccountId>
impl<AccountId, BOuter: Get<u32>, BInner: Get<u32>> TryFrom<sp_npos_elections::Supports<AccountId>>
for BoundedSupports<AccountId, BOuter, BInner>
{
fn try_into_bounded_supports(self) -> Result<BoundedSupports<AccountId, BOuter, BInner>, ()> {
type Error = crate::Error;

fn try_from(supports: sp_npos_elections::Supports<AccountId>) -> Result<Self, Self::Error> {
// optimization note: pre-allocate outer bounded vec.
let mut outer_bounded_supports = BoundedVec::<
(AccountId, BoundedSupport<AccountId, BInner>),
BOuter,
>::with_bounded_capacity(
self.len().min(BOuter::get() as usize)
supports.len().min(BOuter::get() as usize)
);

// optimization note: avoid intermediate allocations.
self.into_iter()
supports
.into_iter()
.map(|(account, support)| (account, support.try_into().map_err(|_| ())))
.try_for_each(|(account, maybe_bounded_supports)| {
outer_bounded_supports
.try_push((account, maybe_bounded_supports?))
.map_err(|_| ())
})?;
})
.map_err(|_| crate::Error::BoundsExceeded)?;

Ok(outer_bounded_supports.into())
}
Expand Down
11 changes: 5 additions & 6 deletions substrate/frame/election-provider-support/src/onchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
use crate::{
bounds::{DataProviderBounds, ElectionBounds, ElectionBoundsBuilder},
BoundedSupportsOf, Debug, ElectionDataProvider, ElectionProvider, InstantElectionProvider,
NposSolver, PageIndex, TryIntoBoundedSupports, WeightInfo, Zero,
NposSolver, PageIndex, WeightInfo, Zero,
};
use alloc::collections::btree_map::BTreeMap;
use core::marker::PhantomData;
Expand Down Expand Up @@ -147,9 +147,8 @@ impl<T: Config> OnChainExecution<T> {

// defensive: Since npos solver returns a result always bounded by `desired_targets`, this
// is never expected to happen as long as npos solver does what is expected for it to do.
let supports: BoundedSupportsOf<Self> = to_supports(&staked)
.try_into_bounded_supports()
.map_err(|_| Error::TooManyWinners)?;
let supports: BoundedSupportsOf<Self> =
to_supports(&staked).try_into().map_err(|_| Error::TooManyWinners)?;

Ok(supports)
}
Expand Down Expand Up @@ -321,7 +320,7 @@ mod tests {
),
(30, Support { total: 35, voters: vec![(2, 20), (3, 15)] }),
]
.try_into_bounded_supports()
.try_into()
.unwrap();

assert_eq!(
Expand Down Expand Up @@ -357,7 +356,7 @@ mod tests {
),
(30, Support { total: 35, voters: vec![(2, 20), (3, 15)] })
]
.try_into_bounded_supports()
.try_into()
.unwrap()
);
})
Expand Down
4 changes: 2 additions & 2 deletions substrate/frame/staking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::{self as pallet_staking, *};
use frame_election_provider_support::{
bounds::{ElectionBounds, ElectionBoundsBuilder},
onchain, BoundedSupports, BoundedSupportsOf, ElectionProvider, PageIndex, SequentialPhragmen,
Support, TryIntoBoundedSupports, VoteWeight,
Support, VoteWeight,
};
use frame_support::{
assert_ok, derive_impl, ord_parameter_types, parameter_types,
Expand Down Expand Up @@ -1023,5 +1023,5 @@ pub(crate) fn to_bounded_supports(
<<Test as Config>::ElectionProvider as ElectionProvider>::MaxWinnersPerPage,
<<Test as Config>::ElectionProvider as ElectionProvider>::MaxBackersPerWinner,
> {
supports.try_into_bounded_supports().unwrap()
supports.try_into().unwrap()
}
2 changes: 2 additions & 0 deletions substrate/primitives/npos-elections/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ pub enum Error {
InvalidSupportEdge,
/// The number of voters is bigger than the `MaxVoters` bound.
TooManyVoters,
/// Some bounds were exceeded when converting election types.
BoundsExceeded,
}

/// A type which is used in the API of this crate as a numeric weight of a vote, most often the
Expand Down

0 comments on commit 93d6bda

Please sign in to comment.