diff options
Diffstat (limited to 'scripts/kmd/src/util.zig')
-rw-r--r-- | scripts/kmd/src/util.zig | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/scripts/kmd/src/util.zig b/scripts/kmd/src/util.zig new file mode 100644 index 0000000..32400c8 --- /dev/null +++ b/scripts/kmd/src/util.zig @@ -0,0 +1,50 @@ +const std = @import("std"); + +// A max of 16 values. +pub fn indexOfAnyArray( + comptime T: type, + slice: []const T, + start: usize, + values: []const []const T, +) ?struct { index: usize, value: usize } { + var lowest_index: ?usize = null; + var value_index: ?usize = null; + + for (values, 0..) |v, i| { + const f = std.mem.indexOfPos(T, slice, start, v); + if (f) |f_| { + if (lowest_index == null) { + // First found: unconditionally set. + lowest_index = f_; + value_index = i; + } else { + // Check whether lower. + if (f_ < lowest_index.?) { + lowest_index = f_; + value_index = i; + } + } + } + } + if (lowest_index) |li_| { + return .{ .index = li_, .value = value_index.? }; + } else { + return null; + } +} + +test "indexOfAnyArray" { + const vals: [2][]const u8 = .{ "Gri", "Sli" }; + const wrong_vals: [2][]const u8 = .{ "Tri", "Pri" }; + const a = indexOfAnyArray(u8, "HiGriSliMi", 0, &vals); + try std.testing.expect(a.index == 2); + try std.testing.expect(a.value == 0); + + const b = indexOfAnyArray(u8, "HiGriSliMi", 3, &vals); + try std.testing.expect(b.index == 5); + try std.testing.expect(b.value == 1); + + const c = indexOfAnyArray(u8, "HiGriSliMi", 0, &wrong_vals); + try std.testing.expect(c.index == null); + try std.testing.expect(c.value == null); +} |