Skip to content

Implement BoundedVec::try_with_capacity #791

@moliholy

Description

@moliholy

Is there an existing issue?

  • I have searched the existing issues

Experiencing problems? Have you tried our Stack Exchange first?

  • 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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions