rust-embedded/heapless

Infallible Vec operations

robin-nitrokey opened this issue · 4 comments

Some operations on a Vec<T, N> are infallible but can only be implemented using fallible methods. What do you think about adding more infallible methods? For example:

  • from_array(data: [T; N]): construct a Vec from an array with the same capacity (would also be useful for constants)
  • fill(&mut self, value: T): resize to capacity and clone value to empty slots
  • fill_default(&mut self): resize to capacity and write T::default() to empty slots
  • replace(&mut self, other: &Self): clear this Vec and copy the data from other

from_array is now implemented in #352.

fill already exists on slice, i.e. via DerefMut, same with fill_with(Default::default) instead of fill_default. These only fill up to the current length, though. What is the use case for the fill methods filling up to capacity? Is it covered now with .spare_capacity_mut().fill(…)?

For replace, I assume this should work only for Vec with the same capacity, otherwise it would still need to be fallible. Again, what is the use case for this method?

Good to see from_array being added! Unfortunately, the implementation is not const. It would still be useful to be able to create non-empty constants.

My use case for fill is preparing a buffer for functions that expect a &mut [u8] for writing. Currently, you have to call v.resize_default(v.capacity()) which is fallible. spare_capacity_mut().fill(MaybeUninit::new(...)) should work but is not really intuitive.

For replace, I don’t remember the specific use case. I’ll report back if I find it again.