Stream: wasmtime

Topic: Owned vs Borrowed resources on the host


view this post on Zulip Karel Hrkal (kajacx) (May 09 2024 at 19:03):

Ok, I've tried to work with both owned and borrowed resources, here is my (simplified) wit file:

Wit file

But work with the "Company" resource on the host is kind of strange. First, there is no distinction between owned and borrowed resource at the type level, so you can accidentally pass a borrowed resource where an owned one is expected or vise versa.

And second, I'm not sure if I know how to create a borrowed resource, I am using Resource::new_borrow(company.rep()) which works, but it looks kind of hacky.

I would expect that the OwnedResource type would have a borrow method (or borrow_resource if you don't want to confuse it with the Borrow trait) that would return a BorrowedResource. You can even use Rust's lifetime checking to make sure that the borrowed resource does not outlive the owned resource with a signature like this:

impl<T> OwnedResource<T> {
    // the 'a lifetime is added here for explicitly
    pub fn borrow_resource<'a>(&'a self) -> BorrowedResource<'a, T> { ... }
}

This feels like the most idiomatic solution in Rust, as it would make sure that you are not passing a borrowed resource into a method that wants a owned one (or vice versa) nor that the borrowed resource will be used after the owned resource is deleted.

There is one last thing - dropping the Resource<T> on the host does not delete the resource from the resource table, which is kind of strange, it definitely feels like it should delete the resource, but I don't know if that is feasible since the user is expected to manage the resources themself.

Edit:

This is my host file, there is just a little bit more going on than in the simplified wit file

host file


Last updated: Nov 22 2024 at 16:03 UTC