Skip to content

Conversation

@lanterno
Copy link
Contributor

@lanterno lanterno commented Jan 29, 2026

Description

Hello,
This PR adds a new method set_len on BoundedVec. My team needed it as we wanted to optimize a code snippet
like:

for i in 0..SOME_LEN {
    vec.push(..)
}

to:

for i in 0..SOME_LEN {
    vec.set_unchecked(vec.len() + i, some_value)
}
vec.set_len(vec.len() + SOME_LEN)

Summary

So, this PR adds set_len to achieve the above goal easily.
There's already other existing methods that do this optimization like extend_from_array or extend_from_bounded_vec etc. However, this is more useful when set_unchecked.

User Documentation

Check one:

  • No user documentation needed.
  • Changes in docs/ included in this PR.
  • [For Experimental Features] Changes in docs/ to be submitted in a separate PR.

PR Checklist

  • Ran cargo insta test
  • I have tested the changes locally.
  • I have formatted the changes with Prettier and/or cargo fmt on default settings.

@github-actions
Copy link
Contributor

Thank you for your contribution to the Noir language.

Please do not force push to this branch after the Noir team have started review of this PR. Doing so will only delay us merging your PR as we will need to start the review process from scratch.

Thanks for your understanding.

@lanterno lanterno force-pushed the feat/add-boundedvec-set-leng branch from 56a62f6 to eeeff00 Compare January 29, 2026 20:16
/// ```
pub fn set_len(&mut self, len: u32) {
assert(len <= MaxLen, "set_len out of bounds");
assert(len >= self.len(), "can not set_len to a length shorter than the current length");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it's meant to be used with the already unsafe set_unchecked, and it is allowed to be set to anything up to MaxLen, which can result in get returning zeroed items if just increase the length of without setting elements, why not also allow it to shorten the vector, which would make it work a bit like Vec::truncate in Rust?

@jfecher
Copy link
Contributor

jfecher commented Jan 30, 2026

My team needed it as we wanted to optimize a code snippet
like:

Can you elaborate a bit more on your optimization need? E.g. was this for constrained or unconstrained code? Have you compared the difference this makes for your program, etc. Since this would be an additional method meant purely for optimization I think the additional context and concrete numbers are important here.

In particular compared to extend_from_array I'd expect a difference of at most 1 assertion compared to the entirely unchecked variant.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants