diff options
| author | Nic Gaffney <gaffney_nic@protonmail.com> | 2025-10-28 20:55:06 -0500 |
|---|---|---|
| committer | Nic Gaffney <gaffney_nic@protonmail.com> | 2025-10-28 20:55:06 -0500 |
| commit | 813b6631de7aa296c23e2471589d66625aa6ce15 (patch) | |
| tree | bfe69e1d47e97dfe95ff22a6e23b5b46680146f7 /src/filter.zig | |
| parent | 99c32737fe07bf7dc6094a1326be418ffd00e36f (diff) | |
| download | funcz-813b6631de7aa296c23e2471589d66625aa6ce15.tar.gz | |
Diffstat (limited to 'src/filter.zig')
| -rw-r--r-- | src/filter.zig | 32 |
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]; } |
