summaryrefslogtreecommitdiff
path: root/helpers.zig
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--helpers.zig41
1 files changed, 41 insertions, 0 deletions
diff --git a/helpers.zig b/helpers.zig
new file mode 100644
index 0000000..17a5b64
--- /dev/null
+++ b/helpers.zig
@@ -0,0 +1,41 @@
1const std = @import("std");
2
3const c = @import("c.zig").c;
4
5const Blob = @import("sqlite.zig").Blob;
6const Text = @import("sqlite.zig").Text;
7
8/// Sets the result of a function call in the context `ctx`.
9///
10/// Determines at compile time which sqlite3_result_XYZ function to use based on the type of `result`.
11pub fn setResult(ctx: ?*c.sqlite3_context, result: anytype) void {
12 const ResultType = @TypeOf(result);
13
14 switch (ResultType) {
15 Text => c.sqlite3_result_text(ctx, result.data.ptr, @intCast(c_int, result.data.len), c.SQLITE_TRANSIENT),
16 Blob => c.sqlite3_result_blob(ctx, result.data.ptr, @intCast(c_int, result.data.len), c.SQLITE_TRANSIENT),
17 else => switch (@typeInfo(ResultType)) {
18 .Int => |info| if ((info.bits + if (info.signedness == .unsigned) 1 else 0) <= 32) {
19 c.sqlite3_result_int(ctx, result);
20 } else if ((info.bits + if (info.signedness == .unsigned) 1 else 0) <= 64) {
21 c.sqlite3_result_int64(ctx, result);
22 } else {
23 @compileError("integer " ++ @typeName(ResultType) ++ " is not representable in sqlite");
24 },
25 .Float => c.sqlite3_result_double(ctx, result),
26 .Bool => c.sqlite3_result_int(ctx, if (result) 1 else 0),
27 .Array => |arr| switch (arr.child) {
28 u8 => c.sqlite3_result_blob(ctx, &result, arr.len, c.SQLITE_TRANSIENT),
29 else => @compileError("cannot use a result of type " ++ @typeName(ResultType)),
30 },
31 .Pointer => |ptr| switch (ptr.size) {
32 .Slice => switch (ptr.child) {
33 u8 => c.sqlite3_result_text(ctx, result.ptr, @intCast(c_int, result.len), c.SQLITE_TRANSIENT),
34 else => @compileError("cannot use a result of type " ++ @typeName(ResultType)),
35 },
36 else => @compileError("cannot use a result of type " ++ @typeName(ResultType)),
37 },
38 else => @compileError("cannot use a result of type " ++ @typeName(ResultType)),
39 },
40 }
41}