#Span array until zeros (structs)

1 messages · Page 1 of 1 (latest)

spare swallow
#

I want to iterate over an array via a C pointer until I find a null sentinel. However, my array is not comprised of primitives, but instead structs. I couldn't get std.mem.span to work with structs, so I've written this that seems to work:

fn spanMem(comptime T: type, ptr: [*c]const T) []const T {
    const sentinel: [@sizeOf(T)]u8 = @bitCast(std.mem.zeroes(T));

    var i: usize = 0;
    while (true) : (i += 1) {
        const elem: [@sizeOf(T)]u8 = @bitCast(ptr[i]);
        if (std.mem.eql(u8, &elem, &sentinel))
            return ptr[0..i];
    }
}

Is this sensible? Is there a function in the std that I'm missing that will do this for me?

fathom jay
#

perhaps std.meta.eql is what you're after
it essentially synthesises an equality check on arbitrary types - make sure to read the docs to be certain this does what you want

wet hill
#

if you don't need it to be generic,

var i: usize = 0;
while (true) : (i += 1) {
    if(ptr[i] is null) break;
}
spare swallow
#

I did have a look at std.meta.eql but I opted just to check the memory of the struct instead. Although thinking about it more, wont padding interfere with my function? Perhaps I should be using std.meta.eql...

fathom jay
wet hill
#

you can use std.mem.hasUniqueRepresentation to check if it's ok to compare with std.mem.eql

#

if it doesn't have a unique representation then two structs could be the same but have different underlying bytes

fathom jay
wet hill
#

yeah

spare swallow
fathom jay
# spare swallow Nice, my function looks like this now: ```rust fn spanMem(comptime T: type, ptr:...

this looks good.
may I suggest...

fn spanMem(comptime T: type, ptr: [*c]const T) [:std.mem.zeroes(T)]const T {
    const sentinel = comptime std.mem.zeroes(T); // `comptime` to force comptime function eval
    var i: usize = 0;
    while (!std.meta.eql(ptr[i], sentinel)) i += 1;
    return ptr[0..i :sentinel];
}
```it's a waste to forget the sentinel information - if we know it's there, let's encode that knowledge in the type!