Random Access: Pointer Arithmetic Helper

I spent about an hour this morning putting together a simple Zig project to help people understand pointer arithmetic a bit better. This is primarily a learning tool to help people see how pointer arithmetic is performed on raw addresses. That said, you can certainly use it you choose to do so:

Examples include:

const ra = @import("random_access.zig");

// requires one-item, many-item, or c-style pointers
var addr = ra.init(slice.ptr);

// move up by one element
addr.add(1);

// move back by one element
addr.sub(1);

// get one-item pointer:
const ptr = addr.one();

// set value with one-item ptr:
addr.one().* = 42;

// get many-item pointer:
const mptr = addr.many();

// pointer comparisons:
addr1.lt(addr2);  // less than
addr1.gt(addr2);  // greater than
addr1.lte(addr2); // less than or equal to
addr1.gte(addr2); // greater than or equal to
addr1.eql(addr2); // equal to

// use with loops:
while (addr1.lt(addr2)) : (addr1.add(1)) {
  // ...
}
5 Likes