Skip to content

Instantly share code, notes, and snippets.

@cshenton
Last active December 23, 2019 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cshenton/08db802c58ebb3777a80e5797a1b6238 to your computer and use it in GitHub Desktop.
Save cshenton/08db802c58ebb3777a80e5797a1b6238 to your computer and use it in GitHub Desktop.
arrayInfo programming
const std = @import("std");
const ArrayInfo = struct {
rank: usize,
child: type,
};
fn arrayInfo(comptime artype: type) ArrayInfo {
var rank: usize = 0;
var currentType: type = artype;
while (true) {
switch (@typeInfo(currentType)) {
.Array => |arinfo| {
rank += 1;
currentType = arinfo.child;
},
.Pointer => |ptinfo| {
if (ptinfo.size == .Slice) {
rank += 1;
currentType = ptinfo.child;
} else {
return ArrayInfo{ .rank = rank, .child = currentType };
}
},
else => {
return ArrayInfo{ .rank = rank, .child = currentType };
},
}
}
}
const expectEqual = std.testing.expectEqual;
test "arrayInfo" {
const a = [_]f64{ 1, 2, 3 };
const b = [_][3]f64{
.{ 1, 2, 3 },
.{ 1, 2, 3 },
};
const c = b[0..2];
expectEqual(arrayInfo(@TypeOf(a)), ArrayInfo{ .rank = 1, .child = f64 });
expectEqual(arrayInfo(@TypeOf(b)), ArrayInfo{ .rank = 2, .child = f64 });
expectEqual(arrayInfo(@TypeOf(c)), ArrayInfo{ .rank = 2, .child = f64 });
}
@cshenton
Copy link
Author

You could consider this complete if you're willing to handle non array type inputs to arrayInfo as rank zero arrays of the input type. That's probably more user friendly than a @compileError

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment