Skip to content

Commit c04dbec

Browse files
committed
client: Add a DestroyOnDrop wrapper that calls destructor on Drop
1 parent 6642661 commit c04dbec

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

wayland-client/src/lib.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,31 @@ pub trait Proxy: Clone + std::fmt::Debug + Sized {
321321
}
322322
}
323323

324+
/// Trait for instances of [`Proxy`] that have destructors
325+
pub trait ProxyDestroy: Proxy {
326+
/// Sends the destructor request to the proxy, which is usually called `.destroy()`
327+
fn call_proxy_destructor(&self);
328+
}
329+
330+
/// Wrap a [`ProxyDestroy`] instance to automatically call the destructor on
331+
/// drop.
332+
#[derive(Debug, Eq, PartialEq, Hash)]
333+
pub struct DestroyOnDrop<T: ProxyDestroy>(T);
334+
335+
impl<T: ProxyDestroy> Drop for DestroyOnDrop<T> {
336+
fn drop(&mut self) {
337+
self.0.call_proxy_destructor();
338+
}
339+
}
340+
341+
impl<T: ProxyDestroy> std::ops::Deref for DestroyOnDrop<T> {
342+
type Target = T;
343+
344+
fn deref(&self) -> &T {
345+
&self.0
346+
}
347+
}
348+
324349
/// Wayland dispatching error
325350
#[derive(Debug)]
326351
pub enum DispatchError {

wayland-scanner/src/client_gen.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,26 @@ fn generate_objects_for(interface: &Interface) -> TokenStream {
4949
};
5050
let doc_attr = to_doc_attr(&docs);
5151

52+
let destructor_trait_impl = if let Some(destructor) =
53+
interface.requests.iter().find(|msg| msg.typ == Some(Type::Destructor))
54+
{
55+
// TODO split off shared code into function
56+
let method_name = format_ident!(
57+
"{}{}",
58+
if is_keyword(&destructor.name) { "_" } else { "" },
59+
destructor.name
60+
);
61+
quote! {
62+
impl super::wayland_client::ProxyDestroy for #iface_name {
63+
fn call_proxy_destructor(&self) {
64+
self.#method_name();
65+
}
66+
}
67+
}
68+
} else {
69+
quote! {}
70+
};
71+
5272
quote! {
5373
#mod_doc
5474
pub mod #mod_name {
@@ -173,6 +193,8 @@ fn generate_objects_for(interface: &Interface) -> TokenStream {
173193
}
174194
}
175195

196+
#destructor_trait_impl
197+
176198
impl #iface_name {
177199
#methods
178200
}

0 commit comments

Comments
 (0)