Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}
}