1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
//! Do you need trait objects, in the form `dyn MyTrait`, that implement traits
//! which are not object-safe?
//!
//! This crate solves the problem by providing object-safe traits which are
//! analogous to some commonly used traits that are not object-safe, and
//! auto-implementing both for a wide range of types. Currently, the following
//! traits are supported:
//! - Hash
//! - PartialEq
//! - Eq
//!
//! I plan to extend this support to other traits, and offer macros to simplify
//! the process for custom traits.
//!
//! Learn about object safety here:
//! https://doc.rust-lang.org/reference/items/traits.html#object-safety
//!
//! ## Example
//!
//! Let's take the `Hash` trait as an example. `Hash` is not object-safe. This
//! means that `dyn Hash` is not a valid type in rust. Now, imagine you define
//! this custom trait:
//! ```rust ignore
//! pub trait MyTrait: Hash {}
//! ```
//! Since `MyTrait` extends `Hash`, it is not object safe either, and `dyn
//! MyTrait` is not a valid type. This crate offers a way to work around this
//! limitation, so you can have object-safe traits whose objects implement
//! object-unsafe traits such as `Hash`.
//!
//! Instead of expressing `Hash` as the trait bound, express `HashObj` as the
//! trait bound.
//! ```rust ignore
//! pub trait MyTrait: HashObj {}
//! ```
//!
//! You do not need to implement `HashObj`. It is automatically implemented for
//! any type that implements `Hash`. Now, `dyn MyTrait` is object-safe. Add one
//! line of code if you want `dyn MyTrait` to implement `Hash`:
//!
//! ```rust ignore
//! impl_hash(dyn MyTrait);
//! ```
//!
//! Here are all the characteristics that come with HashObj:
//! - anything implementing `Hash` automatically implements `HashObj`
//! - `dyn HashObj` implements `Hash`.
//! - `Obj<T>` implements `Hash` for any `T` that derefs to something
//! implementing `HashObj`.
//! - `impl_hash` can implement `Hash` for any type that implements `HashObj`,
//! for example a trait object `dyn MyTrait` where `MyTrait` is a trait
//! extending `HashObj`.
//!
//! ```rust ignore
//! impl_hash! {
//! // typical use, where MyTrait: HashObj
//! dyn MyTrait,
//! dyn AnotherTrait,
//!
//! // structs and enums are supported if they deref to
//! // a target that implements HashObj or Hash.
//! MyStruct,
//!
//! // special syntax for generics.
//! MySimpleGeneric<T> where <T>,
//! MyGenericType<T, F> where <T, F: HashObj>,
//! dyn MyGenericTrait<T> where <T: SomeTraitBound>,
//!
//! // the actual impl for Obj
//! Obj<T> where <T: Deref<Target=X>, X: HashObj + ?Sized>,
//! }
//! ```
use core::{
any::Any,
hash::{Hash, Hasher},
ops::{Deref, DerefMut},
};
use std::{rc::Rc, sync::Arc};
/// Convenient wrapper struct that implements any of the traits supported by
/// this crate if the contained type derefs to something implementing the
/// `**Obj` analog trait.
#[derive(Clone, Copy, Debug)]
pub struct Obj<T>(pub T);
impl Obj<()> {
pub fn boxed<T>(item: T) -> Obj<Box<T>> {
Obj(Box::new(item))
}
pub fn rc<T>(item: T) -> Obj<Rc<T>> {
Obj(Rc::new(item))
}
pub fn arc<T>(item: T) -> Obj<Arc<T>> {
Obj(Arc::new(item))
}
}
impl<T> Deref for Obj<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for Obj<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
/// Helper trait to enable trait upcasting, since upcasting is not stable.
pub trait AsAny: Any {
fn as_any(&self) -> &dyn Any;
}
impl<T: Any> AsAny for T {
fn as_any(&self) -> &(dyn Any) {
self as &dyn Any
}
}
/// Object-safe version of Eq
pub trait EqObj: PartialEqObj {
fn as_eq_object(&self) -> &dyn EqObj;
}
impl<T> EqObj for T
where
T: Eq + PartialEqObj,
{
fn as_eq_object(&self) -> &dyn EqObj {
self
}
}
impl_eq! {
Obj<T> where <T: Deref<Target=X>, X: EqObj + ?Sized>,
dyn EqObj,
}
#[macro_export]
macro_rules! impl_eq {
($(
$Type:ty $(where <$(
$G:ident$(:
$($Gb:ident $(<$($GbIn:ident$(=$GbInEq:ty)?)+>)?)?
$(?$Gbq:ident)?
$(
+
$($Gb2:ident $(<$($GbIn2:ident$(=$GbInEq2:ty)?)+>)?)?
$(?$Gbq2:ident)?
)*
)?
),+>)?
),*$(,)?) => {$(
impl$(<$(
$G$(:
$($Gb $(<$($GbIn$(=$GbInEq)?)+>)?)?
$(?$Gbq)?
$(
+
$($Gb2 $({$($GbIn2$(=$GbInEq2:ty)?)+})?)?
$(?$Gbq2)?
)*
)?
),+>)?
Eq for $Type where $Type: 'static {})*
};
}
/// Object-safe version of PartialEq
pub trait PartialEqObj: AsAny {
fn eq_object(&self, other: &dyn PartialEqObj) -> bool;
fn as_partial_eq_object(&self) -> &dyn PartialEqObj;
}
impl<T> PartialEqObj for T
where
T: PartialEq + AsAny,
{
fn eq_object(&self, other: &dyn PartialEqObj) -> bool {
match other.as_any().downcast_ref::<Self>() {
Some(other) => self == other,
None => false,
}
}
fn as_partial_eq_object(&self) -> &dyn PartialEqObj {
self
}
}
impl_partial_eq! {
Obj<T> where <T: Deref<Target=X>, X: PartialEqObj + ?Sized>,
dyn PartialEqObj,
dyn EqObj,
}
#[macro_export]
macro_rules! impl_partial_eq {
($(
$Type:ty $(where <$(
$G:ident$(:
$($Gb:ident $(<$($GbIn:ident$(=$GbInEq:ty)?)+>)?)?
$(?$Gbq:ident)?
$(
+
$($Gb2:ident $(<$($GbIn2:ident$(=$GbInEq2:ty)?)+>)?)?
$(?$Gbq2:ident)?
)*
)?
),+>)?
),*$(,)?) => {$(
impl$(<$(
$G$(:
$($Gb $(<$($GbIn$(=$GbInEq)?)+>)?)?
$(?$Gbq)?
$(
+
$($Gb2 $({$($GbIn2$(=$GbInEq2:ty)?)+})?)?
$(?$Gbq2)?
)*
)?
),+>)?
PartialEq for $Type where $Type: 'static {
fn eq(&self, other: &Self) -> bool {
self.eq_object(other.as_partial_eq_object())
}
})*
};
}
/// Object-safe version of `std::hash::Hash`
pub trait HashObj {
fn hash_object(&self, state: &mut dyn Hasher);
fn as_hash_object(&self) -> &dyn HashObj;
}
impl<T: Hash> HashObj for T {
fn hash_object(&self, mut state: &mut dyn Hasher) {
self.hash(&mut state);
}
fn as_hash_object(&self) -> &dyn HashObj {
self
}
}
impl_hash! {
Obj<T> where <T: Deref<Target=X>, X: HashObj + ?Sized>,
dyn HashObj,
}
#[macro_export]
macro_rules! impl_hash {
($(
$Type:ty $(where <$(
$G:ident$(:
$($Gb:ident $(<$($GbIn:ident$(=$GbInEq:ty)?)+>)?)?
$(?$Gbq:ident)?
$(
+
$($Gb2:ident $(<$($GbIn2:ident$(=$GbInEq2:ty)?)+>)?)?
$(?$Gbq2:ident)?
)*
)?
),+>)?
),*$(,)?) => {$(
impl$(<$(
$G$(:
$($Gb $(<$($GbIn$(=$GbInEq)?)+>)?)?
$(?$Gbq)?
$(
+
$($Gb2 $({$($GbIn2$(=$GbInEq2:ty)?)+})?)?
$(?$Gbq2)?
)*
)?
),+>)?
std::hash::Hash for $Type {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.hash_object(state);
}
}
)*};
}
#[cfg(test)]
mod test {
use std::collections::hash_map::DefaultHasher;
use super::*;
#[test]
fn eq() {
let x: Box<dyn EqObj> = Box::new(10);
let y: Box<dyn EqObj> = Box::new(10);
let z: Box<dyn EqObj> = Box::new(11);
if x != y {
panic!("should be equal")
}
if x == z {
panic!("should not be equal")
}
}
#[test]
fn hash_works() {
let x: &str = "Hello, World!";
let y: &dyn HashObj = "Hello, World!".as_hash_object();
let z: &dyn HashObj = "banana".as_hash_object();
assert_eq!(hash(x), hash(y));
assert_ne!(hash(y), hash(z));
}
fn hash<T: Hash>(t: T) -> u64 {
let mut hasher = DefaultHasher::new();
t.hash(&mut hasher);
hasher.finish()
}
/// compiler test: hash
trait MyHash: HashObj {}
#[derive(Hash)]
struct MyHashWrapper(Obj<Box<dyn MyHash>>);
/// compiler test: partial eq
trait MyPartialEq: PartialEqObj {}
#[derive(PartialEq)]
struct MyPartialEqWrapper(Obj<Box<dyn MyPartialEq>>);
/// compiler test: eq
trait MyEq: EqObj + PartialEqObj {}
#[derive(PartialEq, Eq)]
struct MyEqWrapper(Obj<Box<dyn MyEq>>);
}
// /// TODO:
// /// - handle different method signature between declaration and definition
// /// - create impl_* macro
// /// - better syntax, find a way around square brackets
// /// - converting this to a proc macro is probably best
// ///
// /// wip! {
// /// PartialEq: AsAny {
// /// [fn eq_object(&self, other: &dyn PartialEqObject) -> bool] {
// /// match other.as_any().downcast_ref::<Self>() {
// /// Some(other) => self == other,
// /// None => false,
// /// }
// /// }
// /// }
// ///
// /// Eq: PartialEqObject {}
// /// }
// #[allow(unused)]
// macro_rules! wip {
// (
// $(
// $Trait:ty $(: $($TraitBound:ty)+)? $(where T: $($ImplBound:ty)+)?
// {$(
// [$($fn_sig:tt)*]
// $fn_impl:block
// )*}
// )*
// ) => {$(paste::paste!{
// pub trait [<$Trait Object>] $(: $($TraitBound)++)? {
// fn [<as_ $Trait:snake _object>](&self) -> &dyn [<$Trait Object>];
// $($($fn_sig)*;)*
// }
// impl<T> [<$Trait Object>] for T
// where
// T: $Trait $($(+ $TraitBound)+)?,
// {
// fn [<as_ $Trait:snake _object>](&self) -> &dyn [<$Trait Object>] {
// self
// }
// $($($fn_sig)* {$fn_impl})*
// }
// })*};
// }