| ... | ... | @@ -1013,6 +1013,54 @@ pub fn indexOfAnyPos(comptime T: type, slice: []const T, start_index: usize, val |
| 1013 | 1013 | return null; |
| 1014 | 1014 | } |
| 1015 | 1015 | |
| 1016 | /// Find the first item in `slice` which is not contained in `values`. |
| 1017 | /// |
| 1018 | /// Comparable to `strspn` in the C standard library. |
| 1019 | pub fn indexOfNone(comptime T: type, slice: []const T, values: []const T) ?usize { |
| 1020 | return indexOfNonePos(T, slice, 0, values); |
| 1021 | } |
| 1022 | |
| 1023 | /// Find the last item in `slice` which is not contained in `values`. |
| 1024 | /// |
| 1025 | /// Like `strspn` in the C standard library, but searches from the end. |
| 1026 | pub fn lastIndexOfNone(comptime T: type, slice: []const T, values: []const T) ?usize { |
| 1027 | var i: usize = slice.len; |
| 1028 | outer: while (i != 0) { |
| 1029 | i -= 1; |
| 1030 | for (values) |value| { |
| 1031 | if (slice[i] == value) continue :outer; |
| 1032 | } |
| 1033 | return i; |
| 1034 | } |
| 1035 | return null; |
| 1036 | } |
| 1037 | |
| 1038 | /// Find the first item in `slice[start_index..]` which is not contained in `values`. |
| 1039 | /// The returned index will be relative to the start of `slice`, and never less than `start_index`. |
| 1040 | /// |
| 1041 | /// Comparable to `strspn` in the C standard library. |
| 1042 | pub fn indexOfNonePos(comptime T: type, slice: []const T, start_index: usize, values: []const T) ?usize { |
| 1043 | var i: usize = start_index; |
| 1044 | outer: while (i < slice.len) : (i += 1) { |
| 1045 | for (values) |value| { |
| 1046 | if (slice[i] == value) continue :outer; |
| 1047 | } |
| 1048 | return i; |
| 1049 | } |
| 1050 | return null; |
| 1051 | } |
| 1052 | |
| 1053 | test "indexOfNone" { |
| 1054 | try testing.expect(indexOfNone(u8, "abc123", "123").? == 0); |
| 1055 | try testing.expect(lastIndexOfNone(u8, "abc123", "123").? == 2); |
| 1056 | try testing.expect(indexOfNone(u8, "123abc", "123").? == 3); |
| 1057 | try testing.expect(lastIndexOfNone(u8, "123abc", "123").? == 5); |
| 1058 | try testing.expect(indexOfNone(u8, "123123", "123") == null); |
| 1059 | try testing.expect(indexOfNone(u8, "333333", "123") == null); |
| 1060 | |
| 1061 | try testing.expect(indexOfNonePos(u8, "abc123", 3, "321") == null); |
| 1062 | } |
| 1063 | |
| 1016 | 1064 | pub fn indexOf(comptime T: type, haystack: []const T, needle: []const T) ?usize { |
| 1017 | 1065 | return indexOfPos(T, haystack, 0, needle); |
| 1018 | 1066 | } |