Structures in this refer to a sequence of Key/Value pairs.
Structures can be created before compile-time so that the key and value types are known beforehand. Here is an example in AssemblyScript .
class Vec3 {
x!: f32;
y!: f32;
z!: f32;
}
@global
function __TBS_Serialize<T>(input: T, out: ArrayBuffer): ArrayBuffer {
if (input instanceof Vec3) {
store<f32>(changetype<usize>(out), input.x);
store<f32>(changetype<usize>(out) + <usize>4, input.y);
store<f32>(changetype<usize>(out) + <usize>8, input.z);
return out;
}
return unreachable();
}
@global
function __TBS_Deserialize<T>(input: ArrayBuffer, out: T): T {
if (out instanceof Vec3) {
out.x = load<f32>(changetype<usize>(input));
out.y = load<f32>(changetype<usize>(input) + <usize>4);
out.z = load<f32>(changetype<usize>(input) + <usize>8);
return out;
}
return unreachable();
}
class Vec3 {
x!: f32;
y!: f32;
z!: f32;
}
const vec: Vec3 = {
x: 3,
y: 4,
z: 5
}
const serialized = serialize(vec);
console.log(serialized);
// ArrayBuffer {...}
const deserialized = deserialize(serialized);
console.log(JSON.stringify(deserialized));
// {"x":3,"y":4,"z":5}
Notice that there is no type or key information because we know it beforehand.