Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement BoundedVec::try_with_capacity #791

Open
2 tasks done
Moliholy opened this issue Sep 27, 2023 · 0 comments
Open
2 tasks done

Implement BoundedVec::try_with_capacity #791

Moliholy opened this issue Sep 27, 2023 · 0 comments

Comments

@Moliholy
Copy link

Moliholy commented Sep 27, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant