#Is there any way to check if an element has been initialized?

1 messages · Page 1 of 1 (latest)

worn pier
#

Suppose I have a slice of a type that requires to be initiallized. The slice is created as:

var arr: []T = allocator.alloc(T, 10);

for some type T with the above restriction and some allocator. Is there any way to check if, for instance, arr[1] has been initialized?

For context, I want to know in a function, if a certain element has been initiallized, because if it has, I need to call the set funciton of that element, but if it has not, I need to create a new object of that type:

arr[1] = T{ .somedata = "foo" };
flat roost
#
const arr = allocator.alloc(?T, 10);
@memset(arr, null);
// later
for (arr) |*maybe_e| {
  if (maybe_e) |*e| {
    e.set()
  } else {
    e.* = .{ .somedata = "foo" };
  }
}
regal turret
#

you can have a metadata field in T, can be more space efficient than optional.

flat roost
#

depends on how T is laid out but yeah

#

although ideally youd just store it out of band
where you have an array of uninitialized Ts that get popped and initialized before going into the array of initialized Ts

#

if thats possible

regal turret
#

An optional type (tagged union a.k.a. enum + union) will have nice alignment in memory so will not be packed to smallest memory, which is good for performance. But a metadata field can be handy since you can let the first bit be the empty/exist bool, then store some other information about T in the other bits zeroLike. And if T would be a packed struct from the start, a metadata field is your best option I would think.

flat roost
#

basically any time you have padding, you can afford a is_optional field

regal turret
#

^ yea

flat roost
#

either way, optionals will never be smaller than just the sturct + a bool