diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-10-09 14:01:20 +0200 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2026-10-09 14:01:20 +0200 |
| commit | 32a251aa9645de070727a6ec91490d3e9219ec7c (patch) | |
| tree | 5dd55205c5df68fa449e766ec2a8d248e21bd2be /src/zeroscript/Env/value.zig | |
| parent | 09e8d4548361ece6151b914709c39e254eba65e3 (diff) | |
rename z framework to zeroscript
Diffstat (limited to 'src/zeroscript/Env/value.zig')
| -rw-r--r-- | src/zeroscript/Env/value.zig | 115 |
1 files changed, 115 insertions, 0 deletions
diff --git a/src/zeroscript/Env/value.zig b/src/zeroscript/Env/value.zig new file mode 100644 index 0000000..59b788f --- /dev/null +++ b/src/zeroscript/Env/value.zig @@ -0,0 +1,115 @@ +const std = @import("std"); +const Object = @import("../Object.zig"); + +pub fn isString(comptime T: type) bool { + return comptime blk: { + const info = @typeInfo(T); + if (info != .pointer) break :blk false; + + const ptr = &info.pointer; + if (ptr.is_volatile or ptr.is_allowzero) break :blk false; + + if (ptr.size == .slice) { + break :blk ptr.child == u8; + } + + if (ptr.size == .one) { + const child = @typeInfo(ptr.child); + if (child == .array) { + const arr = &child.array; + break :blk arr.child == u8; + } + } + + break :blk false; + }; +} + +pub const Value = extern struct { + kind: Kind, + value: extern union { + object: *Object, + string: extern struct { + ptr: [*]const u8, + len: usize, + }, + int: isize, + uint: usize, + float: f64, + undefined: void, + }, + + pub fn from(value: anytype) Value { + const T = @TypeOf(value); + + return switch (T) { + *Object => .{ + .kind = .object, + .value = .{ .object = value }, + }, + comptime_int => if (value >= 0) .{ + .kind = .uint, + .value = .{ .uint = value }, + } else .{ + .kind = .int, + .value = .{ .int = value }, + }, + usize => .{ + .kind = .uint, + .value = .{ .uint = value }, + }, + isize => .{ + .kind = .int, + .value = .{ .int = value }, + }, + f64, f32, f16 => .{ + .kind = .float, + .value = .{ .float = value }, + }, + void => .{ + .kind = .undefined, + .value = .{ .undefined = {} }, + }, + else => str: { + if (comptime isString(T)) { + break :str .{ + .kind = .string, + .value = .{ + .string = .{ + .ptr = @ptrCast(value), + .len = value.len, + }, + }, + }; + } else { + @compileError(std.fmt.comptimePrint( + "cannot auto convert type '{}'.", + .{T}, + )); + } + }, + }; + } + + pub const Kind = enum(u8) { + uninit = 0, + object = 1, + string = 2, + int = 3, + uint = 4, + float = 5, + undefined = 6, + + pub fn asType(comptime self: Kind) type { + return switch (self) { + .object => return *Object, + .string => return []const u8, + .int => return isize, + .uint => return usize, + .float => f64, + .undefined => return void, + .uninit => @compileError("uninit has no associated type."), + }; + } + }; +}; |