Path: blob/main/core/kernel/src/wasm/posix/util.zig
1068 views
const std = @import("std");1const string = @cImport(@cInclude("string.h"));23var gpa = std.heap.GeneralPurposeAllocator(.{}){};4var alloc = gpa.allocator();56// extern fn strcmp(s1: [*:0]const u8, s2: [*:0]const u8) c_int;7// fn eql(s1: [*:0]const u8, s2: [*:0]const u8) bool {8// return strcmp(s1, s2) == 0;9// }1011const Errors = error{MemoryError};1213pub fn zigStringToNullTerminatedString(s: []const u8) ![*:0]u8 {14var m = std.c.malloc(s.len + 1) orelse return Errors.MemoryError;15var ptr = @ptrCast([*]u8, m);16_ = string.memcpy(ptr, s.ptr, s.len);17ptr[s.len] = 0; // also set the null termination of the string.18return @ptrCast([*:0]u8, ptr);19}2021pub fn structToJsonZigString(comptime T: type, obj: T) ![]const u8 {22return std.json.stringifyAlloc(alloc, obj, .{});23}2425// Caller must free with std.c.free.26pub fn structToNullTerminatedJsonString(comptime T: type, obj: T) ![*:0]u8 {27const s = try structToJsonZigString(T, obj);28defer alloc.free(s);29return try zigStringToNullTerminatedString(s);30}3132pub fn mallocType(comptime T: type, comptime errorMesg: [:0]const u8) ?*T {33var ptr = std.c.malloc(@sizeOf(T)) orelse {34std.debug.print("failed to allocate space for object " ++ errorMesg, .{});35return null;36};37return @ptrCast(*T, @alignCast(std.meta.alignment(*T), ptr));38}3940pub fn mallocArray(comptime T: type, len: usize, comptime errorMesg: [:0]const u8) ?[*]T {41var ptr = std.c.malloc(@sizeOf(T) * len) orelse {42std.debug.print("failed to allocate space for array " ++ errorMesg, .{});43return null;44};45return @ptrCast([*]T, @alignCast(std.meta.alignment([*]T), ptr));46}4748pub fn mallocString(n: usize, comptime errorMesg: [:0]const u8) ?[*]u8 {49return @ptrCast([*]u8, std.c.malloc(n) orelse {50std.debug.print("failed to allocate space for string " ++ errorMesg, .{});51return null;52});53}545556