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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
use super::*;
    
use std::{
    fmt,
    ops::{Deref,DerefMut},
};

#[allow(unused_imports)]
use core_extensions::SelfOps;

use crate::{
    abi_stability::SharedStableAbi,
    erased_types::{
        c_functions::adapt_std_fmt,
        InterfaceBound,
    },
    sabi_types::{MaybeCmp,RRef},
    std_types::UTypeId,
    pointer_trait::{
        CanTransmuteElement,TransmuteElement,
        GetPointerKind,PK_SmartPointer,PK_Reference,PointerKind,
    },
    type_level::{
        impl_enum::{Implemented,Unimplemented},
        trait_marker,
    },
    utils::{transmute_reference,transmute_mut_reference},
};


/**
`RObject` implements ffi-safe trait objects,for a minimal selection of traits.

The main use of `RObject<_>` is as the default backend for `#[sabi_trait]` 
generated trait objects.

# Construction

To construct an `RObject<_>` directly (not as part of a trait object) 
you can call one of these methods:

- from_ptr
    Can be constructed from a pointer of a value.Cannot unerase the RObject afterwards.

- from_ptr_unerasable:
    Can be constructed from a pointer of a value.Requires a `'static` value.

- from_value:
    Can be constructed from the value directly.Cannot unerase the RObject afterwards.

- from_value_unerasable
    Can be constructed from the value directly.Requires a `'static` value.

# Trait object

`RObject<'borrow,Pointer<()>,Interface,VTable>` 
can be used as a trait object for any combination of 
the traits listed bellow.

These are the traits:

- Send

- Sync

- Debug

- Clone

# Deconstruction

`RObject<_>` can then be unwrapped into a concrete type,
within the same dynamic library/executable that constructed it,
using these (fallible) conversion methods:

- into_unerased:Unwraps into a pointer to `T`.Requires `T:'static`.

- as_unerased:Unwraps into a `&T`.Requires `T:'static`.

- as_unerased_mut:Unwraps into a `&mut T`.Requires `T:'static`.

`RObject` can only be converted back if it was created 
using a `RObject::*_unerased` function.


*/
#[repr(C)]
#[derive(StableAbi)]
#[sabi(
    not_stableabi(V),
    bound="V:SharedStableAbi",
    bound="I:InterfaceBound",
    extra_checks="<I as InterfaceBound>::EXTRA_CHECKS",
)]
pub struct RObject<'lt,P,I,V>
where
    P:GetPointerKind
{
    vtable:StaticRef<V>,
    ptr: ManuallyDrop<P>,
    _marker:PhantomData<Tuple2<&'lt (),I>>,
}

mod clone_impl{
    pub trait CloneImpl<PtrKind>{
        fn clone_impl(&self) -> Self;
    }
}
use self::clone_impl::CloneImpl;


/// This impl is for smart pointers.
impl<'lt,P, I,V> CloneImpl<PK_SmartPointer> for RObject<'lt,P,I,V>
where
    P: Deref+GetPointerKind,
    I: InterfaceType<Clone = Implemented<trait_marker::Clone>>,
{
    fn clone_impl(&self) -> Self {
        let ptr=unsafe{
            self.sabi_robject_vtable()._sabi_clone().unwrap()(&self.ptr)
        };
        Self{
            vtable:self.vtable,
            ptr:ManuallyDrop::new(ptr),
            _marker:PhantomData,
        }
    }
}

/// This impl is for references.
impl<'lt,P, I,V> CloneImpl<PK_Reference> for RObject<'lt,P,I,V>
where
    P: Deref+Copy+GetPointerKind,
    I: InterfaceType,
{
    fn clone_impl(&self) -> Self {
        Self{
            vtable:self.vtable,
            ptr:ManuallyDrop::new(*self.ptr),
            _marker:PhantomData,
        }
    }
}

/**
Clone is implemented for references and smart pointers,
using `GetPointerKind` to decide whether `P` is a smart pointer or a reference.

RObject does not implement Clone if P==`&mut ()` :


```compile_fail
use abi_stable::{
    sabi_trait::{
        doc_examples::ConstExample_TO,
        TU_Opaque,
    },
    std_types::*,
};

let mut object=ConstExample_TO::from_value(10usize,TU_Opaque);
let borrow=object.sabi_reborrow_mut();
let _=borrow.clone();
```

Here is the same example with `sabi_reborrow`

```
use abi_stable::{
    sabi_trait::{
        doc_examples::ConstExample_TO,
        TU_Opaque,
    },
    std_types::*,
};

let mut object=ConstExample_TO::from_value(10usize,TU_Opaque);
let borrow=object.sabi_reborrow();
let _=borrow.clone();
```


*/
impl<'lt,P, I,V> Clone for RObject<'lt,P,I,V>
where
    P: Deref+GetPointerKind,
    I: InterfaceType,
    Self:CloneImpl<<P as GetPointerKind>::Kind>,
{
    fn clone(&self) -> Self {
        self.clone_impl()
    }
}


impl<'lt,P,I,V> Debug for RObject<'lt,P,I,V> 
where
    P: Deref<Target=()>+GetPointerKind,
    I: InterfaceType<Debug = Implemented<trait_marker::Debug>>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        unsafe{
            adapt_std_fmt::<ErasedObject>(
                self.sabi_erased_ref(), 
                self.sabi_robject_vtable()._sabi_debug().unwrap(), 
                f
            )
        }
    }
}


impl<'lt,P,I,V> Display for RObject<'lt,P,I,V> 
where
    P: Deref<Target=()>+GetPointerKind,
    I: InterfaceType<Display = Implemented<trait_marker::Display>>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        unsafe{
            adapt_std_fmt::<ErasedObject>(
                self.sabi_erased_ref(), 
                self.sabi_robject_vtable()._sabi_display().unwrap(), 
                f
            )
        }
    }
}

impl<'lt,P, I,V> std::error::Error for RObject<'lt,P,I,V>
where
    P: Deref<Target=()>+GetPointerKind,
    I: InterfaceBound<
        Display=Implemented<trait_marker::Display>,
        Debug=Implemented<trait_marker::Debug>,
        Error=Implemented<trait_marker::Error>,
    >,
{}



unsafe impl<'lt,P,I,V> Send for RObject<'lt,P,I,V> 
where 
    P:GetPointerKind,
    I:InterfaceType<Send = Implemented<trait_marker::Send>>,
{}

unsafe impl<'lt,P,I,V> Sync for RObject<'lt,P,I,V> 
where
    P:GetPointerKind,
    I:InterfaceType<Sync = Implemented<trait_marker::Sync>>,
{}


impl<'lt,P,I,V> RObject<'lt,P,I,V>
where
    P:GetPointerKind<Target=()>,
{
/**

Constructs an RObject from a pointer and an extra vtable.

This is mostly intended to be called by `#[sabi_trait]` generated trait objects.

# Safety

These are the requirements for the caller:

- `P` must be a pointer to the type that the vtable functions 
    take as the first parameter.

- The vtable must not come from a reborrowed RObject
    (created using RObject::reborrow or RObject::reborrow_mut).

- The vtable must be the `<SomeVTableName>` of a struct declared with 
    `#[derive(StableAbi)]``#[sabi(kind(Prefix(prefix_struct="<SomeVTableName>")))]`.

- The vtable must have `StaticRef<RObjectVtable<..>>` 
    as its first declared field

*/
    pub unsafe fn with_vtable<OrigPtr>(
        ptr:OrigPtr,
        vtable:StaticRef<V>,
    )-> RObject<'lt,P,I,V>
    where 
        OrigPtr:CanTransmuteElement<(),TransmutedPtr=P>,
        OrigPtr::Target:Sized+'lt,
        P:Deref<Target=()>,
    {
        RObject{
            vtable,
            ptr:ManuallyDrop::new( ptr.transmute_element::<()>() ),
            _marker:PhantomData,
        }
    }
}


impl<'borr,'a,I,V> RObject<'borr,RRef<'a,()>,I,V>{

/**
This function allows constructing an RObject in a constant/static.

This is mostly intended for `#[sabi_trait] generated trait objects`

# Safety

This has the same safety requirements as `RObject::with_vtable`

# Example

Because this is intended for `#[sabi_trait]` generated trait objects,
this demonstrates how to construct one in a constant.

```
use abi_stable::sabi_trait::{
    doc_examples::{ConstExample_CTO,ConstExample_MV},
    prelude::TU_Opaque,
};

const EXAMPLE0:ConstExample_CTO<'static,'static>=
    ConstExample_CTO::from_const(
        &0usize,
        TU_Opaque,
        ConstExample_MV::VTABLE,
    );


```


*/
    pub const unsafe fn with_vtable_const<T,Unerasability>(
        ptr: &'a T,
        vtable:VTableTO_RO<T,RRef<'a,T>,Unerasability,V>,
    )-> Self
    where
        T:'borr,
    {
        RObject{
            vtable: vtable.robject_vtable(),
            ptr:{
                let x=RRef::new(ptr).transmute_ref::<()>();
                ManuallyDrop::new(x)
            },
            _marker:PhantomData,
        }
    }
}


impl<'lt,P,I,V> RObject<'lt,P,I,V>
where
    P:GetPointerKind,
{
    /// The uid in the vtable has to be the same as the one for T,
    /// otherwise it was not created from that T in the library that 
    /// declared the trait object.
    fn sabi_check_same_utypeid<T>(&self) -> Result<(), UneraseError<()>>
    where
        T:'static,
    {
        let expected_typeid=self.sabi_robject_vtable()._sabi_type_id().get();
        let actual_typeid=UTypeId::new::<T>();
        if expected_typeid == MaybeCmp::Just(actual_typeid) {
            Ok(())
        } else {
            Err(UneraseError {
                robject:(),
                expected_typeid,
                actual_typeid,
            })
        }
    }

    /// Attempts to unerase this trait object into the pointer it was constructed with.
    ///
    /// # Errors
    ///
    /// This will return an error in any of these conditions:
    ///
    /// - It is called in a dynamic library/binary outside
    /// the one from which this RObject was constructed.
    ///
    /// - The RObject was constructed using the `from_(value|ptr)` method
    ///
    /// - `T` is not the concrete type this `RObject<_>` was constructed with.
    ///
    pub fn into_unerased<T>(self) -> Result<P::TransmutedPtr, UneraseError<Self>>
    where
        T:'static,
        P: Deref<Target=()>+CanTransmuteElement<T>,
    {
        check_unerased!(self,self.sabi_check_same_utypeid::<T>());
        unsafe {
            let this=ManuallyDrop::new(self);
            Ok(ptr::read(&*this.ptr).transmute_element::<T>()) 
        }
    }

    /// Attempts to unerase this trait object into a reference of 
    /// the value was constructed with.
    ///
    /// # Errors
    ///
    /// This will return an error in any of these conditions:
    ///
    /// - It is called in a dynamic library/binary outside
    /// the one from which this RObject was constructed.
    ///
    /// - The RObject was constructed using the `from_(value|ptr)` method
    ///
    /// - `T` is not the concrete type this `RObject<_>` was constructed with.
    ///
    pub fn as_unerased<T>(&self) -> Result<&T, UneraseError<&Self>>
    where
        T:'static,
        P:Deref<Target=()>+CanTransmuteElement<T>,
    {
        check_unerased!(self,self.sabi_check_same_utypeid::<T>());
        unsafe { 
            Ok(transmute_reference::<(),T>(&**self.ptr))
        }
    }

    /// Attempts to unerase this trait object into a mutable reference of 
    /// the value was constructed with.
    ///
    /// # Errors
    ///
    /// This will return an error in any of these conditions:
    ///
    /// - It is called in a dynamic library/binary outside
    /// the one from which this RObject was constructed.
    ///
    /// - The RObject was constructed using the `frfrom_(value|ptr)_*` method
    ///
    /// - `T` is not the concrete type this `RObject<_>` was constructed with.
    ///
    pub fn as_unerased_mut<T>(&mut self) -> Result<&mut T, UneraseError<&mut Self>>
    where
        T:'static,
        P:DerefMut<Target=()>+CanTransmuteElement<T>,
    {
        check_unerased!(self,self.sabi_check_same_utypeid::<T>());
        unsafe { 
            Ok(transmute_mut_reference::<(),T>(&mut **self.ptr))
        }
    }

    /// Unwraps the `RObject<_>` into a pointer to T,
    /// without checking whether `T` is the type that the RObject was constructed with.
    ///
    /// # Safety
    ///
    /// You must check that `T` is the type that RObject was constructed
    /// with through other means.
    #[inline]
    pub unsafe fn unchecked_into_unerased<T>(self) -> P::TransmutedPtr
    where
        P: Deref<Target=()> + CanTransmuteElement<T>,
    {
        let this=ManuallyDrop::new(self);
        ptr::read(&*this.ptr).transmute_element::<T>()
    }

    /// Unwraps the `RObject<_>` into a reference to T,
    /// without checking whether `T` is the type that the RObject was constructed with.
    ///
    /// # Safety
    ///
    /// You must check that `T` is the type that RObject was constructed
    /// with through other means.
    #[inline]
    pub unsafe fn unchecked_as_unerased<T>(&self) -> &T
    where
        P:Deref<Target=()>,
    {
        transmute_reference::<(),T>(&**self.ptr)
    }

    /// Unwraps the `RObject<_>` into a mutable reference to T,
    /// without checking whether `T` is the type that the RObject was constructed with.
    ///
    /// # Safety
    ///
    /// You must check that `T` is the type that RObject was constructed
    /// with through other means.
    #[inline]
    pub unsafe fn unchecked_as_unerased_mut<T>(&mut self) -> &mut T
    where
        P:DerefMut<Target=()>,
    {
        transmute_mut_reference::<(),T>(&mut **self.ptr)
    }

}


mod private_struct {
    pub struct PrivStruct;
}
use self::private_struct::PrivStruct;


/// This is used to make sure that reborrowing does not change 
/// the Send-ness or Sync-ness of the pointer.
pub trait ReborrowBounds<SendNess,SyncNess>{}

// If it's reborrowing,it must have either both Sync+Send or neither.
impl ReborrowBounds<Unimplemented<trait_marker::Send>,Unimplemented<trait_marker::Sync>> 
for PrivStruct 
{}

impl ReborrowBounds<Implemented<trait_marker::Send>,Implemented<trait_marker::Sync>> 
for PrivStruct 
{}


impl<'lt,P,I,V> RObject<'lt,P,I,V>
where
    P:GetPointerKind,
    I:InterfaceType,
{
    /// Creates a shared reborrow of this RObject.
    ///
    pub fn reborrow<'re>(&'re self)->RObject<'lt,&'re (),I,V> 
    where
        P:Deref<Target=()>,
        PrivStruct:ReborrowBounds<I::Send,I::Sync>,
    {
        // Reborrowing will break if I add extra functions that operate on `P`.
        RObject{
            vtable:self.vtable,
            ptr:ManuallyDrop::new(&**self.ptr),
            _marker:PhantomData,
        }
    }

    /// Creates a mutable reborrow of this RObject.
    ///
    /// The reborrowed RObject cannot use these methods:
    ///
    /// - RObject::clone
    /// 
    pub fn reborrow_mut<'re>(&'re mut self)->RObject<'lt,&'re mut (),I,V> 
    where
        P:DerefMut<Target=()>,
        PrivStruct:ReborrowBounds<I::Send,I::Sync>,
    {
        // Reborrowing will break if I add extra functions that operate on `P`.
        RObject {
            vtable: self.vtable,
            ptr: ManuallyDrop::new(&mut **self.ptr),
            _marker:PhantomData,
        }
    }
}




impl<'lt,P,I,V> RObject<'lt,P,I,V>
where
    P:GetPointerKind,
{
    #[inline]
    pub fn sabi_et_vtable(&self)->StaticRef<V>{
        self.vtable
    }

    /// The vtable common to all `#[sabi_trait]` generated trait objects.
    #[inline]
    pub fn sabi_robject_vtable<'a>(&self)->&'a RObjectVtable<(),P,I>{
        unsafe{ 
            let vtable=&*(self.vtable.get() as *const V as *const BaseVtable<(),P,I>);
            vtable._sabi_vtable().get()
        }
    }

    #[inline]
    fn sabi_into_erased_ptr(self)->ManuallyDrop<P>{
        let mut __this= ManuallyDrop::new(self);
        unsafe{ ptr::read(&mut __this.ptr) }
    }

    #[inline]
    pub fn sabi_erased_ref(&self)->&ErasedObject<()>
    where
        P: __DerefTrait<Target=()>
    {
        unsafe{&*((&**self.ptr) as *const () as *const ErasedObject<()>)}
    }
    
    #[inline]
    pub fn sabi_erased_mut(&mut self)->&mut ErasedObject<()>
    where
        P: __DerefMutTrait<Target=()>
    {
        unsafe{&mut *((&mut **self.ptr) as *mut () as *mut ErasedObject<()>)}
    }

    #[inline]
    pub fn sabi_with_value<F,R>(self,f:F)->R
    where 
        P: OwnedPointer<Target=()>,
        F:FnOnce(MovePtr<'_,()>)->R,
    {
        OwnedPointer::with_move_ptr(self.sabi_into_erased_ptr(),f)
    }
}

impl<P,I,V> Drop for RObject<'_,P,I,V>
where
    P:GetPointerKind,
{
    fn drop(&mut self){
        // This condition is necessary because if the RObject was reborrowed,
        // the destructor function would take a different pointer type.
        if <P as GetPointerKind>::KIND==PointerKind::SmartPointer {
            let destructor=self.sabi_robject_vtable()._sabi_drop();
            unsafe{
                destructor(&mut self.ptr);
            }
        }
    }
}





//////////////////////////////////////////////////////////////////

/// Error for `RObject<_>` being unerased into the wrong type
/// with one of the `*unerased*` methods.
#[derive(Copy, Clone)]
pub struct UneraseError<T> {
    robject:T,
    expected_typeid:MaybeCmp<UTypeId>,
    actual_typeid:UTypeId,
}


impl<T> UneraseError<T>{
    fn map<F,U>(self,f:F)->UneraseError<U>
    where F:FnOnce(T)->U
    {
        UneraseError{
            robject        :f(self.robject),
            expected_typeid:self.expected_typeid,
            actual_typeid  :self.actual_typeid,
        }
    }

    /// Extracts the RObject,to handle the failure to unerase it.
    #[must_use]
    pub fn into_inner(self)->T{
        self.robject
    }
}


impl<D> fmt::Debug for UneraseError<D>{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UneraseError")
            .field("dyn_trait",&"<not shown>")
            .field("expected_typeid",&self.expected_typeid)
            .field("actual_typeid",&self.actual_typeid)
            .finish()
    }
}

impl<D> fmt::Display for UneraseError<D>{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl<D> ::std::error::Error for UneraseError<D> {}

//////////////////////////////////////////////////////////////////