Zig data structures in PHP ᴾᴴᴾ - chung-leong/zigar GitHub Wiki

JavaScript | PHP


Zig is a low-level, bare-metal programming language. Data types are representated in a way that essentially reflects how the CPU sees them. For instance, a variable of the type u32 (32-bit integer) is just 4 bytes residing somewhere in the computer's memory. If it holds the value 0x01020304, those 4 bytes would be 0x04 0x03 0x02 0x01 in an Intel machine (little-endian laoutout). They would be 0x01 0x02 0x3 0x4 in a machine with a machine with a big-endian PowerPC processor.

Composite types like struct and array are likewise just a sequence of bytes. struct { x: f32, y: f32 } has 8 bytes, with x occupying the first 4 and y occupying the remainder. [12]f32, meanwhile, consumes 48 bytes of memory.

In PHP, Zig data types are represented by custom objects. Internally, each object holds a byte buffer containing the Zig binary data. When you access a struct field or an array element, custom handlers decodes the binary data and return a standard PHP value. The buffer keeps track of where its memory comes from. If it has come from PHP's memory manager, it'd be freed when the object is garbage-collected.

An object may also have a hash table, used to hold child objects.