Fastest way to 'switch' ownership of arraylist

What is the best and fastest way to do this without copying?

fn compress(list: *std.ArrayList(u8)) !void
{
    var new_list = std.ArrayList(u8).init();
    // create contents of new_list
    // list = new_list (without copy)
    // deinit new_list
}

You can just assign the whole list struct to transfer ownership.

    var new_list = std.ArrayList(u8).init(allocator);
    // create contents of new_list
    list.deinit();
    list.* = new_list;

Be careful not to double .deinit() though!

For bonus points, ditch the ArrayList and use ArrayListUnmanaged instead.

4 Likes

Works!
What is the benefit of ArrayListUnmanaged?
Doesn’t std.ArrayList(u8) automatically create an unmanaged one?

One reason is that it’s gonna be deprecated.

2 Likes

So… now we have to put an extra alllocator parameter with each append / insert??
At first sight that is ultimately confusing for me.

I think the idea is to promote using ensureCapacity once at the beginning of the function and then appendAssumeCapacity/insertAssumeCapacity.

4 Likes

ArrayListUnmanaged is much smaller than ArrayList because it does not store an Allocator (nearly half the size iirc).

In practice you very rarely need an extra copy of the Allocator because it’s usually available already as a function parameter or a member of the enclosing structure if there is one.

Also, I find the ergonomics of ArrayListUnmanaged are actually better because you can default initialize them to .empty, which is kind of cool because you’re not forced to provide an allocator until it’s actually used.

No, they are completely separate unrelated types.

4 Likes

Ok that makes sense somehow. And I like compact and small.

But theoretically you can append with different allocators to the same list, which will totally crash (i dare not try it).
Isn’t that a complete mess (theoretically)?

Or am I competely missing something?

that depends entirely on the allocators you use.
for the allocators currently in std that will crash
but there is nothing stopping you from creating some allocators that let you do that