wasm-lang/example/reflect

45 lines
1.2 KiB
Text
Raw Normal View History

2023-10-22 20:20:04 +00:00
// this version uses types as values
// every version i tried to make feels oddly hacky, unsure what to do
fn serialize(data: Any, w: Write) {
match std::const::type_info(std::const::type_of(data)) {
.int => w.write(data.to_string()),
.float => w.write(data.to_string()),
.bool => w.write(data.to_string()),
.enum => todo(),
.struct(s) => {
w.write("{");
for field in s.fields {
let d = std::const::get_struct_field(s, field.name);
w.write(f"\"{field.name}\":{d}");
}
w.write("}");
}
_ => todo(),
}
}
fn deserialize(into: type, json: Value) -> into {
match (std::const::type_info(into), json) {
(.int, .int(i)) => i,
(.float, .float(f)) => f,
(.bool, .bool(b)) => b,
(.struct(s), .map(m)) => {
let s = std::mem::uninit(into);
for field in s.fields {
s.set_field(field.name, m.get(field.name).expect("missing field!")).expect("wrong type!");
}
unsafe { s.assume_init() }
},
(_, _) => todo(),
// (_, _) => panic("expected {into} but got {json.type_name()}"),
}
}
// in std
mod const {
pub const fn type_of(data: Any) -> type;
pub const fn type_info(ty: type) -> TypeInfo;
pub const fn get_struct_field(data: struct, name: String) -> /* type of data.name */;
}