Last active
December 23, 2019 05:08
-
-
Save cshenton/08db802c58ebb3777a80e5797a1b6238 to your computer and use it in GitHub Desktop.
arrayInfo programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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