parity-common icon indicating copy to clipboard operation
parity-common copied to clipboard

Implement BoundedVec::try_with_capacity

Open Moliholy opened this issue 9 months ago • 0 comments

Is there an existing issue?

  • [X] I have searched the existing issues

Experiencing problems? Have you tried our Stack Exchange first?

  • [X] This is not a support question.

Motivation

There are cases in pallets where unbounded arrays are passed. At some point elements in those arrays are likely mapped to a bounded vector whose capacity is not enough to contain all elements, so after a few iterations an error is generated, wasting some computation in the process.

The main idea is that BoundedVec::with_bounded_capacity() is a non-intuitive constructor. One has to read the docs (and keep in mind) to find out that the minimum between the value passed and the maximum capacity is going to be used, which is error prone. In my opinion, that constructor should be removed and replaced by this one, but I understand there is a lot of code written with BoundedVec::with_bounded_capacity(), so I think it could be simply deprecated. Or at least the proposed feature could live along BoundedVec::with_bounded_capacity() for the time being.

Request

Implement a constructor that raises an error if the requested capacity is greater than the maximum.

This way developers would know in advance whether they are going to be able to effectively use the BoundedVec for their purposes or not, and eagerly return the corresponding error instead of wasting computational resources.

Solution

Something like this:

impl<T, S: Get<u32>> BoundedVec<T, S> {
        // -- snip --

        /// Pre-allocate `capacity` items in self.
	///
	/// If `capacity` is greater than [`Self::bound`], then an error is returned.
	pub fn try_with_capacity(capacity: usize) -> Result<Self, ()> {
		if Self::bound() < capacity {
                     return Err(());
                }
		Ok(Self(Vec::with_capacity(capacity), Default::default()))
	}

        // -- snip --
}

Are you willing to help with this request?

Absolutely.

Moliholy avatar Sep 27 '23 10:09 Moliholy