#How to clean up elements of an array

1 messages · Page 1 of 1 (latest)

honest rivet
#
var buffers: [THREADS]*Buffer = undefined;
{
    var i: usize = 0;
    errdefer for (0..i) |j| {
        alloc.destroy(buffers[j]);
    };
    while (i < buffers.len) : (i += 1) {
        buffers[i] = try alloc.create(Buffer);
    }
}
defer for (buffers) |buffer| {
    alloc.destroy(buffer);
};

Is there an idiomatic pattern to use for this?

marble glacier
#

That's pretty close. Although I don't know why you're using a while loop there

#
var buffers: [THREADS]*Buffer = undefined;
for (&buffers, 0..) |*buf, i| {
    errdefer for (buffers[0..i]) |prev|
        allocator.destroy(prev);
    buf.* = try allocator.create(Buffer);
}
defer for (buffers) |buf| allocator.destroy(buf);
#

another way to got about this would be to used a bounded array

honest rivet
#

how should I think about the performance of defer blocks? are they (semantically) statically inlined at return sites

marble glacier
#

they are just run at the end of the block

honest rivet
#

but that looks great :) ty.

marble glacier
#

it's the same as manually setting them up at each relevant end of scope

honest rivet
marble glacier
#

what do you mean by followed?

#

there is a small cost to error handling with errors as values

#

with that cost being the branch on whether there's an error or not

#

for errdefer specifically, there's likely some specific ways in which it's optimised such that branching is minimised, or friendly to the branch predictor

#

in particular, error branches (errdefer, catch blocks, else |err| blocks) are all annotated as cold branches

honest rivet
#

Ig more specifically, is there ever any runtime state associated with an errdefer?

marble glacier
#

nothing "associated" with it, no

honest rivet
#

or can I trust that they're alr to put in a for loop like this in all cases

marble glacier
#

they're fine to put in the for loop

#

it's the same as manually checking for any errors in that scope, and executing that expression if any error is encountered

#

probably also has some optimisation for code size to put it under a single label which all the following error checks goto in the case of error

honest rivet
#

but that's great, thx