summaryrefslogtreecommitdiff
path: root/scripts/kmd/src/util.zig
blob: 32400c84c34451dbac8bf8e025063e314523f24a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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);
}