SkylerLipthay / mini-v8

A minimal embedded V8 JavaScript engine wrapper for Rust
MIT License
106 stars 11 forks source link

Store js objects on struct #4

Closed jkelleyrtp closed 1 year ago

jkelleyrtp commented 4 years ago

Cool crate!

Curious of a thing.

If I create a function with MiniV8, then that object is bound with the 'mv8 lifetime. Awesome. But I want to compile a bunch of functions and then store them on a struct to call them at a later time.

I would like to store MiniV8 on the struct as well. But, that breaks the lifetime. MiniV8 will be valid as long as the struct is valid, so the lifetime of the functions should be tied to the struct itself. If I tie the mv8 lifetime to the struct, the struct itself falls out of scope because the reference to MiniV8 also falls out of scope.

Have you used MiniV8 like this before, and would you have any pointers for solving this?

SkylerLipthay commented 4 years ago

Thanks!

This Stack Overflow answer (and the owning_ref crate) may help you out. Alternatively you can store the functions in the mv8.global() object for later retrieval in Rust, but this is definitely less performant and you're forced to expose the functions in the global JavaScript scope. (V8 has the concept of hidden/private keys so you can set data accessible only from the host environment, but this is not yet implemented on mini_v8::Object.)

mini_v8 could be refactored so that MiniV8 internally holds a reference-counted context... This way, Function/Object/Array would not actually hold a &'mv8 MiniV8 but a Rc<MiniV8>. So lifetimes wouldn't be an issue. This would be less performant but perhaps it would be the right decision given the project's overriding purpose (to provide a simple and ergonomic interface to V8). I'll leave this issue open and readdress the question when solving #3.