ndarray
ndarray copied to clipboard
Add .shrink_to_fit() method for Array
Some methods (e.g. .remove_axis(), .into_subview(), and .slice_move()) can cause some of the elements in an owned array to be come inaccessable. It would be useful to have a method that removes the inaccessable elements (to reduce memory usage without performing a new heap allocation) by shifting the remaining elements to the front of the underlying Vec and shrinking the Vec. See the discussion in #425, in particular this comment for some thoughts about the implementation.
Hello!
I would like to work on this issue, but I have one question: if the ptr of an Array has an offset, how do I find the first element of the allocated ptr?
For example, suppose you have an Array of dim-> (3, 3),stride-> (3, 1) and you drop the 0th row (dim-> (2, 3), stride -> (3, 1)). Then the ptr is considered to be offset by three. Once it is offset, it is difficult to calculate the offset for these three in shrink_to_fit().
[[0, 1, 2],
[3, 4, 5], -> [[3, 4, 5],
[6, 7, 8],]. [6, 7, 8],]
memory order
ptr -> ptr(difficult to find first ptr. In this case, the pointer pointing to the zero element)
▼ ▼
0, 1, 2, 3, 4, 5, 6, 7, 8 0, 1, 2, 3, 4, 5, 6, 7, 8
An easy solution I can think of is to record the offset in an ArrayBase, but I don't think that's a good idea since it would require a lot of implementation and there would be few opportunities to use it. What do you think about this problem?
For owned arrays, you can determine this offset by the following snippet (copied from the append implementation):
let data_to_array_offset = if std::mem::size_of::<A>() != 0 {
self.as_ptr().offset_from(self.data.as_ptr())
} else {
0
};
debug_assert!(data_to_array_offset >= 0);
The ptr field of ArrayBase is a pointer to the first element. The data field of an owned array has type OwnedRepr, which is effectively a Vec – it has a pointer (to the start of the allocation), length, and capacity.