aboutsummaryrefslogtreecommitdiff
path: root/src/filter.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/filter.zig')
-rw-r--r--src/filter.zig32
1 files changed, 27 insertions, 5 deletions
diff --git a/src/filter.zig b/src/filter.zig
index b9e2167..2395dda 100644
--- a/src/filter.zig
+++ b/src/filter.zig
@@ -7,16 +7,38 @@ const typeVerify = @import("util.zig").typeVerify;
/// Filters a slice, only keeping items give `true` when passed into `func`
/// Type signature: `(a -> bool) -> [a] -> [a]`
/// `func` is of type `a -> bool`, where `items` is of type `[a]`
-pub fn filter(
+pub fn filterAlloc(
+ allocator: std.mem.Allocator,
func: anytype,
items: []typeVerify(@TypeOf(func), .{ .@"fn" }).@"fn".params[0].type.?,
-) []typeVerify(@TypeOf(func), .{ .@"fn" }).@"fn".params[0].type.? {
- var output = items;
+) ![]typeVerify(@TypeOf(func), .{ .@"fn" }).@"fn".params[0].type.? {
+ var tmp = items;
var i: u32 = 0;
for (items) |it|
if (func(it)) {
- output[i] = it;
+ tmp[i] = it;
i = i + 1;
};
- return output[0..i];
+
+ const output = try allocator.alloc(typeVerify(@TypeOf(func), .{ .@"fn" }).@"fn".params[0].type.?, i);
+ for (0..i) |j|
+ output[j] = tmp[i];
+ return output;
+}
+
+pub fn filterBuff(
+ func: anytype,
+ items: []typeVerify(@TypeOf(func), .{ .@"fn" }).@"fn".params[0].type.?,
+ buffer: *[]typeVerify(@TypeOf(func), .{ .@"fn" }).@"fn".params[0].type.?,
+) void {
+ var tmp = items;
+ var i: u32 = 0;
+ for (items) |it|
+ if (func(it)) {
+ tmp[i] = it;
+ i = i + 1;
+ };
+
+ for (0..i) |j|
+ buffer[j] = tmp[i];
}