Skip to content

Commit

Permalink
Add initial Id conversion traits
Browse files Browse the repository at this point in the history
  • Loading branch information
madsmtm committed Oct 15, 2021
1 parent 4955e5c commit 5ac9146
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
50 changes: 50 additions & 0 deletions objc2/src/rc/id_traits.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Various helper traits for implementing Id on foreign types / traits on Id.

use core::convert::Infallible;

use super::{Id, Owned, Ownership};
use crate::Message;

Expand Down Expand Up @@ -69,3 +71,51 @@ impl<T: DefaultId> Default for Id<T, T::Ownership> {
T::default_id()
}
}

pub trait FromId<T, O: Ownership> {
fn from_id(obj: Id<T, O>) -> Self;
}

pub trait TryFromId<T, O: Ownership>: Sized {
type Error;
fn try_from_id(obj: Id<T, O>) -> Result<Self, Self::Error>;
}

impl<T, O: Ownership, U: FromId<T, O>> TryFromId<T, O> for U {
type Error = Infallible;

fn try_from_id(obj: Id<T, O>) -> Result<Self, Self::Error> {
Ok(FromId::from_id(obj))
}
}

/// TODO.
///
/// This is similar to [`Into`] in that it is implemented automatically for
/// all [`Id`] that implement [`FromId`]; but you will have to implement this
/// yourself in many more cases!
pub trait IntoId<T, O: Ownership> {
fn into_id(self) -> Id<T, O>;
}

impl<T, O: Ownership, U> IntoId<U, O> for Id<T, O>
where
Id<U, O>: FromId<T, O>,
{
fn into_id(self) -> Id<U, O> {
FromId::from_id(self)
}
}

pub trait TryIntoId<T, O: Ownership> {
type Error;
fn try_into_id(self) -> Result<Id<T, O>, Self::Error>;
}

impl<T, O: Ownership, U: IntoId<T, O>> TryIntoId<T, O> for U {
type Error = Infallible;

fn try_into_id(self) -> Result<Id<T, O>, Self::Error> {
Ok(IntoId::into_id(self))
}
}
2 changes: 1 addition & 1 deletion objc2/src/rc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ mod weak_id;

pub use self::autorelease::{autoreleasepool, AutoreleasePool, AutoreleaseSafe};
pub use self::id::Id;
pub use self::id_traits::{DefaultId, SliceId, SliceIdMut};
pub use self::id_traits::{DefaultId, FromId, IntoId, SliceId, SliceIdMut, TryFromId, TryIntoId};
pub use self::ownership::{Owned, Ownership, Shared};
pub use self::weak_id::WeakId;

Expand Down

0 comments on commit 5ac9146

Please sign in to comment.