65 lines
1.9 KiB
Plaintext
65 lines
1.9 KiB
Plaintext
import t, c
|
|
from stdint import *
|
|
|
|
# Variant type tags (fixed enumeration + custom pointer type)
|
|
VARIANT_NONE: t.CDefine = 0 # Untyped / null value
|
|
VARIANT_INT: t.CDefine = 1 # int (i64)
|
|
VARIANT_FLOAT: t.CDefine = 2 # float (f32)
|
|
VARIANT_DOUBLE: t.CDefine = 3 # double (f64)
|
|
VARIANT_STR: t.CDefine = 4 # str (i8*)
|
|
VARIANT_DICT: t.CDefine = 5 # dict*
|
|
VARIANT_LIST: t.CDefine = 6 # list*
|
|
VARIANT_BOOL: t.CDefine = 7 # bool (i1/i32)
|
|
VARIANT_PTR: t.CDefine = 8 # Custom pointer type
|
|
|
|
|
|
class Variant:
|
|
"""Generic variant type storing a type tag and untyped pointer.
|
|
Used for universal object storage inside dict/list, supports nesting and JSON serialization.
|
|
|
|
Usage:
|
|
v: Variant = Variant(VARIANT_INT, t.CNeedPtr(42))
|
|
v2: Variant = Variant(VARIANT_STR, t.CNeedPtr("hello"))
|
|
|
|
# Retrieve value
|
|
ptr: t.CPtr = v.ptr
|
|
i: int = c.Deref(ptr)
|
|
"""
|
|
vtype: int
|
|
ptr: t.CPtr
|
|
|
|
def __init__(self, vtype: int, val: t.CNeedPtr):
|
|
"""Construct Variant instance.
|
|
t.CNeedPtr automatically obtains address of val (non-pointer values will be allocated on stack and stored).
|
|
Note: The lifecycle of val is managed by the caller; Variant only stores a pointer reference.
|
|
"""
|
|
self.vtype = vtype
|
|
self.ptr = val
|
|
|
|
def is_none(self) -> int:
|
|
return self.vtype == VARIANT_NONE
|
|
|
|
def is_int(self) -> int:
|
|
return self.vtype == VARIANT_INT
|
|
|
|
def is_float(self) -> int:
|
|
return self.vtype == VARIANT_FLOAT
|
|
|
|
def is_double(self) -> int:
|
|
return self.vtype == VARIANT_DOUBLE
|
|
|
|
def is_str(self) -> int:
|
|
return self.vtype == VARIANT_STR
|
|
|
|
def is_dict(self) -> int:
|
|
return self.vtype == VARIANT_DICT
|
|
|
|
def is_list(self) -> int:
|
|
return self.vtype == VARIANT_LIST
|
|
|
|
def is_bool(self) -> int:
|
|
return self.vtype == VARIANT_BOOL
|
|
|
|
def is_ptr(self) -> int:
|
|
return self.vtype == VARIANT_PTR
|