Skip to content

Commit aa2745e

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

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-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: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,20 @@ 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) = interface.requests.iter().find(|msg| msg.typ == Some(Type::Destructor)) {
53+
// TODO split off shared code into function
54+
let method_name = format_ident!("{}{}", if is_keyword(&destructor.name) { "_" } else { "" }, destructor.name);
55+
quote! {
56+
impl super::wayland_client::ProxyDestroy for #iface_name {
57+
fn call_proxy_destructor(&self) {
58+
self.#method_name();
59+
}
60+
}
61+
}
62+
} else {
63+
quote! {}
64+
};
65+
5266
quote! {
5367
#mod_doc
5468
pub mod #mod_name {
@@ -173,6 +187,8 @@ fn generate_objects_for(interface: &Interface) -> TokenStream {
173187
}
174188
}
175189

190+
#destructor_trait_impl
191+
176192
impl #iface_name {
177193
#methods
178194
}

0 commit comments

Comments
 (0)