wasm-lang/example/_reflect

79 lines
1.7 KiB
Text
Raw Normal View History

2023-10-22 20:20:04 +00:00
// this doesn't work, not sure what to do
struct Foobar {
is_foo: bool,
number: uint,
name: string,
}
enum Value {
Null,
Bool(bool),
Integer(int),
Float(float),
String(String),
Array(Vec<Value>),
Object(Map<String, Value>),
}
fn serialize_ungeneric(f: Foobar, w: Write) {
w.write(f"{\"is_foo\":");
w.write(f.bool.to_string());
w.write(f",\"number\":");
w.write(f.number.to_string());
w.write(f",\"name\":");
w.write(f.name);
w.write(f"}");
}
fn deserialize_ungeneric(v: Value) -> Foobar {
let r = r.into();
let Value::Object(obj) = v else {
panic("wanted an object");
};
Foobar {
is_foo: obj.map.get("is_foo").unwrap().as_bool().unwrap(),
number: obj.map.get("number").unwrap().as_int().unwrap(),
name: obj.map.get("name").unwrap().as_str().unwrap(),
}
}
fn serialize<T>(data: T, w: Write) {
match std::const::typeof::<T>() {
std::const::Type::Int(i) => w.write(i.to_string()),
std::const::Type::Uint(u) => w.write(u.to_string()),
std::const::Type::Float(f) => w.write(f.to_string()),
std::const::Type::String(s) => w.write(f"\"{s}\""),
std::const::Type::Boolean(b) => w.write(b.to_string()),
std::const::Type::Vec => {
w.write("[");
for (idx, item) in data.enumerate() {
serialize(item, w);
if idx < fields.len() - 1 {
w.write(",");
}
}
w.write("]");
}
std::const::Type::Struct(fields) => {
w.write("{");
for (idx, field) in fields.enumerate() {
let f = std::const::get_field(data, field);
w.write("\"{name}\": ");
serialize(f, w);
if idx < fields.len() - 1 {
w.write(",");
}
}
w.write("}");
}
_ => todo(),
}
}
fn deserialize<T>(v: Value) -> T {
match (std::const::typeof::<T>(), v) {
(std::const::Type::Int, Value::Int(d) => d
}
}