trait_cast/
trait_cast.rs

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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use core::{
  any::{Any, TypeId, type_name},
  fmt::{self, Debug, Formatter},
  ptr,
  ptr::DynMetadata,
};

#[cfg(feature = "alloc")]
use alloc::{boxed::Box, rc::Rc, sync::Arc};

/// This trait must be implemented on every concrete type for every trait that `TraitcastableAny`
/// should be able to downcast to.
///
/// This trait is not object save.
pub trait TraitcastableTo<Target: 'static + ?Sized>: TraitcastableAny {
  /// The metadata that is required to for the cast
  const METADATA: DynMetadata<Target>;
}

/// A struct representing the transformation from `dyn TraitcastableAny` to another `dyn Trait`.
///
/// This should generally not be manually used, but generated by the `make_trait_castable` attribute macro.
pub struct TraitcastTarget {
  target_type_id: TypeId,
  target_type_name: &'static str,
  /// Must point to the `DynMetadata<T>` (where T is the type in `TypeId`)
  metadata: *const (),
}
impl TraitcastTarget {
  /// Creates a new `TraitcastTarget` from a `TraitcastableTo` implementation.
  #[must_use]
  pub const fn from<Src: TraitcastableTo<Target>, Target: 'static + ?Sized>() -> Self {
    #[allow(clippy::borrow_as_ptr)] // Seems like another false positive
    Self {
      target_type_id: TypeId::of::<Target>(),
      target_type_name: type_name::<Target>(),
      metadata: ptr::from_ref::<DynMetadata<Target>>(&Src::METADATA).cast::<()>(),
    }
  }
  /// Returns the `TypeId` of the type to which can be cast with this instance.
  #[must_use]
  pub const fn target_type_id(&self) -> TypeId {
    self.target_type_id
  }
}

/// A trait marking a type as being potentially able to traitcast from `dyn TraitcastableAny` to another `dyn Trait`.
/// Use this trait instead of the `Any` trait throughout your program.
///
/// This should generally not be manually implemented, but generated by the `make_trait_castable` attribute macro.
///
/// # Safety
/// The function `traitcast_targets` must only produce valid `TraitcastTarget` (That use the metadata associated the the correct source struct).
/// The function `find_traitcast_target` must not return `Some` unless contained value has the correct target `TypeId`.
pub unsafe trait TraitcastableAny: Any {
  /// This function returns a list of all the `TraitcastTarget`'s to which a trait object can be cast, this is then used by the implementations of `TraitcastableAnyInfra` to accomplish the traitcast.
  /// The function is used to generate debug output for `TraitcastableAny`.
  /// The default implementation of `find_traitcast_target` uses this function by default.
  ///
  /// This should generally not be manually implemented, but generated by the `make_trait_castable` attribute macro.
  // Note: We dropped `'static` on the return type to better support generics.
  // > "use of generic parameter from outer function"
  fn traitcast_targets(&self) -> &[TraitcastTarget];

  /// This function can be implemented to support custom `TypeId` lookup algorithms.
  /// This may be desired when there are lots of `TraitcastTarget`s (30 or more).
  ///
  /// Possible strategies:
  /// * Unsorted `Vec<TraitcastTarget>` lookup. Hot traits first. - Used by the default implementation.
  /// * `HashMap`
  /// * Temporarily removed without replacement: ~`Vec<TraitcastTarget>` sorted by the `TypeId` and performing a binary search on it - Used if feature `const_sort` is used.~
  fn find_traitcast_target(&self, target: TypeId) -> Option<&TraitcastTarget> {
    self
      .traitcast_targets()
      .iter()
      .find(|possible| possible.target_type_id == target)
  }

  /// Returns the `TypeId` of the concrete type.
  fn type_id(&self) -> TypeId {
    Any::type_id(self)
  }
}

/// Mimics the API of `Any` but additionally allows downcasts to select trait objects.
// This helper trait was created to be able to use `min_specialization` to generate different implementations for `Sized` and `!Sized` types.
// The functions actually belong to `TraitcastableAny`.
pub trait TraitcastableAnyInfra<Target: ?Sized>: 'static {
  /// Returns true if `Target` is the exact same type as Self.
  fn is(&self) -> bool;

  /// Returns true if Self can be converted to a `Target`.
  fn can_be(&self) -> bool;

  /// Returns some reference to the inner value if it is downcastable to `Target`, or `None` if it isn’t.
  ///
  /// If `Target` is Sized this is forwarded to `Any::downcast_ref`,
  /// otherwise `TraitcastableAny::traitcast_targets` is used to determine if a traitcast is possible.
  ///
  /// Returns `None` if the concrete type of self is not `Target` and a traitcast is not possible.
  fn downcast_ref(&self) -> Option<&Target>;

  /// Unchecked variant of `downcast_ref`
  /// # Safety
  /// This function is unsafe because the caller must ensure that the cast is valid.
  #[cfg(feature = "downcast_unchecked")]
  #[doc(cfg(feature = "downcast_unchecked"))]
  unsafe fn downcast_ref_unchecked(&self) -> &Target;

  /// Returns some mutable reference to the inner value if it is downcastable to `Target`, or `None` if it isn’t.
  ///
  /// If `Target` is Sized this is forwarded to `Any::downcast_ref`,
  /// otherwise `TraitcastableAny::traitcast_targets` is used to determine if a traitcast is possible.
  ///
  /// Returns `None` if the concrete type of self is not `Target` and a traitcast is not possible.
  fn downcast_mut(&mut self) -> Option<&mut Target>;

  /// Unchecked variant of `downcast_ref`
  /// # Safety
  /// This function is unsafe because the caller must ensure that the cast is valid.
  #[cfg(feature = "downcast_unchecked")]
  #[doc(cfg(feature = "downcast_unchecked"))]
  unsafe fn downcast_mut_unchecked(&mut self) -> &mut Target;
}

// TODO: Allocator api support.

/// Extension Trait to implement over Smart Pointer Types (`Box`, `Rc`, `Arc`).
///
/// Tries to mimic the API of `Any` but additionally allows downcasts to select trait objects.
#[cfg(feature = "alloc")]
#[doc(cfg(feature = "alloc"))]
pub trait TraitcastableAnyInfraExt<Target: ?Sized + 'static>: Sized {
  /// The type that will be returned on a successful cast. Something like `Box<Target>`.
  type Output;

  /// Same as `downcast_ref` and `downcast_mut`, except that it downcasts a `Box` in place.
  ///
  /// Returns `None` if the concrete type of self is not `Target` and a traitcast is not possible.
  ///
  /// # Errors
  /// In case a cast is impossible the original input is returned as the error type.
  /// Otherwise the box would be dropped.
  fn downcast(self) -> Result<Self::Output, Self>;

  /// Unchecked variant of `downcast`
  /// # Safety
  /// This function is unsafe because the caller must ensure that the cast is valid.
  #[cfg(feature = "downcast_unchecked")]
  #[doc(cfg(feature = "downcast_unchecked"))]
  unsafe fn downcast_unchecked(self) -> Self::Output;
}

#[cfg(feature = "min_specialization")]
// Safety:
// Since `traitcast_targets` returns nothing this is always safe.
// `find_traitcast_target` has the default implementations.
unsafe impl<T: 'static> TraitcastableAny for T {
  default fn traitcast_targets(&self) -> &[TraitcastTarget] {
    &[]
  }
  default fn find_traitcast_target(&self, target: TypeId) -> Option<&TraitcastTarget> {
    // Note: copied from above
    self
      .traitcast_targets()
      .iter()
      .find(|possible| possible.target_type_id == target)
  }
}
impl Debug for dyn TraitcastableAny {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    write!(f, "TraitcastableAny to {{")?;
    for (i, target) in self.traitcast_targets().iter().enumerate() {
      if i != 0 {
        write!(f, ", ")?;
      }
      write!(f, "{}", target.target_type_name)?;
    }
    write!(f, "}}")
  }
}
macro_rules! implement_with_markers {
  ($($(+)? $traits:ident)*) => {
    impl<Target: ?Sized + 'static + $($traits +)*> TraitcastableAnyInfra<Target> for dyn TraitcastableAny $(+ $traits)* {
      default fn is(&self) -> bool {
        false
      }
      default fn can_be(&self) -> bool {
        let found_target = self.find_traitcast_target(TypeId::of::<Target>());
        found_target.is_some()
      }

      default fn downcast_ref(&self) -> Option<&Target> {
        // SAFETY:
        // The invariant of Traitcast target guarantees that the metadata points to an instance of `<Target as ::core::ptr::Pointee>::Metadata`.
        let metadata = Self::find_traitcast_target(self, TypeId::of::<Target>()).map(|target| unsafe {*(target.metadata.cast::<<Target as ::core::ptr::Pointee>::Metadata>())});

        let raw_ptr = core::ptr::from_ref::<Self>(self).to_raw_parts().0;

        metadata.map(|metadata| {
          let ret_ptr: *const Target = ptr::from_raw_parts(raw_ptr, metadata);

          // SAFETY:
          // we turned this into a raw pointer before and changed the metadata to that of a dyn Trait
          //  where the Trait must be implemented, so this must be safe!
          unsafe {&*ret_ptr}
        })
      }
      #[cfg(feature = "downcast_unchecked")]
      default unsafe fn downcast_ref_unchecked(&self) -> &Target {
        // SAFETY: The caller must ensure that the cast is valid.
        unsafe { self.downcast_ref().unwrap_unchecked() }
      }

      default fn downcast_mut(&mut self) -> Option<&mut Target> {
        // SAFETY:
        // The invariant of Traitcast target guarantees that the metadata points to an instance of `<Target as ::core::ptr::Pointee>::Metadata`.
        let metadata = Self::find_traitcast_target(self, TypeId::of::<Target>()).map(|target| unsafe {*(target.metadata.cast::<<Target as ::core::ptr::Pointee>::Metadata>())});

        let raw_ptr = core::ptr::from_mut::<Self>(self).to_raw_parts().0;

        metadata.map(|metadata| {
          let ret_ptr: *mut Target = ptr::from_raw_parts_mut(raw_ptr, metadata);

          // SAFETY:
          // we turned this into a raw pointer before and changed the metadata to that of a dyn Trait
          //  where the Trait must be implemented, so this must be safe!
          unsafe {&mut *ret_ptr}
        })

      }
      #[cfg(feature = "downcast_unchecked")]
      default unsafe fn downcast_mut_unchecked(&mut self) -> &mut Target {
        // SAFETY: The caller must ensure that the cast is valid.
        unsafe { self.downcast_mut().unwrap_unchecked() }
      }
    }
    impl<Target: Sized + 'static + $($traits +)*> TraitcastableAnyInfra<Target> for dyn TraitcastableAny $(+ $traits)* {
      fn is(&self) -> bool {
        <dyn Any>::is::<Target>(self)
      }
      fn can_be(&self) -> bool {
        <dyn TraitcastableAny as TraitcastableAnyInfra<Target>>::is(self)
      }
      fn downcast_ref(&self) -> Option<&Target> {
        <dyn Any>::downcast_ref::<Target>(self)
      }
      #[cfg(feature = "downcast_unchecked")]
      unsafe fn downcast_ref_unchecked(&self) -> &Target {
        // SAFETY: We are just forwarding the call to the `Any` trait.
        unsafe { <dyn Any>::downcast_ref_unchecked::<Target>(self) }
      }

      fn downcast_mut(&mut self) -> Option<&mut Target> {
        <dyn Any>::downcast_mut::<Target>(self)
      }
      #[cfg(feature = "downcast_unchecked")]
      unsafe fn downcast_mut_unchecked(&mut self) -> &mut Target {
        // SAFETY: We are just forwarding the call to the `Any` trait.
        unsafe { <dyn Any>::downcast_mut_unchecked::<Target>(self) }
      }
    }
  };
}

#[cfg(feature = "alloc")]
impl<Src: TraitcastableAnyInfra<Target> + ?Sized, Target: ?Sized + 'static>
  TraitcastableAnyInfraExt<Target> for Box<Src>
{
  type Output = Box<Target>;

  default fn downcast(self) -> Result<Self::Output, Self> {
    let raw = Self::into_raw(self);
    // SAFETY:
    // We can cast the *mut to a &mut since we never use the pointer directly in the success case
    //  and the reference isn't passed to the failure case.
    if let Some(to_ref) = unsafe { &mut *raw }.downcast_mut() {
      // SAFETY:
      // The pointer originates from a `Box` with the same dynamic type,
      //  since we only changed the pointer metadata.
      Ok(unsafe { Box::from_raw(to_ref) })
    } else {
      // SAFETY:
      // We reconstruct the previously destructed `Box`.
      Err(unsafe { Self::from_raw(raw) })
    }
  }
  #[cfg(feature = "downcast_unchecked")]
  default unsafe fn downcast_unchecked(self) -> Self::Output {
    // SAFETY: The caller must ensure that the cast is valid.
    unsafe { <Self as TraitcastableAnyInfraExt<Target>>::downcast(self).unwrap_unchecked() }
  }
}

#[cfg(feature = "alloc")]
impl<Src: TraitcastableAnyInfra<Target>, Target: Sized + 'static> TraitcastableAnyInfraExt<Target>
  for Box<Src>
{
  fn downcast(self) -> Result<Self::Output, Self> {
    #[cfg(feature = "downcast_unchecked")]
    if TraitcastableAnyInfra::<Target>::is(self.as_ref()) {
      // SAFETY:
      // We checked for dynamic type equality `is` in the previous if.
      unsafe { Ok(<Box<dyn Any>>::downcast_unchecked(self)) }
    } else {
      Err(self)
    }
    #[cfg(not(feature = "downcast_unchecked"))]
    if TraitcastableAnyInfra::<Target>::is(self.as_ref()) {
      Ok(<Box<dyn Any>>::downcast::<Target>(self).unwrap())
    } else {
      Err(self)
    }
  }

  #[cfg(feature = "downcast_unchecked")]
  unsafe fn downcast_unchecked(self) -> Self::Output {
    // SAFETY: The caller must ensure that the cast is valid.
    unsafe { <Box<dyn Any>>::downcast_unchecked::<Target>(self) }
  }
}

#[cfg(feature = "alloc")]
impl<Src: TraitcastableAnyInfra<Target> + ?Sized, Target: ?Sized + 'static>
  TraitcastableAnyInfraExt<Target> for Rc<Src>
{
  type Output = Rc<Target>;

  default fn downcast(self) -> Result<Self::Output, Self> {
    let raw = Self::into_raw(self);
    // SAFETY:
    // We can cast the *mut to a &mut since we never use the pointer directly in the success case
    //  and the reference isn't passed to the failure case.
    if let Some(to_ref) = unsafe { &*raw }.downcast_ref() {
      // SAFETY:
      // The pointer originates from a `Rc` with the same dynamic type,
      //  since we only changed the pointer metadata.
      Ok(unsafe { Rc::from_raw(to_ref) })
    } else {
      // SAFETY:
      // We reconstruct the previously destructed `Rc`.
      Err(unsafe { Self::from_raw(raw) })
    }
  }
  #[cfg(feature = "downcast_unchecked")]
  default unsafe fn downcast_unchecked(self) -> Self::Output {
    // SAFETY: The caller must ensure that the cast is valid.
    unsafe { <Self as TraitcastableAnyInfraExt<Target>>::downcast(self).unwrap_unchecked() }
  }
}

#[cfg(feature = "alloc")]
impl<Src: TraitcastableAnyInfra<Target>, Target: Sized + 'static> TraitcastableAnyInfraExt<Target>
  for Rc<Src>
{
  fn downcast(self) -> Result<Self::Output, Self> {
    #[cfg(feature = "downcast_unchecked")]
    if TraitcastableAnyInfra::<Target>::is(self.as_ref()) {
      // SAFETY:
      // We checked for dynamic type equality `is` in the previous if.
      unsafe { Ok(<Rc<dyn Any>>::downcast_unchecked(self)) }
    } else {
      Err(self)
    }
    #[cfg(not(feature = "downcast_unchecked"))]
    if TraitcastableAnyInfra::<Target>::is(self.as_ref()) {
      Ok(<Rc<dyn Any>>::downcast(self).unwrap())
    } else {
      Err(self)
    }
  }

  #[cfg(feature = "downcast_unchecked")]
  unsafe fn downcast_unchecked(self) -> Self::Output {
    // SAFETY: The caller must ensure that the cast is valid.
    unsafe { <Rc<dyn Any>>::downcast_unchecked::<Target>(self) }
  }
}

#[cfg(feature = "alloc")]
impl<
  Src: TraitcastableAnyInfra<Target> + ?Sized + Send + Sync,
  Target: ?Sized + 'static + Send + Sync,
> TraitcastableAnyInfraExt<Target> for Arc<Src>
{
  type Output = Arc<Target>;

  default fn downcast(self) -> Result<Self::Output, Self> {
    let raw = Self::into_raw(self);
    // SAFETY:
    // We can cast the *mut to a &mut since we never use the pointer directly in the success case
    //  and the reference isn't passed to the failure case.
    if let Some(to_ref) = unsafe { &*raw }.downcast_ref() {
      // SAFETY:
      // The pointer originates from a `Arc` with the same dynamic type,
      //  since we only changed the pointer metadata.
      Ok(unsafe { Arc::from_raw(to_ref) })
    } else {
      // SAFETY:
      // We reconstruct the previously destructed `Arc`.
      Err(unsafe { Self::from_raw(raw) })
    }
  }
  #[cfg(feature = "downcast_unchecked")]
  default unsafe fn downcast_unchecked(self) -> Self::Output {
    // SAFETY: The caller must ensure that the cast is valid.
    unsafe { <Self as TraitcastableAnyInfraExt<Target>>::downcast(self).unwrap_unchecked() }
  }
}

#[cfg(feature = "alloc")]
impl<Src: TraitcastableAnyInfra<Target> + Send + Sync, Target: Sized + 'static + Send + Sync>
  TraitcastableAnyInfraExt<Target> for Arc<Src>
{
  fn downcast(self) -> Result<Self::Output, Self> {
    #[cfg(feature = "downcast_unchecked")]
    if TraitcastableAnyInfra::<Target>::is(self.as_ref()) {
      // SAFETY:
      // We checked for dynamic type equality `is` in the previous if.
      unsafe { Ok(<Arc<dyn Any + Send + Sync>>::downcast_unchecked(self)) }
    } else {
      Err(self)
    }
    #[cfg(not(feature = "downcast_unchecked"))]
    if TraitcastableAnyInfra::<Target>::is(self.as_ref()) {
      Ok(<Arc<dyn Any + Send + Sync>>::downcast(self).unwrap())
    } else {
      Err(self)
    }
  }

  #[cfg(feature = "downcast_unchecked")]
  unsafe fn downcast_unchecked(self) -> Self::Output {
    // SAFETY: The caller must ensure that the cast is valid.
    unsafe { <Arc<dyn Any + Send + Sync>>::downcast_unchecked::<Target>(self) }
  }
}

implement_with_markers!();
implement_with_markers!(Send);
implement_with_markers!(Send + Sync);