Skip to content

Instantly share code, notes, and snippets.

@fengb
Created July 3, 2019 13:44
Show Gist options
  • Save fengb/dab28366f60b271b8fe8fad7529fab0a to your computer and use it in GitHub Desktop.
Save fengb/dab28366f60b271b8fe8fad7529fab0a to your computer and use it in GitHub Desktop.
const std = @import("std");
pub fn Matrix(comptime T: type, width: usize, height: usize) type {
return struct {
const Self = @This();
width: usize = width,
height: usize = height,
array: [height * width]T = undefined,
slice: MatrixSlice(T) = MatrixSlice(T){
.width = width,
.height = height,
.slice = array[0..],
},
};
}
pub fn MatrixSlice(comptime T: type) type {
return struct {
const Self = @This();
width: usize,
height: usize,
slice: []T,
pub fn get(self: Self, x: usize, y: usize) T {
const i = self.idx(x, y);
return self.slice[i];
}
pub fn set(self: Self, x: usize, y: usize, val: T) void {
const i = self.idx(x, y);
self.slice[i] = val;
}
fn idx(self: Self, x: usize, y: usize) usize {
return x + y * self.width;
}
};
}
test "foo" {
const Mu8 = Matrix(u8, 10, 8);
const m = try std.heap.direct_allocator.create(Mu8);
std.debug.warn("{} {}\n", @ptrToInt(&m.array), @ptrToInt(m.slice.slice.ptr));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment