First time working with allocators, I am misunderstanding something?

I was trying to store the messages received by stream server into an arrayList of const u8.
However, I think I am doing something wrong.
Appending a slice made from “buf” delimited by “bytes_written” results on populating the arraylist with the same memory.

So instead, I used the allocator from the arrayLis to allocate a new slice and then copy the relevant bytes from the buffer.
It works but I am not confident with my solution, is there a better way to achieve the same thing?
Was it necessary to allocate the new slice prior to appending into the arraylist?

Thank you.

Here is the snippet I was talking about for reference

fn listen(list: *std.ArrayList([]const u8)) !void {
    const address = try std.net.Address.resolveIp("127.0.0.1", 8888);
    var server = try address.listen(.{ .reuse_port = true, .reuse_address = true });
    defer _ = server.deinit();

    var buf: [64]u8 = undefined;

    while (true) {
        
        const conn = try server.accept();
        const bytes_written = try conn.stream.read(&buf);

        const str = try list.allocator.alloc(u8, bytes_written);
        std.mem.copyForwards(u8, str, buf[0..bytes_written]);
        try list.append(str);

        if (std.mem.eql(u8, str, "quit")) break;
        conn.stream.close();
    }
}

Hello @nwk
welcome to ziggit :slight_smile:

Yes, it is necessary to allocate memory.
There is another way to do it,
dupe is an allocator method that can replace:

        const str = try list.allocator.alloc(u8, bytes_written);
        std.mem.copyForwards(u8, str, buf[0..bytes_written]);

with

        const str = try list.allocator.dupe(u8, buf[0..bytes_written]);
2 Likes

Your code is kind of convoluted. If you want the bytes in the ArrayList, just read them into the ArrayList.

Edit: Noticed a bug in the buffer. I’ve corrected the code.

2 Likes

Oh, I did not think about it.

Thanks for the idea, I will experiment with it

Thank you!

It is funny how much I struggled to make this a reply instead of an isolated comment haha.

That feels more ergonomic.

I was reading the source for dupe, and I saw that it is using @memcpy, do you how does it differ from std.mem.copyForwards? I do not know where to find the source code for the builtins…

memcpy assumes no overlap between destination and source, which is way faster. copyForwards is for when there is overlap.

1 Like

Thank you!

1 Like