Skip to content

Commit

Permalink
Implement DerefMut for Own<Resource> in Rust component export (#647)
Browse files Browse the repository at this point in the history
  • Loading branch information
juntyr committed Aug 21, 2023
1 parent f26f5aa commit a753365
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
20 changes: 20 additions & 0 deletions crates/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,26 @@ impl InterfaceGenerator<'_> {
}}
}}
impl core::ops::DerefMut for Own{camel} {{
fn deref_mut(&mut self) -> &mut Rep{camel} {{
unsafe {{
#[cfg(target_arch = "wasm32")]
#[link(wasm_import_module = "[export]{module}")]
extern "C" {{
#[link_name = "[resource-rep]{name}"]
fn wit_import(_: i32) -> i32;
}}
#[cfg(not(target_arch = "wasm32"))]
unsafe fn wit_import(_n: i32) -> i32 {{ unreachable!() }}
::core::mem::transmute::<isize, &mut Rep{camel}>(
wit_import(self.handle).try_into().unwrap()
)
}}
}}
}}
impl Drop for Own{camel} {{
fn drop(&mut self) {{
unsafe {{
Expand Down
47 changes: 47 additions & 0 deletions crates/rust/tests/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,50 @@ mod alternative_bitflags_path {
}
}
}

mod owned_resource_deref_mut {
wit_bindgen::generate!({
inline: "
package my:inline
interface foo {
resource bar {
constructor(data: u32)
get-data: func() -> u32
consume: static func(%self: bar) -> u32
}
}
world baz {
export foo
}
",
exports: {
"my:inline/foo/bar": Resource
}
});

pub struct Resource {
data: u32,
}

impl exports::my::inline::foo::Bar for Resource {
fn new(data: u32) -> Self {
Self { data }
}

fn get_data(&self) -> u32 {
self.data
}

fn consume(mut this: exports::my::inline::foo::OwnBar) -> u32 {
// Check that Deref<Target = Self> is implemented
let prior_data: &u32 = &this.data;
let new_data = prior_data + 1;
// Check that DerefMut<Target = Self> is implemented
let mutable_data: &mut u32 = &mut this.data;
*mutable_data = new_data;
this.data
}
}
}

0 comments on commit a753365

Please sign in to comment.