From 138aa0492a1277b2d426cb02cfa881a494080180 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Sun, 2 Apr 2023 16:10:16 -0600 Subject: [PATCH] Add downcast_ref to AnyViewHandle I use unsafe code to transmute an AnyViewHandle to a ViewHandle when the type matches. Because ViewHandle is repr(transparent) to the wrapped AnyViewHandle, this is safe. --- crates/file_finder/src/file_finder.rs | 3 +-- crates/gpui/src/app.rs | 9 +++++++++ crates/workspace/src/pane.rs | 3 +-- crates/zed/src/zed.rs | 12 ++++-------- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rs index bc7e23d1ae7a3ecdc7734273a29b2d89df28c101..1160cb617447e8c9855858f0ab621ad61da725fc 100644 --- a/crates/file_finder/src/file_finder.rs +++ b/crates/file_finder/src/file_finder.rs @@ -353,8 +353,7 @@ mod tests { assert_eq!( active_item .as_any() - .clone() - .downcast::() + .downcast_ref::() .unwrap() .read(cx) .title(cx), diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs index 137a9d065361964586248587b36253c13b379544..4f14d4e9d627745a08a44df26005b78db5e0a00f 100644 --- a/crates/gpui/src/app.rs +++ b/crates/gpui/src/app.rs @@ -4661,6 +4661,7 @@ impl Clone for WeakModelHandle { impl Copy for WeakModelHandle {} +#[repr(transparent)] pub struct ViewHandle { any_handle: AnyViewHandle, view_type: PhantomData, @@ -4877,6 +4878,14 @@ impl AnyViewHandle { } } + pub fn downcast_ref(&self) -> Option<&ViewHandle> { + if self.is::() { + Some(unsafe { mem::transmute(self) }) + } else { + None + } + } + pub fn downgrade(&self) -> AnyWeakViewHandle { AnyWeakViewHandle { window_id: self.window_id, diff --git a/crates/workspace/src/pane.rs b/crates/workspace/src/pane.rs index c1b1131aac257198c8d5b8c216484dc4c5ccc1f9..572c87fcd5028719e463e9dc0ada33f036541e0d 100644 --- a/crates/workspace/src/pane.rs +++ b/crates/workspace/src/pane.rs @@ -2279,8 +2279,7 @@ mod tests { .map(|(ix, item)| { let mut state = item .as_any() - .clone() - .downcast::() + .downcast_ref::() .unwrap() .read(cx) .label diff --git a/crates/zed/src/zed.rs b/crates/zed/src/zed.rs index 9258a79d92a7864fb111443b63524dc26f09ff21..11546565a4e7f822eaddde6b7dac80ae6063df6d 100644 --- a/crates/zed/src/zed.rs +++ b/crates/zed/src/zed.rs @@ -1021,8 +1021,7 @@ mod tests { .active_item() .unwrap() .as_any() - .clone() - .downcast::() + .downcast_ref::() .unwrap() .read(cx) .title(cx), @@ -1058,8 +1057,7 @@ mod tests { .active_item() .unwrap() .as_any() - .clone() - .downcast::() + .downcast_ref::() .unwrap() .read(cx) .title(cx), @@ -1095,8 +1093,7 @@ mod tests { .active_item() .unwrap() .as_any() - .clone() - .downcast::() + .downcast_ref::() .unwrap() .read(cx) .title(cx), @@ -1146,8 +1143,7 @@ mod tests { .active_item() .unwrap() .as_any() - .clone() - .downcast::() + .downcast_ref::() .unwrap() .read(cx) .title(cx),