pkg/macos: dictionary create

This commit is contained in:
Mitchell Hashimoto
2022-10-01 09:53:48 -07:00
parent d79c8fab39
commit 2440b0ec67

View File

@ -1,21 +1,35 @@
const std = @import("std"); const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const cftype = @import("type.zig"); const foundation = @import("../foundation.zig");
pub const Dictionary = opaque { pub const Dictionary = opaque {
pub fn create() Allocator.Error!*Dictionary { pub fn create(
keys: ?[]*const anyopaque,
values: ?[]*const anyopaque,
) Allocator.Error!*Dictionary {
if (keys != null or values != null) {
assert(keys != null);
assert(values != null);
assert(keys.?.len == values.?.len);
}
return CFDictionaryCreate( return CFDictionaryCreate(
null, null,
null, if (keys) |slice| slice.ptr else null,
null, if (values) |slice| slice.ptr else null,
0, if (keys) |slice| slice.len else 0,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks, &kCFTypeDictionaryValueCallBacks,
) orelse Allocator.Error.OutOfMemory; ) orelse Allocator.Error.OutOfMemory;
} }
pub fn release(self: *Dictionary) void { pub fn release(self: *Dictionary) void {
cftype.CFRelease(self); foundation.CFRelease(self);
}
pub fn getCount(self: *Dictionary) usize {
return CFDictionaryGetCount(self);
} }
pub extern "c" fn CFDictionaryCreate( pub extern "c" fn CFDictionaryCreate(
@ -26,12 +40,25 @@ pub const Dictionary = opaque {
key_callbacks: *const anyopaque, key_callbacks: *const anyopaque,
value_callbacks: *const anyopaque, value_callbacks: *const anyopaque,
) ?*Dictionary; ) ?*Dictionary;
pub extern "c" fn CFDictionaryGetCount(*Dictionary) usize;
extern "c" var kCFTypeDictionaryKeyCallBacks: anyopaque; extern "c" var kCFTypeDictionaryKeyCallBacks: anyopaque;
extern "c" var kCFTypeDictionaryValueCallBacks: anyopaque; extern "c" var kCFTypeDictionaryValueCallBacks: anyopaque;
}; };
// Just used for a test
extern "c" var kCFURLIsPurgeableKey: *const anyopaque;
test "dictionary" { test "dictionary" {
const dict = try Dictionary.create(); const testing = std.testing;
const str = try foundation.String.createWithBytes("hello", .unicode, false);
defer str.release();
var keys = [_]*const anyopaque{kCFURLIsPurgeableKey};
var values = [_]*const anyopaque{str};
const dict = try Dictionary.create(&keys, &values);
defer dict.release(); defer dict.release();
try testing.expectEqual(@as(usize, 1), dict.getCount());
} }