Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CastNone trait #843

Merged
merged 5 commits into from Dec 4, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
49 changes: 49 additions & 0 deletions glib/src/object.rs
Expand Up @@ -288,6 +288,55 @@ pub trait Cast: ObjectType {

impl<T: ObjectType> Cast for T {}

// rustdoc-stripper-ignore-next
/// Convenience trait mirroring `Cast`, implemented on `Option<Object>` types.
ranfdev marked this conversation as resolved.
Show resolved Hide resolved
pub trait CastNone: Sized {
ranfdev marked this conversation as resolved.
Show resolved Hide resolved
type Inner;
fn downcast<T: ObjectType>(self) -> Result<T, Self>
sdroege marked this conversation as resolved.
Show resolved Hide resolved
bilelmoussaoui marked this conversation as resolved.
Show resolved Hide resolved
where
Self::Inner: CanDowncast<T>;
fn downcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self::Inner: CanDowncast<T>;
fn upcast<T: ObjectType>(self) -> Option<T>
where
Self::Inner: IsA<T>;
fn upcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self::Inner: IsA<T>;
ranfdev marked this conversation as resolved.
Show resolved Hide resolved
}
impl<I: ObjectType + Sized> CastNone for Option<I> {
type Inner = I;

fn downcast<T: ObjectType>(self) -> Result<T, Self>
where
Self::Inner: CanDowncast<T>,
{
self.ok_or(None)
.and_then(|i| i.downcast().map_err(|e| Some(e)))
}

fn downcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self::Inner: CanDowncast<T>,
{
self.as_ref().and_then(|i| i.downcast_ref())
}
fn upcast<T: ObjectType>(self) -> Option<T>
where
Self::Inner: IsA<T>,
{
self.map(|i| i.upcast())
}

fn upcast_ref<T: ObjectType>(&self) -> Option<&T>
where
Self::Inner: IsA<T>,
{
self.as_ref().map(|i| i.upcast_ref())
}
}

// rustdoc-stripper-ignore-next
/// Marker trait for the statically known possibility of downcasting from `Self` to `T`.
pub trait CanDowncast<T> {}
Expand Down