#How to wrap an owned slice into std.ArrayList interface?

1 messages · Page 1 of 1 (latest)

ionic rampart
#

I hope the code speaks for itself:

test {
    const alloc = std.testing.allocator;

    // In case I got an owned slice of memory
    const slice = try std.fmt.allocPrint(alloc, "\"{s}", .{"Hello"});
    defer alloc.free(slice);

    // How to wrap it into ArrayList?
    var wrapper = std.ArrayList(u8).init(alloc);
    defer wrapper.deinit();
    try wrapper.appendSlice(slice);

    // To get the usual interface
    try wrapper.appendSlice(" world!\"");
    try std.testing.expectEqualStrings("\"Hello world!\"", wrapper.items);
}

I mean, the way I did it above works okay, but I think the step of copying the already owned region of memory into a new one is redundant (in wrapper.appendSlice(slice)), and it could be just this (pseudo-code):

// ... within an ArrayList(T) function that generates a type ...
pub fn initFromOwnedSlice(allocator: Allocator, mem: []T) Self {
    return Self{
        .items = mem,
        .capacity = mem.len,
        .allocator = allocator,
    };
}
olive river
#

you're looking for fromOwnedSlice

ionic rampart
#

wow!