rune icon indicating copy to clipboard operation
rune copied to clipboard

Make generated `Any::type_hash()` a const function?

Open pkolaczk opened this issue 2 years ago • 1 comments

My Rune script can call into the Rust host program and pass an Any object into it. I can do this:

fn do_sth_with_value(value: &Value) {
    match value {
            Value::Any(obj) => {
                let obj = obj.borrow_ref().unwrap();
                if obj.type_hash() == Uuid::type_hash() {
                    let uuid: &Uuid = obj.downcast_borrow_ref().unwrap();
                    // ...
                } else if obj.type_hash() == SomethingElse::type_hash() {
                    let sth_else: &SomethingElse = obj.downcast_borrow_ref().unwrap();
                    // ...
                } else {
                    return Err(format!("Unsupported object type: {}", value.type_info().unwrap()));
                }
            }
    //...

However if I have many different types to handle, I guess a pattern match on type_hash() would be both more readable and probably faster (I guess the compiler can generate a constant-time jump-table instead of a series of comparisons). How do I use type_hash() in a pattern match? Unfortunately I can't because they are not constants.

So I thought that maybe they could be somehow made const functions? Rune generates them in a proc-macro, so I don't think there is anything preventing their values to be known at compile time.

Or maybe there could be some official way to do dynamic dispatch by type supported by the API directly?

pkolaczk avatar Nov 07 '21 07:11 pkolaczk

This is on the roadmap (see TODO), but requires that TypeId::of becomes const stable or some other method of generating unique type identifiers in const contexts becomes available.

udoprog avatar Nov 10 '21 16:11 udoprog