Skip to content

Commit f39377d

Browse files
committed
Implement upcasting using a similar mechanism to AsAny
1 parent be8bb91 commit f39377d

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

winit-core/src/window.rs

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -819,7 +819,7 @@ impl rwh_06::HasWindowHandle for dyn Surface + '_ {
819819
///
820820
/// **Web:** The [`Window`], which is represented by a `HTMLElementCanvas`, can
821821
/// not be closed by dropping the [`Window`].
822-
pub trait Window: Surface {
822+
pub trait Window: AsSurface {
823823
/// Reset the dead key state of the keyboard.
824824
///
825825
/// This is useful when a dead key is bound to trigger an action. Then
@@ -1971,18 +1971,65 @@ mod tests {
19711971
.is_some());
19721972
}
19731973
}
1974+
// Implementation trait to allow upcasting to [`Surface`].
1975+
// This trait can be safely removed once MSRV hits Rust 1.86, similar to `AsAny`.
1976+
#[doc(hidden)]
1977+
pub trait AsSurface: Surface {
1978+
#[doc(hidden)]
1979+
fn __as_surface(&self) -> &dyn Surface;
1980+
#[doc(hidden)]
1981+
fn __as_surface_mut(&mut self) -> &mut dyn Surface;
1982+
#[doc(hidden)]
1983+
fn __into_surface(self: Box<Self>) -> Box<dyn Surface>;
1984+
}
1985+
1986+
impl<T: Surface> AsSurface for T {
1987+
fn __as_surface(&self) -> &dyn Surface {
1988+
self
1989+
}
1990+
1991+
fn __as_surface_mut(&mut self) -> &mut dyn Surface {
1992+
self
1993+
}
1994+
1995+
fn __into_surface(self: Box<Self>) -> Box<dyn Surface> {
1996+
self
1997+
}
1998+
}
1999+
19742000
/// Dynamic reference to one of the common surface traits.
2001+
#[non_exhaustive]
19752002
pub enum SurfaceDowncastRef<'a> {
19762003
/// A toplevel window, see [`Window`] for details.
19772004
Window(&'a dyn Window),
19782005
}
19792006

2007+
impl SurfaceDowncastRef<'_> {
2008+
/// Tries to cast this reference into a [`Window`].
2009+
pub fn as_window(&self) -> Option<&'_ dyn Window> {
2010+
match self {
2011+
Self::Window(window) => Some(*window),
2012+
_ => None,
2013+
}
2014+
}
2015+
}
2016+
19802017
/// Dynamic mutable reference to one of the common surface traits.
19812018
pub enum SurfaceDowncastMut<'a> {
19822019
/// A toplevel window, see [`Window`] for details.
19832020
Window(&'a mut dyn Window),
19842021
}
19852022

2023+
impl SurfaceDowncastMut<'_> {
2024+
/// Tries to cast this reference into a [`Window`].
2025+
pub fn as_window(&mut self) -> Option<&'_ mut dyn Window> {
2026+
match self {
2027+
Self::Window(window) => Some(*window),
2028+
_ => None,
2029+
}
2030+
}
2031+
}
2032+
19862033
/// Helper macro for implementing [`Surface::try_downcast`] and [`Surface::try_downcast_mut`].
19872034
/// ## Syntax
19882035
/// Use the names of variants of [`SurfaceDowncastRef`] or [`SurfaceDowncastMut`] to return that type:

0 commit comments

Comments
 (0)