Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/posix-node/src/util.zig
1067 views
1
const std = @import("std");
2
const string = @cImport(@cInclude("string.h"));
3
const allocator = @import("../../interface/allocator.zig");
4
5
// extern fn strcmp(s1: [*:0]const u8, s2: [*:0]const u8) c_int;
6
// fn eql(s1: [*:0]const u8, s2: [*:0]const u8) bool {
7
// return strcmp(s1, s2) == 0;
8
// }
9
10
const Errors = error{MemoryError};
11
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
12
const alloc = gpa.allocator();
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
// here "array" and "string" are meant in the C sense, not the zig sense.
34
pub fn freeArrayOfStrings(s: [*]?[*:0]u8) void {
35
var i: usize = 0;
36
while (s[i] != null) : (i += 1) {
37
std.c.free(s[i]);
38
}
39
std.c.free(@ptrCast(*anyopaque, s));
40
}
41
42
pub fn getErrno() c_int {
43
return std.c._errno().*;
44
}
45
46
pub fn setErrno(errnoVal: c_int) void {
47
std.c._errno().* = errnoVal;
48
}
49
50
pub fn printErrno() void {
51
std.debug.print("errno = {}\n", .{getErrno()});
52
}
53
54
pub const errno = @cImport(@cInclude("errno.h"));
55
pub const constants = .{
56
.c_import = errno,
57
.names = [_][:0]const u8{ "E2BIG", "EACCES", "EBADF", "EBUSY", "ECHILD", "EDEADLK", "EEXIST", "EFAULT", "EFBIG", "EINTR", "EINVAL", "EIO", "EISDIR", "EMFILE", "EMLINK", "ENFILE", "ENODEV", "ENOENT", "ENOEXEC", "ENOMEM", "ENOSPC", "ENOTBLK", "ENOTDIR", "ENOTTY", "ENXIO", "EPERM", "EPIPE", "EROFS", "ESPIPE", "ESRCH", "ETXTBSY", "EXDEV" },
58
};
59
60