#How do I do pointer arithmetic with a signed integer?

1 messages · Page 1 of 1 (latest)

coarse tide
#

I have a snippet of code like:

const addr: [*]u8 = @ptrCast(self);
const offset: i16 = self.next_offset;

Where self is just a pointer and next_offset is the distance in bytes from the next instance of my object. This is basically a linked list but instead of storing next as a pointer I am storing it as an offset to save some bits (because I know the next thing is pretty close by).

Anyways, I want to get to that next item by doing pointer arithmetic. I thought I could do something like:

const next: [*]u8 = addr + offset;

But the compiler doesn't like that. It's telling me that it expects offset to be a usize, and you can't safely coerce i16 to usize (obviously, because usize can't be negative). But I want that behavior. It seems really silly to have some if statement that checks if it's negative. Is there a better way of doing this?

coarse tide
#

Like I can do:

pub fn getNext(self: *MyLinkedItem) *MyLinkedItem {
    const addr: [*]u8 = @ptrCast(self);
    const offset: i16 = self.next_offset;
    if (offset < 0) {
        return @alignCast(@ptrCast(addr - @as(u15, @intCast(-offset))));
    } else {
        return @alignCast(@ptrCast(addr + @as(u15, @intCast(offset))));
    }
}

and it works, but it makes me feel disgusting for writing it. Is there really no better way to do this?

bronze quarry
#

i would convert addr to an isize. still pretty messy, but then it might look like this:

    const addr: isize = @intCast(@intFromPtr(@ptrCast(self)));
    const offset: i16 = self.next_offset;
    return @alignCast(@ptrCast(@ptrFromInt(@intCast(addr + offset))));
coarse tide
#

That’s a good idea, thanks 👍🏼

#

Still kinda scuffed but ill take it