Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/kernel/src/wasm/posix/util.zig
1068 views
1
const std = @import("std");
2
const string = @cImport(@cInclude("string.h"));
3
4
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
5
var alloc = gpa.allocator();
6
7
// extern fn strcmp(s1: [*:0]const u8, s2: [*:0]const u8) c_int;
8
// fn eql(s1: [*:0]const u8, s2: [*:0]const u8) bool {
9
// return strcmp(s1, s2) == 0;
10
// }
11
12
const Errors = error{MemoryError};
13
14
pub fn zigStringToNullTerminatedString(s: []const u8) ![*:0]u8 {
15
var m = std.c.malloc(s.len + 1) orelse return Errors.MemoryError;
16
var ptr = @ptrCast([*]u8, m);
17
_ = string.memcpy(ptr, s.ptr, s.len);
18
ptr[s.len] = 0; // also set the null termination of the string.
19
return @ptrCast([*:0]u8, ptr);
20
}
21
22
pub fn structToJsonZigString(comptime T: type, obj: T) ![]const u8 {
23
return std.json.stringifyAlloc(alloc, obj, .{});
24
}
25
26
// Caller must free with std.c.free.
27
pub fn structToNullTerminatedJsonString(comptime T: type, obj: T) ![*:0]u8 {
28
const s = try structToJsonZigString(T, obj);
29
defer alloc.free(s);
30
return try zigStringToNullTerminatedString(s);
31
}
32
33
pub fn mallocType(comptime T: type, comptime errorMesg: [:0]const u8) ?*T {
34
var ptr = std.c.malloc(@sizeOf(T)) orelse {
35
std.debug.print("failed to allocate space for object " ++ errorMesg, .{});
36
return null;
37
};
38
return @ptrCast(*T, @alignCast(std.meta.alignment(*T), ptr));
39
}
40
41
pub fn mallocArray(comptime T: type, len: usize, comptime errorMesg: [:0]const u8) ?[*]T {
42
var ptr = std.c.malloc(@sizeOf(T) * len) orelse {
43
std.debug.print("failed to allocate space for array " ++ errorMesg, .{});
44
return null;
45
};
46
return @ptrCast([*]T, @alignCast(std.meta.alignment([*]T), ptr));
47
}
48
49
pub fn mallocString(n: usize, comptime errorMesg: [:0]const u8) ?[*]u8 {
50
return @ptrCast([*]u8, std.c.malloc(n) orelse {
51
std.debug.print("failed to allocate space for string " ++ errorMesg, .{});
52
return null;
53
});
54
}
55
56