#Why doesn't Zig allow pointer comparison for similar types

1 messages · Page 1 of 1 (latest)

teal parcel
#

By similar I meant same type or differing only in const vs non-const. There shouldn't be any memory safety concerns here. Zig many-item pointers do support pointer arithmetic and it seems reasonable to be able to compare two such pointers.

The context for this question is I was looking at code for a memory allocator written in C and since it's doling out chunks of memory it has some assertions verifying that memory addresses fall in a range. Porting that to zig would require sprinkling @ptrToInt() in lots of places which is a pain.

ionic basalt
#

I don't know the actual reason, but one thing I might suggest is that it would allow inconsistent / implementation-detail-dependent comptime code, which is generally something we try to disallow:

if (comptime ptr_a < ptr_b) { ... } else { ... }

It's the same sort of reason that @ptrToInt is disallowed at comptime - comptime pointers are fancy (since they're GC'd and point to boxed values) so you can't meaningfully look at the raw value. In that case, we just disallow the operation at comptime, but it's possible that for comparisons, being a less "explicit" operation in a sense, the core team didn't want to make that distinction.
A simpler argument might be that putting @ptrToInt wherever you need comparisons, while a bit more verbose, is less bug-prone and easier to read since the intent is very explicit and pointer comparisons aren't a hugely common thing to need.
Note that in your case, you could probably just write a small helper function if you want:

fn assertPtrRange(ptr: anytype, min: @TypeOf(ptr), max: @TypeOf(ptr)) void {
    if (@ptrToInt(ptr) < @ptrToInt(min) or @ptrToInt(ptr) > @ptrToInt(max)) {
        unreachable; // assertion failure
    }
}

// assertPtrRange(val, min, max);
teal parcel
#

I agree pointer comparison is not a hugely common thing but useful for low level code like allocators, device drivers or operating systems (manipulating address spaces). A helper function definitely makes it easier and. with Zig's comptime types they can be made type safe. Thank you for responding.

lilac hornet