Skip to content
New issue

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

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

Already on GitHub? # to your account

Add .shrink_to_fit() method for Array #427

Open
jturner314 opened this issue Mar 19, 2018 · 2 comments
Open

Add .shrink_to_fit() method for Array #427

jturner314 opened this issue Mar 19, 2018 · 2 comments

Comments

@jturner314
Copy link
Member

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.

@bokutotu
Copy link

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?

@jturner314
Copy link
Member Author

jturner314 commented Dec 18, 2021

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.

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

No branches or pull requests

2 participants