slice-of-array icon indicating copy to clipboard operation
slice-of-array copied to clipboard

Owned data conversions ARE possible

Open ExpHP opened this issue 6 years ago • 1 comments
trafficstars

The primary issue that prevented me from implementing these on Vecs was the cap field, which is not necessarily a multiple of the array length when using nest(). However, Box<[T]> and Rc<[T]> have no such problem.

Furthermore, in the current implementation of Vec, the value of the cap field is always a deterministic function of the sequence of methods called on the Vec, independent of the block sizes used by the allocator:

https://users.rust-lang.org/t/needlessly-weak-promises-on-vector-capacity/25572

However, I am not willing to provide these methods on Vec until there is a method whose documentation explicitly guarantees that it will set cap = len.

ExpHP avatar Jul 11 '19 13:07 ExpHP

Update: The Vec docs now specify a number of tools that let you precisely control the capacity.

vec![x; n], vec![a, b, c, d], and Vec::with_capacity(n), will all produce a Vec with exactly the requested capacity. If len==capacity, (as is the case for the vec! macro), then a Vec<T> can be converted to and from a Box<[T]> without reallocating or moving the elements.

(annoyingly, the shrink_to_fit docs still contain some weaselly language, but you can at least convert Vec<T> => Box<[T]> => Vec<T> to guarantee that len == cap)

This means I am more amenable to providing methods on Vec than I previously was. However, I would somewhat prefer if they had different signatures, to force the programmer to recognize that there are non-obvious reasons why Vec conversion may fail.

Box<[T]> -> Box<[[T; 3]]>
Vec<T> -> Option<Vec<[T; 3]>>

ExpHP avatar Dec 24 '19 21:12 ExpHP