diff --git a/src/isIndexable.zig b/src/isIndexable.zig new file mode 100644 index 0000000000000000000000000000000000000000..ec59ec2a2d4fd3355bcd9ab524dfc84084a2cfc9 --- /dev/null +++ b/src/isIndexable.zig @@ -0,0 +1,38 @@ +const std = @import("std"); +const string = []const u8; +const extras = @import("./lib.zig"); + +pub fn isIndexable(comptime T: type) bool { + if (comptime is(.Pointer)(T)) { + if (@typeInfo(T).Pointer.size == .One) { + return (comptime is(.Array)(std.meta.Child(T))); + } + return true; + } + return comptime is(.Array)(T) or is(.Vector)(T) or isTuple(T); +} +fn is(comptime id: std.builtin.TypeId) fn (type) bool { + const Closure = struct { + pub fn trait(comptime T: type) bool { + return id == @typeInfo(T); + } + }; + return Closure.trait; +} +fn isTuple(comptime T: type) bool { + return is(.Struct)(T) and @typeInfo(T).Struct.is_tuple; +} + +test { + const array = [_]u8{0} ** 10; + const slice = @as([]const u8, &array); + const vector: @Vector(2, u32) = [_]u32{0} ** 2; + const tuple = .{ 1, 2, 3 }; + + try std.testing.expect(isIndexable(@TypeOf(array))); + try std.testing.expect(isIndexable(@TypeOf(&array))); + try std.testing.expect(isIndexable(@TypeOf(slice))); + try std.testing.expect(!isIndexable(std.meta.Child(@TypeOf(slice)))); + try std.testing.expect(isIndexable(@TypeOf(vector))); + try std.testing.expect(isIndexable(@TypeOf(tuple))); +} diff --git a/src/lib.zig b/src/lib.zig index e0f05139f7b97b1cb897b7561cb09883ebe28d8d..9e57dc4908b775a730868271bd86a3f3fb4f0d6b 100644 --- a/src/lib.zig +++ b/src/lib.zig @@ -96,3 +96,4 @@ pub usingnamespace @import("./globalOption.zig"); pub usingnamespace @import("./OneSmallerInt.zig"); pub usingnamespace @import("./FlippedInt.zig"); pub usingnamespace @import("./isZigString.zig"); +pub usingnamespace @import("./isIndexable.zig");