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
|
// SPDX-FileCopyrightText: 2024 Himbeer <himbeer@disroot.org>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
pub fn Filter(comptime T: type, comptime U: type) type {
return struct {
pub const Predicate = *const fn (T, U) bool;
buffer: []const T,
index: ?usize,
predicate: Predicate,
matcher: U,
const Self = @This();
pub fn new(buffer: []const T, predicate: Predicate, matcher: U) Self {
return .{
.buffer = buffer,
.index = 0,
.predicate = predicate,
.matcher = matcher,
};
}
pub fn next(self: *Self) ?T {
const start = self.index orelse return null;
const index = for (self.buffer[start..], 0..) |elem, skipped| {
if (self.predicate(elem, self.matcher)) {
break start + skipped;
}
} else null;
if (index) |i| {
self.index = if (1 + i < self.buffer.len) 1 + i else null;
return self.buffer[i];
}
self.index = null;
return null;
}
pub fn reset(self: *Self) void {
self.index = 0;
}
};
}
|