lib/choir/src/backends/artifact/model/slice.zig
daab053ee43316e1809a84551d573ddd1e5bf3d2
1 const std = @import("std");
2
3 pub const Error = std.mem.Allocator.Error;
4
5 pub fn dupeOptional(allocator: std.mem.Allocator, value: ?[]const u8) Error!?[]const u8 {
6 return if (value) |actual| try dupe(allocator, actual) else null;
7 }
8
9 pub fn freeOptional(allocator: std.mem.Allocator, value: ?[]const u8) void {
10 if (value) |actual| free(allocator, actual);
11 }
12
13 pub fn dupe(allocator: std.mem.Allocator, value: []const u8) Error![]const u8 {
14 return try allocator.dupe(u8, value);
15 }
16
17 pub fn free(allocator: std.mem.Allocator, value: []const u8) void {
18 allocator.free(@constCast(value));
19 }
20
21 pub fn dupeList(allocator: std.mem.Allocator, values: []const []const u8) Error![]const []const u8 {
22 if (values.len == 0) return &.{};
23
24 const out = try allocator.alloc([]const u8, values.len);
25 var filled: usize = 0;
26 errdefer {
27 for (out[0..filled]) |item| free(allocator, item);
28 allocator.free(out);
29 }
30
31 for (values, 0..) |value, index| {
32 out[index] = try dupe(allocator, value);
33 filled += 1;
34 }
35 return out;
36 }
37
38 pub fn freeList(allocator: std.mem.Allocator, values: []const []const u8) void {
39 for (values) |value| free(allocator, value);
40 if (values.len > 0) allocator.free(@constCast(values));
41 }
42
43 pub fn optionalEqual(left: ?[]const u8, right: ?[]const u8) bool {
44 if (left == null or right == null) return left == null and right == null;
45 return std.mem.eql(u8, left.?, right.?);
46 }