u/tindzk

▲ 12 r/rust

typex: Runtime reflection for Rust

I've published typex, a small Rust library for runtime reflection. I built it for a template language that needed to access Rust structs without serde and wanted something lighter than bevy_reflect.

It can inspect or mutate struct fields by name without knowing their concrete type. You can batch changes and undo them afterwards.

Common Rust types and collections are supported out of the box. For your own structs and enums, derive Meta for reflection and MetaMut for mutation. It works with no_std + alloc, has no runtime dependencies and uses no unsafe code.

Here's an example:

use typex::{Meta, Object};

#[derive(Meta)]
struct Counter {
  count: u8,
}

let object = Object::new(Counter { count: 3 });
assert_eq!(object.field_names(), &["count"]);

let count = object.field("count").unwrap();

println!("{}", count.type_name()); // u8
assert_eq!(count.to_ref::<u8>(), Some(&3));

To apply a batch of updates, then undo it:

use typex::{MutationBatch, PatchOperation, PathSegment};

let mut values = vec![1_u8];
let batch = MutationBatch::from([
  PatchOperation::set([PathSegment::Item(0)], 2_u8),
  PatchOperation::push_item([], 3_u8),
]);

let rollback = batch.commit(&mut values).unwrap(); // [2, 3]
rollback.undo(&mut values).unwrap();               // [1]
reddit.com
u/tindzk — 11 days ago