Repository: paritytech/substrate
File: frame/election-provider-multi-phase/src/lib.rs (Rust)

Code before:
		let known_score = supports.evaluate();
		ensure!(known_score == score, FeasibilityError::InvalidScore);

		Ok(ReadySolution { supports, compute, score })
	}

	/// Should be used instead of the getter of `Snapshot` in memory-bounded code paths.
	fn read_snapshot_with_preallocate() -> Result<RoundSnapshot<T>, Error<T>> {
		use codec::MaxEncodedLen;
		let snap = Self::snapshot_metadata().ok_or(Error::<T>::MissingSnapshot)?;
		let voters_size = snap.voters as usize * <VoterOf<T>>::max_encoded_len();
		let targets_size = snap.targets as usize * T::AccountId::max_encoded_len();

		// we want to decode two vecs, which need two u32s at most for their size.
		let initial_capacity = voters_size + targets_size + 4 + 4;
		let mut buffer = Vec::<u8>::with_capacity(initial_capacity);

		// fill this whole buffer, and decode into it.
		buffer.resize(buffer.capacity(), 0);
		let _leftover = sp_io::storage::read(&<Snapshot<T>>::hashed_key(), &mut buffer, 0)
			.ok_or(Error::<T>::MissingSnapshot)?;

		// buffer should have not re-allocated
		debug_assert!(buffer.capacity() == initial_capacity);
		<RoundSnapshot<T> as codec::Decode>::decode(&mut &*buffer).map_err(|_| Error::<T>::Codec)
	}

	/// Perform the tasks to be done after a new `elect` has been triggered:
	///
	/// 1. Increment round.
	/// 2. Change phase to [`Phase::Off`]
	/// 3. Clear all snapshot data.
	fn rotate_round() {
		// Inc round.
		<Round<T>>::mutate(|r| *r += 1);

		// Phase is off now.
		<CurrentPhase<T>>::put(Phase::Off);

		// Kill snapshots.
		Self::kill_snapshot();
	}

	fn do_elect() -> Result<Supports<T::AccountId>, ElectionError<T>> {
		// We have to unconditionally try finalizing the signed phase here. There are only two
		// possibilities:
		//
		// - signed phase was open, in which case this is essential for correct functioning of the
		//   system
		// - signed phase was complete or not started, in which case finalization is idempotent and
		//   inexpensive (1 read of an empty vector).

Review comment (performance):
Hmm... so you manually calculate how much the scale-encoded value is supposed to take, preallocate a buffer, fetch it into that buffer and then decode it. Can you explain why is this necessary? How is this different than calling `Snapshot::get()`?

AFAIK this should already be done on the FFI boundary automatically, unless I'm missing something here? (And if I'm missing something then it'd be better to fix this on the FFI boundary so that it's fixed everywhere instead of manually fixing in on a case-by-case basis like here.)

Code after:

	/// Perform the tasks to be done after a new `elect` has been triggered:
	///
	/// 1. Increment round.
	/// 2. Change phase to [`Phase::Off`]
	/// 3. Clear all snapshot data.
	fn rotate_round() {
		// Inc round.
		<Round<T>>::mutate(|r| *r += 1);

		// Phase is off now.
		<CurrentPhase<T>>::put(Phase::Off);

		// Kill snapshots.
		Self::kill_snapshot();
	}

	fn do_elect() -> Result<Supports<T::AccountId>, ElectionError<T>> {
		// We have to unconditionally try finalizing the signed phase here. There are only two
		// possibilities:
		//
		// - signed phase was open, in which case this is essential for correct functioning of the
		//   system
		// - signed phase was complete or not started, in which case finalization is idempotent and
		//   inexpensive (1 read of an empty vector).
		let _ = Self::finalize_signed_phase();
		<QueuedSolution<T>>::take()
			.map_or_else(
				|| {
					T::Fallback::elect()
						.map_err(|fe| ElectionError::Fallback(fe))
						.map(|supports| (supports, ElectionCompute::Fallback))
				},
				|ReadySolution { supports, compute, .. }| Ok((supports, compute)),
			)
			.map(|(supports, compute)| {
				Self::deposit_event(Event::ElectionFinalized { election_compute: Some(compute) });
				if Self::round() != 1 {
					log!(info, "Finalized election round with compute {:?}.", compute);
				}
				supports
			})
			.map_err(|err| {
				Self::deposit_event(Event::ElectionFinalized { election_compute: None });
				if Self::round() != 1 {
					log!(warn, "Failed to finalize election round. reason {:?}", err);
				}
				err
			})
	}