intuicio_data/
managed.rs

1use crate::{
2    Finalize,
3    lifetime::{
4        Lifetime, LifetimeLazy, LifetimeRef, LifetimeRefMut, ValueReadAccess, ValueWriteAccess,
5    },
6    type_hash::TypeHash,
7};
8use std::{
9    alloc::{Layout, alloc, dealloc},
10    mem::MaybeUninit,
11};
12
13#[derive(Default)]
14pub struct Managed<T> {
15    lifetime: Lifetime,
16    data: T,
17}
18
19impl<T> Managed<T> {
20    pub fn new(data: T) -> Self {
21        Self {
22            lifetime: Default::default(),
23            data,
24        }
25    }
26
27    pub fn new_raw(data: T, lifetime: Lifetime) -> Self {
28        Self { lifetime, data }
29    }
30
31    pub fn into_inner(self) -> (Lifetime, T) {
32        (self.lifetime, self.data)
33    }
34
35    pub fn into_dynamic(self) -> Option<DynamicManaged> {
36        DynamicManaged::new(self.data).ok()
37    }
38
39    pub fn renew(mut self) -> Self {
40        self.lifetime = Lifetime::default();
41        self
42    }
43
44    pub fn lifetime(&self) -> &Lifetime {
45        &self.lifetime
46    }
47
48    pub fn read(&self) -> Option<ValueReadAccess<T>> {
49        self.lifetime.read(&self.data)
50    }
51
52    pub fn write(&mut self) -> Option<ValueWriteAccess<T>> {
53        self.lifetime.write(&mut self.data)
54    }
55
56    pub fn consume(self) -> Result<T, Self> {
57        if self.lifetime.state().is_in_use() {
58            Err(self)
59        } else {
60            Ok(self.data)
61        }
62    }
63
64    pub fn move_into_ref(self, mut target: ManagedRefMut<T>) -> Result<(), Self> {
65        *target.write().unwrap() = self.consume()?;
66        Ok(())
67    }
68
69    pub fn move_into_lazy(self, target: ManagedLazy<T>) -> Result<(), Self> {
70        *target.write().unwrap() = self.consume()?;
71        Ok(())
72    }
73
74    pub fn borrow(&self) -> Option<ManagedRef<T>> {
75        Some(ManagedRef::new(&self.data, self.lifetime.borrow()?))
76    }
77
78    pub fn borrow_mut(&mut self) -> Option<ManagedRefMut<T>> {
79        Some(ManagedRefMut::new(
80            &mut self.data,
81            self.lifetime.borrow_mut()?,
82        ))
83    }
84
85    pub fn lazy(&mut self) -> ManagedLazy<T> {
86        ManagedLazy::new(&mut self.data, self.lifetime.lazy())
87    }
88
89    /// # Safety
90    pub unsafe fn lazy_immutable(&self) -> ManagedLazy<T> {
91        unsafe {
92            ManagedLazy::new_raw(&self.data as *const T as *mut T, self.lifetime.lazy()).unwrap()
93        }
94    }
95
96    /// # Safety
97    pub unsafe fn map<U>(self, f: impl FnOnce(T) -> U) -> Managed<U> {
98        Managed {
99            lifetime: Default::default(),
100            data: f(self.data),
101        }
102    }
103
104    /// # Safety
105    pub unsafe fn try_map<U>(self, f: impl FnOnce(T) -> Option<U>) -> Option<Managed<U>> {
106        f(self.data).map(|data| Managed {
107            lifetime: Default::default(),
108            data,
109        })
110    }
111
112    /// # Safety
113    pub unsafe fn as_ptr(&self) -> *const T {
114        &self.data as _
115    }
116
117    /// # Safety
118    pub unsafe fn as_mut_ptr(&mut self) -> *mut T {
119        &mut self.data as _
120    }
121}
122
123impl<T> TryFrom<ManagedValue<T>> for Managed<T> {
124    type Error = ();
125
126    fn try_from(value: ManagedValue<T>) -> Result<Self, Self::Error> {
127        match value {
128            ManagedValue::Owned(value) => Ok(value),
129            _ => Err(()),
130        }
131    }
132}
133
134pub struct ManagedRef<T: ?Sized> {
135    lifetime: LifetimeRef,
136    data: *const T,
137}
138
139unsafe impl<T: ?Sized> Send for ManagedRef<T> where T: Send {}
140unsafe impl<T: ?Sized> Sync for ManagedRef<T> where T: Sync {}
141
142impl<T: ?Sized> ManagedRef<T> {
143    pub fn new(data: &T, lifetime: LifetimeRef) -> Self {
144        Self {
145            lifetime,
146            data: data as *const T,
147        }
148    }
149
150    /// # Safety
151    pub unsafe fn new_raw(data: *const T, lifetime: LifetimeRef) -> Option<Self> {
152        if data.is_null() {
153            None
154        } else {
155            Some(Self { lifetime, data })
156        }
157    }
158
159    pub fn make(data: &T) -> (Self, Lifetime) {
160        let result = Lifetime::default();
161        (Self::new(data, result.borrow().unwrap()), result)
162    }
163
164    /// # Safety
165    pub unsafe fn make_raw(data: *const T) -> Option<(Self, Lifetime)> {
166        let result = Lifetime::default();
167        Some((
168            unsafe { Self::new_raw(data, result.borrow().unwrap()) }?,
169            result,
170        ))
171    }
172
173    pub fn into_inner(self) -> (LifetimeRef, *const T) {
174        (self.lifetime, self.data)
175    }
176
177    pub fn into_dynamic(self) -> DynamicManagedRef {
178        unsafe {
179            DynamicManagedRef::new_raw(TypeHash::of::<T>(), self.lifetime, self.data as *const u8)
180                .unwrap()
181        }
182    }
183
184    pub fn lifetime(&self) -> &LifetimeRef {
185        &self.lifetime
186    }
187
188    pub fn borrow(&self) -> Option<ManagedRef<T>> {
189        Some(ManagedRef {
190            lifetime: self.lifetime.borrow()?,
191            data: self.data,
192        })
193    }
194
195    pub fn read(&self) -> Option<ValueReadAccess<T>> {
196        unsafe { self.lifetime.read_ptr(self.data) }
197    }
198
199    /// # Safety
200    pub unsafe fn map<U>(self, f: impl FnOnce(&T) -> &U) -> ManagedRef<U> {
201        unsafe {
202            let data = f(&*self.data);
203            ManagedRef {
204                lifetime: self.lifetime,
205                data: data as *const U,
206            }
207        }
208    }
209
210    /// # Safety
211    pub unsafe fn try_map<U>(self, f: impl FnOnce(&T) -> Option<&U>) -> Option<ManagedRef<U>> {
212        unsafe {
213            f(&*self.data).map(|data| ManagedRef {
214                lifetime: self.lifetime,
215                data: data as *const U,
216            })
217        }
218    }
219
220    /// # Safety
221    pub unsafe fn as_ptr(&self) -> Option<*const T> {
222        if self.lifetime.exists() {
223            Some(self.data)
224        } else {
225            None
226        }
227    }
228}
229
230impl<T> TryFrom<ManagedValue<T>> for ManagedRef<T> {
231    type Error = ();
232
233    fn try_from(value: ManagedValue<T>) -> Result<Self, Self::Error> {
234        match value {
235            ManagedValue::Ref(value) => Ok(value),
236            _ => Err(()),
237        }
238    }
239}
240
241pub struct ManagedRefMut<T: ?Sized> {
242    lifetime: LifetimeRefMut,
243    data: *mut T,
244}
245
246unsafe impl<T: ?Sized> Send for ManagedRefMut<T> where T: Send {}
247unsafe impl<T: ?Sized> Sync for ManagedRefMut<T> where T: Sync {}
248
249impl<T: ?Sized> ManagedRefMut<T> {
250    pub fn new(data: &mut T, lifetime: LifetimeRefMut) -> Self {
251        Self {
252            lifetime,
253            data: data as *mut T,
254        }
255    }
256
257    /// # Safety
258    pub unsafe fn new_raw(data: *mut T, lifetime: LifetimeRefMut) -> Option<Self> {
259        if data.is_null() {
260            None
261        } else {
262            Some(Self { lifetime, data })
263        }
264    }
265
266    pub fn make(data: &mut T) -> (Self, Lifetime) {
267        let result = Lifetime::default();
268        (Self::new(data, result.borrow_mut().unwrap()), result)
269    }
270
271    /// # Safety
272    pub unsafe fn make_raw(data: *mut T) -> Option<(Self, Lifetime)> {
273        let result = Lifetime::default();
274        Some((
275            unsafe { Self::new_raw(data, result.borrow_mut().unwrap()) }?,
276            result,
277        ))
278    }
279
280    pub fn into_inner(self) -> (LifetimeRefMut, *mut T) {
281        (self.lifetime, self.data)
282    }
283
284    pub fn into_dynamic(self) -> DynamicManagedRefMut {
285        unsafe {
286            DynamicManagedRefMut::new_raw(TypeHash::of::<T>(), self.lifetime, self.data as *mut u8)
287                .unwrap()
288        }
289    }
290
291    pub fn lifetime(&self) -> &LifetimeRefMut {
292        &self.lifetime
293    }
294
295    pub fn borrow(&self) -> Option<ManagedRef<T>> {
296        Some(ManagedRef {
297            lifetime: self.lifetime.borrow()?,
298            data: self.data,
299        })
300    }
301
302    pub fn borrow_mut(&mut self) -> Option<ManagedRefMut<T>> {
303        Some(ManagedRefMut {
304            lifetime: self.lifetime.borrow_mut()?,
305            data: self.data,
306        })
307    }
308
309    pub fn read(&self) -> Option<ValueReadAccess<T>> {
310        unsafe { self.lifetime.read_ptr(self.data) }
311    }
312
313    pub fn write(&mut self) -> Option<ValueWriteAccess<T>> {
314        unsafe { self.lifetime.write_ptr(self.data) }
315    }
316
317    /// # Safety
318    pub unsafe fn map<U>(self, f: impl FnOnce(&mut T) -> &mut U) -> ManagedRefMut<U> {
319        unsafe {
320            let data = f(&mut *self.data);
321            ManagedRefMut {
322                lifetime: self.lifetime,
323                data: data as *mut U,
324            }
325        }
326    }
327
328    /// # Safety
329    pub unsafe fn try_map<U>(
330        self,
331        f: impl FnOnce(&mut T) -> Option<&mut U>,
332    ) -> Option<ManagedRefMut<U>> {
333        unsafe {
334            f(&mut *self.data).map(|data| ManagedRefMut {
335                lifetime: self.lifetime,
336                data: data as *mut U,
337            })
338        }
339    }
340
341    /// # Safety
342    pub unsafe fn as_ptr(&self) -> Option<*const T> {
343        if self.lifetime.exists() {
344            Some(self.data)
345        } else {
346            None
347        }
348    }
349
350    /// # Safety
351    pub unsafe fn as_mut_ptr(&mut self) -> Option<*mut T> {
352        if self.lifetime.exists() {
353            Some(self.data)
354        } else {
355            None
356        }
357    }
358}
359
360impl<T> TryFrom<ManagedValue<T>> for ManagedRefMut<T> {
361    type Error = ();
362
363    fn try_from(value: ManagedValue<T>) -> Result<Self, Self::Error> {
364        match value {
365            ManagedValue::RefMut(value) => Ok(value),
366            _ => Err(()),
367        }
368    }
369}
370
371pub struct ManagedLazy<T: ?Sized> {
372    lifetime: LifetimeLazy,
373    data: *mut T,
374}
375
376unsafe impl<T: ?Sized> Send for ManagedLazy<T> where T: Send {}
377unsafe impl<T: ?Sized> Sync for ManagedLazy<T> where T: Sync {}
378
379impl<T: ?Sized> Clone for ManagedLazy<T> {
380    fn clone(&self) -> Self {
381        Self {
382            lifetime: self.lifetime.clone(),
383            data: self.data,
384        }
385    }
386}
387
388impl<T: ?Sized> ManagedLazy<T> {
389    pub fn new(data: &mut T, lifetime: LifetimeLazy) -> Self {
390        Self {
391            lifetime,
392            data: data as *mut T,
393        }
394    }
395
396    /// # Safety
397    pub unsafe fn new_raw(data: *mut T, lifetime: LifetimeLazy) -> Option<Self> {
398        if data.is_null() {
399            None
400        } else {
401            Some(Self { lifetime, data })
402        }
403    }
404
405    pub fn make(data: &mut T) -> (Self, Lifetime) {
406        let result = Lifetime::default();
407        (Self::new(data, result.lazy()), result)
408    }
409
410    /// # Safety
411    pub unsafe fn make_raw(data: *mut T) -> Option<(Self, Lifetime)> {
412        let result = Lifetime::default();
413        Some((unsafe { Self::new_raw(data, result.lazy()) }?, result))
414    }
415
416    pub fn into_inner(self) -> (LifetimeLazy, *mut T) {
417        (self.lifetime, self.data)
418    }
419
420    pub fn into_dynamic(self) -> DynamicManagedLazy {
421        unsafe {
422            DynamicManagedLazy::new_raw(TypeHash::of::<T>(), self.lifetime, self.data as *mut u8)
423                .unwrap()
424        }
425    }
426
427    pub fn lifetime(&self) -> &LifetimeLazy {
428        &self.lifetime
429    }
430
431    pub fn borrow(&self) -> Option<ManagedRef<T>> {
432        Some(ManagedRef {
433            lifetime: self.lifetime.borrow()?,
434            data: self.data,
435        })
436    }
437
438    pub fn borrow_mut(&mut self) -> Option<ManagedRefMut<T>> {
439        Some(ManagedRefMut {
440            lifetime: self.lifetime.borrow_mut()?,
441            data: self.data,
442        })
443    }
444
445    pub fn read(&self) -> Option<ValueReadAccess<T>> {
446        unsafe { self.lifetime.read_ptr(self.data) }
447    }
448
449    pub fn write(&self) -> Option<ValueWriteAccess<T>> {
450        unsafe { self.lifetime.write_ptr(self.data) }
451    }
452
453    /// # Safety
454    pub unsafe fn map<U>(self, f: impl FnOnce(&mut T) -> &mut U) -> ManagedLazy<U> {
455        unsafe {
456            let data = f(&mut *self.data);
457            ManagedLazy {
458                lifetime: self.lifetime,
459                data: data as *mut U,
460            }
461        }
462    }
463
464    /// # Safety
465    pub unsafe fn try_map<U>(
466        self,
467        f: impl FnOnce(&mut T) -> Option<&mut U>,
468    ) -> Option<ManagedLazy<U>> {
469        unsafe {
470            f(&mut *self.data).map(|data| ManagedLazy {
471                lifetime: self.lifetime,
472                data: data as *mut U,
473            })
474        }
475    }
476
477    /// # Safety
478    pub unsafe fn as_ptr(&self) -> Option<*const T> {
479        if self.lifetime.exists() {
480            Some(self.data)
481        } else {
482            None
483        }
484    }
485
486    /// # Safety
487    pub unsafe fn as_mut_ptr(&self) -> Option<*mut T> {
488        if self.lifetime.exists() {
489            Some(self.data)
490        } else {
491            None
492        }
493    }
494}
495
496impl<T> TryFrom<ManagedValue<T>> for ManagedLazy<T> {
497    type Error = ();
498
499    fn try_from(value: ManagedValue<T>) -> Result<Self, Self::Error> {
500        match value {
501            ManagedValue::Lazy(value) => Ok(value),
502            _ => Err(()),
503        }
504    }
505}
506
507pub enum ManagedValue<T> {
508    Owned(Managed<T>),
509    Ref(ManagedRef<T>),
510    RefMut(ManagedRefMut<T>),
511    Lazy(ManagedLazy<T>),
512}
513
514impl<T> ManagedValue<T> {
515    pub fn as_owned(&self) -> Option<&Managed<T>> {
516        match self {
517            Self::Owned(value) => Some(value),
518            _ => None,
519        }
520    }
521
522    pub fn as_mut_owned(&mut self) -> Option<&mut Managed<T>> {
523        match self {
524            Self::Owned(value) => Some(value),
525            _ => None,
526        }
527    }
528
529    pub fn as_ref(&self) -> Option<&ManagedRef<T>> {
530        match self {
531            Self::Ref(value) => Some(value),
532            _ => None,
533        }
534    }
535
536    pub fn as_mut_ref(&mut self) -> Option<&mut ManagedRef<T>> {
537        match self {
538            Self::Ref(value) => Some(value),
539            _ => None,
540        }
541    }
542
543    pub fn as_ref_mut(&self) -> Option<&ManagedRefMut<T>> {
544        match self {
545            Self::RefMut(value) => Some(value),
546            _ => None,
547        }
548    }
549
550    pub fn as_mut_ref_mut(&mut self) -> Option<&mut ManagedRefMut<T>> {
551        match self {
552            Self::RefMut(value) => Some(value),
553            _ => None,
554        }
555    }
556
557    pub fn as_lazy(&self) -> Option<&ManagedLazy<T>> {
558        match self {
559            Self::Lazy(value) => Some(value),
560            _ => None,
561        }
562    }
563
564    pub fn as_mut_lazy(&mut self) -> Option<&mut ManagedLazy<T>> {
565        match self {
566            Self::Lazy(value) => Some(value),
567            _ => None,
568        }
569    }
570
571    pub fn read(&self) -> Option<ValueReadAccess<T>> {
572        match self {
573            Self::Owned(value) => value.read(),
574            Self::Ref(value) => value.read(),
575            Self::RefMut(value) => value.read(),
576            Self::Lazy(value) => value.read(),
577        }
578    }
579
580    pub fn write(&mut self) -> Option<ValueWriteAccess<T>> {
581        match self {
582            Self::Owned(value) => value.write(),
583            Self::RefMut(value) => value.write(),
584            Self::Lazy(value) => value.write(),
585            _ => None,
586        }
587    }
588
589    pub fn borrow(&self) -> Option<ManagedRef<T>> {
590        match self {
591            Self::Owned(value) => value.borrow(),
592            Self::Ref(value) => value.borrow(),
593            Self::RefMut(value) => value.borrow(),
594            _ => None,
595        }
596    }
597
598    pub fn borrow_mut(&mut self) -> Option<ManagedRefMut<T>> {
599        match self {
600            Self::Owned(value) => value.borrow_mut(),
601            Self::RefMut(value) => value.borrow_mut(),
602            _ => None,
603        }
604    }
605
606    pub fn lazy(&mut self) -> Option<ManagedLazy<T>> {
607        match self {
608            Self::Owned(value) => Some(value.lazy()),
609            Self::Lazy(value) => Some(value.clone()),
610            _ => None,
611        }
612    }
613}
614
615impl<T> From<Managed<T>> for ManagedValue<T> {
616    fn from(value: Managed<T>) -> Self {
617        Self::Owned(value)
618    }
619}
620
621impl<T> From<ManagedRef<T>> for ManagedValue<T> {
622    fn from(value: ManagedRef<T>) -> Self {
623        Self::Ref(value)
624    }
625}
626
627impl<T> From<ManagedRefMut<T>> for ManagedValue<T> {
628    fn from(value: ManagedRefMut<T>) -> Self {
629        Self::RefMut(value)
630    }
631}
632
633impl<T> From<ManagedLazy<T>> for ManagedValue<T> {
634    fn from(value: ManagedLazy<T>) -> Self {
635        Self::Lazy(value)
636    }
637}
638
639pub struct DynamicManaged {
640    type_hash: TypeHash,
641    lifetime: Lifetime,
642    memory: *mut u8,
643    layout: Layout,
644    finalizer: unsafe fn(*mut ()),
645    drop: bool,
646}
647
648unsafe impl Send for DynamicManaged {}
649unsafe impl Sync for DynamicManaged {}
650
651impl Drop for DynamicManaged {
652    fn drop(&mut self) {
653        if self.drop {
654            unsafe {
655                let data_pointer = self.memory.cast::<()>();
656                (self.finalizer)(data_pointer);
657                dealloc(self.memory, self.layout);
658            }
659        }
660    }
661}
662
663impl DynamicManaged {
664    pub fn new<T: Finalize>(data: T) -> Result<Self, T> {
665        let layout = Layout::new::<T>().pad_to_align();
666        unsafe {
667            let memory = alloc(layout);
668            if memory.is_null() {
669                Err(data)
670            } else {
671                memory.cast::<T>().write(data);
672                Ok(Self {
673                    type_hash: TypeHash::of::<T>(),
674                    lifetime: Default::default(),
675                    memory,
676                    layout,
677                    finalizer: T::finalize_raw,
678                    drop: true,
679                })
680            }
681        }
682    }
683
684    pub fn new_raw(
685        type_hash: TypeHash,
686        lifetime: Lifetime,
687        memory: *mut u8,
688        layout: Layout,
689        finalizer: unsafe fn(*mut ()),
690    ) -> Option<Self> {
691        if memory.is_null() {
692            None
693        } else {
694            Some(Self {
695                type_hash,
696                lifetime,
697                memory,
698                layout,
699                finalizer,
700                drop: true,
701            })
702        }
703    }
704
705    /// # Safety
706    pub unsafe fn from_bytes(
707        type_hash: TypeHash,
708        lifetime: Lifetime,
709        bytes: Vec<u8>,
710        layout: Layout,
711        finalizer: unsafe fn(*mut ()),
712    ) -> Self {
713        let memory = unsafe { alloc(layout) };
714        unsafe { memory.copy_from(bytes.as_ptr(), bytes.len()) };
715        Self {
716            type_hash,
717            lifetime,
718            memory,
719            layout,
720            finalizer,
721            drop: true,
722        }
723    }
724
725    #[allow(clippy::type_complexity)]
726    pub fn into_inner(mut self) -> (TypeHash, Lifetime, *mut u8, Layout, unsafe fn(*mut ())) {
727        self.drop = false;
728        (
729            self.type_hash,
730            std::mem::take(&mut self.lifetime),
731            self.memory,
732            self.layout,
733            self.finalizer,
734        )
735    }
736
737    pub fn into_typed<T>(self) -> Result<Managed<T>, Self> {
738        Ok(Managed::new(self.consume()?))
739    }
740
741    pub fn renew(mut self) -> Self {
742        self.lifetime = Lifetime::default();
743        self
744    }
745
746    pub fn type_hash(&self) -> &TypeHash {
747        &self.type_hash
748    }
749
750    pub fn lifetime(&self) -> &Lifetime {
751        &self.lifetime
752    }
753
754    pub fn layout(&self) -> &Layout {
755        &self.layout
756    }
757
758    pub fn finalizer(&self) -> unsafe fn(*mut ()) {
759        self.finalizer
760    }
761
762    /// # Safety
763    pub unsafe fn memory(&self) -> &[u8] {
764        unsafe { std::slice::from_raw_parts(self.memory, self.layout.size()) }
765    }
766
767    /// # Safety
768    pub unsafe fn memory_mut(&mut self) -> &mut [u8] {
769        unsafe { std::slice::from_raw_parts_mut(self.memory, self.layout.size()) }
770    }
771
772    pub fn is<T>(&self) -> bool {
773        self.type_hash == TypeHash::of::<T>()
774    }
775
776    pub fn read<T>(&self) -> Option<ValueReadAccess<T>> {
777        if self.type_hash == TypeHash::of::<T>() {
778            unsafe { self.lifetime.read_ptr(self.memory.cast::<T>()) }
779        } else {
780            None
781        }
782    }
783
784    pub fn write<T>(&mut self) -> Option<ValueWriteAccess<T>> {
785        if self.type_hash == TypeHash::of::<T>() {
786            unsafe { self.lifetime.write_ptr(self.memory.cast::<T>()) }
787        } else {
788            None
789        }
790    }
791
792    pub fn consume<T>(mut self) -> Result<T, Self> {
793        if self.type_hash == TypeHash::of::<T>() && !self.lifetime.state().is_in_use() {
794            self.drop = false;
795            let mut result = MaybeUninit::<T>::uninit();
796            unsafe {
797                result.as_mut_ptr().copy_from(self.memory.cast::<T>(), 1);
798                dealloc(self.memory, self.layout);
799                Ok(result.assume_init())
800            }
801        } else {
802            Err(self)
803        }
804    }
805
806    pub fn move_into_ref(self, target: DynamicManagedRefMut) -> Result<(), Self> {
807        if self.type_hash == target.type_hash && self.memory != target.data {
808            let (_, _, memory, layout, _) = self.into_inner();
809            unsafe {
810                target.data.copy_from(memory, layout.size());
811                dealloc(memory, layout);
812            }
813            Ok(())
814        } else {
815            Err(self)
816        }
817    }
818
819    pub fn move_into_lazy(self, target: DynamicManagedLazy) -> Result<(), Self> {
820        if self.type_hash == target.type_hash && self.memory != target.data {
821            let (_, _, memory, layout, _) = self.into_inner();
822            unsafe {
823                target.data.copy_from(memory, layout.size());
824                dealloc(memory, layout);
825            }
826            Ok(())
827        } else {
828            Err(self)
829        }
830    }
831
832    pub fn borrow(&self) -> Option<DynamicManagedRef> {
833        unsafe { DynamicManagedRef::new_raw(self.type_hash, self.lifetime.borrow()?, self.memory) }
834    }
835
836    pub fn borrow_mut(&mut self) -> Option<DynamicManagedRefMut> {
837        unsafe {
838            DynamicManagedRefMut::new_raw(self.type_hash, self.lifetime.borrow_mut()?, self.memory)
839        }
840    }
841
842    pub fn lazy(&self) -> DynamicManagedLazy {
843        unsafe {
844            DynamicManagedLazy::new_raw(self.type_hash, self.lifetime.lazy(), self.memory).unwrap()
845        }
846    }
847
848    /// # Safety
849    pub unsafe fn map<T, U: Finalize>(self, f: impl FnOnce(T) -> U) -> Option<Self> {
850        let data = self.consume::<T>().ok()?;
851        let data = f(data);
852        Self::new(data).ok()
853    }
854
855    /// # Safety
856    pub unsafe fn try_map<T, U: Finalize>(self, f: impl FnOnce(T) -> Option<U>) -> Option<Self> {
857        let data = self.consume::<T>().ok()?;
858        let data = f(data)?;
859        Self::new(data).ok()
860    }
861
862    /// # Safety
863    pub unsafe fn as_ptr<T>(&self) -> Option<*const T> {
864        if self.type_hash == TypeHash::of::<T>() && !self.lifetime.state().is_in_use() {
865            Some(self.memory.cast::<T>())
866        } else {
867            None
868        }
869    }
870
871    /// # Safety
872    pub unsafe fn as_mut_ptr<T>(&mut self) -> Option<*mut T> {
873        if self.type_hash == TypeHash::of::<T>() && !self.lifetime.state().is_in_use() {
874            Some(self.memory.cast::<T>())
875        } else {
876            None
877        }
878    }
879
880    /// # Safety
881    pub unsafe fn as_ptr_raw(&self) -> *const u8 {
882        self.memory
883    }
884
885    /// # Safety
886    pub unsafe fn as_mut_ptr_raw(&mut self) -> *mut u8 {
887        self.memory
888    }
889}
890
891impl TryFrom<DynamicManagedValue> for DynamicManaged {
892    type Error = ();
893
894    fn try_from(value: DynamicManagedValue) -> Result<Self, Self::Error> {
895        match value {
896            DynamicManagedValue::Owned(value) => Ok(value),
897            _ => Err(()),
898        }
899    }
900}
901
902pub struct DynamicManagedRef {
903    type_hash: TypeHash,
904    lifetime: LifetimeRef,
905    data: *const u8,
906}
907
908unsafe impl Send for DynamicManagedRef {}
909unsafe impl Sync for DynamicManagedRef {}
910
911impl DynamicManagedRef {
912    pub fn new<T: ?Sized>(data: &T, lifetime: LifetimeRef) -> Self {
913        Self {
914            type_hash: TypeHash::of::<T>(),
915            lifetime,
916            data: data as *const T as *const u8,
917        }
918    }
919
920    /// # Safety
921    pub unsafe fn new_raw(
922        type_hash: TypeHash,
923        lifetime: LifetimeRef,
924        data: *const u8,
925    ) -> Option<Self> {
926        if data.is_null() {
927            None
928        } else {
929            Some(Self {
930                type_hash,
931                lifetime,
932                data,
933            })
934        }
935    }
936
937    pub fn make<T: ?Sized>(data: &T) -> (Self, Lifetime) {
938        let result = Lifetime::default();
939        (Self::new(data, result.borrow().unwrap()), result)
940    }
941
942    pub fn into_inner(self) -> (TypeHash, LifetimeRef, *const u8) {
943        (self.type_hash, self.lifetime, self.data)
944    }
945
946    pub fn into_typed<T>(self) -> Result<ManagedRef<T>, Self> {
947        if self.type_hash == TypeHash::of::<T>() {
948            unsafe { Ok(ManagedRef::new_raw(self.data.cast::<T>(), self.lifetime).unwrap()) }
949        } else {
950            Err(self)
951        }
952    }
953
954    pub fn type_hash(&self) -> &TypeHash {
955        &self.type_hash
956    }
957
958    pub fn lifetime(&self) -> &LifetimeRef {
959        &self.lifetime
960    }
961
962    pub fn borrow(&self) -> Option<DynamicManagedRef> {
963        Some(DynamicManagedRef {
964            type_hash: self.type_hash,
965            lifetime: self.lifetime.borrow()?,
966            data: self.data,
967        })
968    }
969
970    pub fn is<T>(&self) -> bool {
971        self.type_hash == TypeHash::of::<T>()
972    }
973
974    pub fn read<T>(&self) -> Option<ValueReadAccess<T>> {
975        if self.type_hash == TypeHash::of::<T>() {
976            unsafe { self.lifetime.read_ptr(self.data.cast::<T>()) }
977        } else {
978            None
979        }
980    }
981
982    /// # Safety
983    pub unsafe fn map<T, U>(self, f: impl FnOnce(&T) -> &U) -> Option<Self> {
984        if self.type_hash == TypeHash::of::<T>() {
985            unsafe {
986                let data = f(&*self.data.cast::<T>());
987                Some(Self {
988                    type_hash: TypeHash::of::<U>(),
989                    lifetime: self.lifetime,
990                    data: data as *const U as *const u8,
991                })
992            }
993        } else {
994            None
995        }
996    }
997
998    /// # Safety
999    pub unsafe fn try_map<T, U>(self, f: impl FnOnce(&T) -> Option<&U>) -> Option<Self> {
1000        if self.type_hash == TypeHash::of::<T>() {
1001            unsafe {
1002                let data = f(&*self.data.cast::<T>())?;
1003                Some(Self {
1004                    type_hash: TypeHash::of::<U>(),
1005                    lifetime: self.lifetime,
1006                    data: data as *const U as *const u8,
1007                })
1008            }
1009        } else {
1010            None
1011        }
1012    }
1013
1014    /// # Safety
1015    pub unsafe fn as_ptr<T>(&self) -> Option<*const T> {
1016        if self.type_hash == TypeHash::of::<T>() && self.lifetime.exists() {
1017            Some(self.data.cast::<T>())
1018        } else {
1019            None
1020        }
1021    }
1022
1023    /// # Safety
1024    pub unsafe fn as_ptr_raw(&self) -> Option<*const u8> {
1025        if self.lifetime.exists() {
1026            Some(self.data)
1027        } else {
1028            None
1029        }
1030    }
1031}
1032
1033impl TryFrom<DynamicManagedValue> for DynamicManagedRef {
1034    type Error = ();
1035
1036    fn try_from(value: DynamicManagedValue) -> Result<Self, Self::Error> {
1037        match value {
1038            DynamicManagedValue::Ref(value) => Ok(value),
1039            _ => Err(()),
1040        }
1041    }
1042}
1043
1044pub struct DynamicManagedRefMut {
1045    type_hash: TypeHash,
1046    lifetime: LifetimeRefMut,
1047    data: *mut u8,
1048}
1049
1050unsafe impl Send for DynamicManagedRefMut {}
1051unsafe impl Sync for DynamicManagedRefMut {}
1052
1053impl DynamicManagedRefMut {
1054    pub fn new<T: ?Sized>(data: &mut T, lifetime: LifetimeRefMut) -> Self {
1055        Self {
1056            type_hash: TypeHash::of::<T>(),
1057            lifetime,
1058            data: data as *mut T as *mut u8,
1059        }
1060    }
1061
1062    /// # Safety
1063    pub unsafe fn new_raw(
1064        type_hash: TypeHash,
1065        lifetime: LifetimeRefMut,
1066        data: *mut u8,
1067    ) -> Option<Self> {
1068        if data.is_null() {
1069            None
1070        } else {
1071            Some(Self {
1072                type_hash,
1073                lifetime,
1074                data,
1075            })
1076        }
1077    }
1078
1079    pub fn make<T: ?Sized>(data: &mut T) -> (Self, Lifetime) {
1080        let result = Lifetime::default();
1081        (Self::new(data, result.borrow_mut().unwrap()), result)
1082    }
1083
1084    pub fn into_inner(self) -> (TypeHash, LifetimeRefMut, *mut u8) {
1085        (self.type_hash, self.lifetime, self.data)
1086    }
1087
1088    pub fn into_typed<T>(self) -> Result<ManagedRefMut<T>, Self> {
1089        if self.type_hash == TypeHash::of::<T>() {
1090            unsafe { Ok(ManagedRefMut::new_raw(self.data.cast::<T>(), self.lifetime).unwrap()) }
1091        } else {
1092            Err(self)
1093        }
1094    }
1095
1096    pub fn type_hash(&self) -> &TypeHash {
1097        &self.type_hash
1098    }
1099
1100    pub fn lifetime(&self) -> &LifetimeRefMut {
1101        &self.lifetime
1102    }
1103
1104    pub fn borrow(&self) -> Option<DynamicManagedRef> {
1105        Some(DynamicManagedRef {
1106            type_hash: self.type_hash,
1107            lifetime: self.lifetime.borrow()?,
1108            data: self.data,
1109        })
1110    }
1111
1112    pub fn borrow_mut(&mut self) -> Option<DynamicManagedRefMut> {
1113        Some(DynamicManagedRefMut {
1114            type_hash: self.type_hash,
1115            lifetime: self.lifetime.borrow_mut()?,
1116            data: self.data,
1117        })
1118    }
1119
1120    pub fn is<T>(&self) -> bool {
1121        self.type_hash == TypeHash::of::<T>()
1122    }
1123
1124    pub fn read<T>(&self) -> Option<ValueReadAccess<T>> {
1125        if self.type_hash == TypeHash::of::<T>() {
1126            unsafe { self.lifetime.read_ptr(self.data.cast::<T>()) }
1127        } else {
1128            None
1129        }
1130    }
1131
1132    pub fn write<T>(&mut self) -> Option<ValueWriteAccess<T>> {
1133        if self.type_hash == TypeHash::of::<T>() {
1134            unsafe { self.lifetime.write_ptr(self.data.cast::<T>()) }
1135        } else {
1136            None
1137        }
1138    }
1139
1140    /// # Safety
1141    pub unsafe fn map<T, U>(self, f: impl FnOnce(&mut T) -> &mut U) -> Option<Self> {
1142        if self.type_hash == TypeHash::of::<T>() {
1143            unsafe {
1144                let data = f(&mut *self.data.cast::<T>());
1145                Some(Self {
1146                    type_hash: TypeHash::of::<U>(),
1147                    lifetime: self.lifetime,
1148                    data: data as *mut U as *mut u8,
1149                })
1150            }
1151        } else {
1152            None
1153        }
1154    }
1155
1156    /// # Safety
1157    pub unsafe fn try_map<T, U>(self, f: impl FnOnce(&mut T) -> Option<&mut U>) -> Option<Self> {
1158        if self.type_hash == TypeHash::of::<T>() {
1159            unsafe {
1160                let data = f(&mut *self.data.cast::<T>())?;
1161                Some(Self {
1162                    type_hash: TypeHash::of::<U>(),
1163                    lifetime: self.lifetime,
1164                    data: data as *mut U as *mut u8,
1165                })
1166            }
1167        } else {
1168            None
1169        }
1170    }
1171
1172    /// # Safety
1173    pub unsafe fn as_ptr<T>(&self) -> Option<*const T> {
1174        if self.type_hash == TypeHash::of::<T>() && self.lifetime.exists() {
1175            Some(self.data.cast::<T>())
1176        } else {
1177            None
1178        }
1179    }
1180
1181    /// # Safety
1182    pub unsafe fn as_mut_ptr<T>(&mut self) -> Option<*mut T> {
1183        if self.type_hash == TypeHash::of::<T>() && self.lifetime.exists() {
1184            Some(self.data.cast::<T>())
1185        } else {
1186            None
1187        }
1188    }
1189
1190    /// # Safety
1191    pub unsafe fn as_ptr_raw(&self) -> Option<*const u8> {
1192        if self.lifetime.exists() {
1193            Some(self.data)
1194        } else {
1195            None
1196        }
1197    }
1198
1199    /// # Safety
1200    pub unsafe fn as_mut_ptr_raw(&mut self) -> Option<*mut u8> {
1201        if self.lifetime.exists() {
1202            Some(self.data)
1203        } else {
1204            None
1205        }
1206    }
1207}
1208
1209impl TryFrom<DynamicManagedValue> for DynamicManagedRefMut {
1210    type Error = ();
1211
1212    fn try_from(value: DynamicManagedValue) -> Result<Self, Self::Error> {
1213        match value {
1214            DynamicManagedValue::RefMut(value) => Ok(value),
1215            _ => Err(()),
1216        }
1217    }
1218}
1219
1220pub struct DynamicManagedLazy {
1221    type_hash: TypeHash,
1222    lifetime: LifetimeLazy,
1223    data: *mut u8,
1224}
1225
1226unsafe impl Send for DynamicManagedLazy {}
1227unsafe impl Sync for DynamicManagedLazy {}
1228
1229impl Clone for DynamicManagedLazy {
1230    fn clone(&self) -> Self {
1231        Self {
1232            type_hash: self.type_hash,
1233            lifetime: self.lifetime.clone(),
1234            data: self.data,
1235        }
1236    }
1237}
1238
1239impl DynamicManagedLazy {
1240    pub fn new<T: ?Sized>(data: &mut T, lifetime: LifetimeLazy) -> Self {
1241        Self {
1242            type_hash: TypeHash::of::<T>(),
1243            lifetime,
1244            data: data as *mut T as *mut u8,
1245        }
1246    }
1247
1248    /// # Safety
1249    pub unsafe fn new_raw(
1250        type_hash: TypeHash,
1251        lifetime: LifetimeLazy,
1252        data: *mut u8,
1253    ) -> Option<Self> {
1254        if data.is_null() {
1255            None
1256        } else {
1257            Some(Self {
1258                type_hash,
1259                lifetime,
1260                data,
1261            })
1262        }
1263    }
1264
1265    pub fn make<T: ?Sized>(data: &mut T) -> (Self, Lifetime) {
1266        let result = Lifetime::default();
1267        (Self::new(data, result.lazy()), result)
1268    }
1269
1270    pub fn into_inner(self) -> (TypeHash, LifetimeLazy, *mut u8) {
1271        (self.type_hash, self.lifetime, self.data)
1272    }
1273
1274    pub fn into_typed<T>(self) -> Result<ManagedLazy<T>, Self> {
1275        if self.type_hash == TypeHash::of::<T>() {
1276            unsafe { Ok(ManagedLazy::new_raw(self.data.cast::<T>(), self.lifetime).unwrap()) }
1277        } else {
1278            Err(self)
1279        }
1280    }
1281
1282    pub fn type_hash(&self) -> &TypeHash {
1283        &self.type_hash
1284    }
1285
1286    pub fn lifetime(&self) -> &LifetimeLazy {
1287        &self.lifetime
1288    }
1289
1290    pub fn is<T>(&self) -> bool {
1291        self.type_hash == TypeHash::of::<T>()
1292    }
1293
1294    pub fn read<T>(&self) -> Option<ValueReadAccess<T>> {
1295        if self.type_hash == TypeHash::of::<T>() {
1296            unsafe { self.lifetime.read_ptr(self.data.cast::<T>()) }
1297        } else {
1298            None
1299        }
1300    }
1301
1302    pub fn write<T>(&self) -> Option<ValueWriteAccess<T>> {
1303        if self.type_hash == TypeHash::of::<T>() {
1304            unsafe { self.lifetime.write_ptr(self.data.cast::<T>()) }
1305        } else {
1306            None
1307        }
1308    }
1309
1310    pub fn borrow(&self) -> Option<DynamicManagedRef> {
1311        Some(DynamicManagedRef {
1312            type_hash: self.type_hash,
1313            lifetime: self.lifetime.borrow()?,
1314            data: self.data,
1315        })
1316    }
1317
1318    pub fn borrow_mut(&mut self) -> Option<DynamicManagedRefMut> {
1319        Some(DynamicManagedRefMut {
1320            type_hash: self.type_hash,
1321            lifetime: self.lifetime.borrow_mut()?,
1322            data: self.data,
1323        })
1324    }
1325
1326    /// # Safety
1327    pub unsafe fn map<T, U>(self, f: impl FnOnce(&mut T) -> &mut U) -> Option<Self> {
1328        if self.type_hash == TypeHash::of::<T>() {
1329            unsafe {
1330                let data = f(&mut *self.data.cast::<T>());
1331                Some(Self {
1332                    type_hash: TypeHash::of::<U>(),
1333                    lifetime: self.lifetime,
1334                    data: data as *mut U as *mut u8,
1335                })
1336            }
1337        } else {
1338            None
1339        }
1340    }
1341
1342    /// # Safety
1343    pub unsafe fn try_map<T, U>(self, f: impl FnOnce(&mut T) -> Option<&mut U>) -> Option<Self> {
1344        if self.type_hash == TypeHash::of::<T>() {
1345            unsafe {
1346                let data = f(&mut *self.data.cast::<T>())?;
1347                Some(Self {
1348                    type_hash: TypeHash::of::<U>(),
1349                    lifetime: self.lifetime,
1350                    data: data as *mut U as *mut u8,
1351                })
1352            }
1353        } else {
1354            None
1355        }
1356    }
1357
1358    /// # Safety
1359    pub unsafe fn as_ptr<T>(&self) -> Option<*const T> {
1360        if self.type_hash == TypeHash::of::<T>() && self.lifetime.exists() {
1361            Some(self.data.cast::<T>())
1362        } else {
1363            None
1364        }
1365    }
1366
1367    /// # Safety
1368    pub unsafe fn as_mut_ptr<T>(&self) -> Option<*mut T> {
1369        if self.type_hash == TypeHash::of::<T>() && self.lifetime.exists() {
1370            Some(self.data.cast::<T>())
1371        } else {
1372            None
1373        }
1374    }
1375
1376    /// # Safety
1377    pub unsafe fn as_ptr_raw(&self) -> Option<*const u8> {
1378        if self.lifetime.exists() {
1379            Some(self.data)
1380        } else {
1381            None
1382        }
1383    }
1384
1385    /// # Safety
1386    pub unsafe fn as_mut_ptr_raw(&mut self) -> Option<*mut u8> {
1387        if self.lifetime.exists() {
1388            Some(self.data)
1389        } else {
1390            None
1391        }
1392    }
1393}
1394
1395impl TryFrom<DynamicManagedValue> for DynamicManagedLazy {
1396    type Error = ();
1397
1398    fn try_from(value: DynamicManagedValue) -> Result<Self, Self::Error> {
1399        match value {
1400            DynamicManagedValue::Lazy(value) => Ok(value),
1401            _ => Err(()),
1402        }
1403    }
1404}
1405
1406pub enum DynamicManagedValue {
1407    Owned(DynamicManaged),
1408    Ref(DynamicManagedRef),
1409    RefMut(DynamicManagedRefMut),
1410    Lazy(DynamicManagedLazy),
1411}
1412
1413impl DynamicManagedValue {
1414    pub fn as_owned(&self) -> Option<&DynamicManaged> {
1415        match self {
1416            Self::Owned(value) => Some(value),
1417            _ => None,
1418        }
1419    }
1420
1421    pub fn as_mut_owned(&mut self) -> Option<&mut DynamicManaged> {
1422        match self {
1423            Self::Owned(value) => Some(value),
1424            _ => None,
1425        }
1426    }
1427
1428    pub fn as_ref(&self) -> Option<&DynamicManagedRef> {
1429        match self {
1430            Self::Ref(value) => Some(value),
1431            _ => None,
1432        }
1433    }
1434
1435    pub fn as_mut_ref(&mut self) -> Option<&mut DynamicManagedRef> {
1436        match self {
1437            Self::Ref(value) => Some(value),
1438            _ => None,
1439        }
1440    }
1441
1442    pub fn as_ref_mut(&self) -> Option<&DynamicManagedRefMut> {
1443        match self {
1444            Self::RefMut(value) => Some(value),
1445            _ => None,
1446        }
1447    }
1448
1449    pub fn as_mut_ref_mut(&mut self) -> Option<&mut DynamicManagedRefMut> {
1450        match self {
1451            Self::RefMut(value) => Some(value),
1452            _ => None,
1453        }
1454    }
1455
1456    pub fn as_lazy(&self) -> Option<&DynamicManagedLazy> {
1457        match self {
1458            Self::Lazy(value) => Some(value),
1459            _ => None,
1460        }
1461    }
1462
1463    pub fn as_mut_lazy(&mut self) -> Option<&mut DynamicManagedLazy> {
1464        match self {
1465            Self::Lazy(value) => Some(value),
1466            _ => None,
1467        }
1468    }
1469
1470    pub fn read<T>(&self) -> Option<ValueReadAccess<T>> {
1471        match self {
1472            Self::Owned(value) => value.read::<T>(),
1473            Self::Ref(value) => value.read::<T>(),
1474            Self::RefMut(value) => value.read::<T>(),
1475            Self::Lazy(value) => value.read::<T>(),
1476        }
1477    }
1478
1479    pub fn write<T>(&mut self) -> Option<ValueWriteAccess<T>> {
1480        match self {
1481            Self::Owned(value) => value.write::<T>(),
1482            Self::RefMut(value) => value.write::<T>(),
1483            Self::Lazy(value) => value.write::<T>(),
1484            _ => None,
1485        }
1486    }
1487
1488    pub fn borrow(&self) -> Option<DynamicManagedRef> {
1489        match self {
1490            Self::Owned(value) => value.borrow(),
1491            Self::Ref(value) => value.borrow(),
1492            Self::RefMut(value) => value.borrow(),
1493            _ => None,
1494        }
1495    }
1496
1497    pub fn borrow_mut(&mut self) -> Option<DynamicManagedRefMut> {
1498        match self {
1499            Self::Owned(value) => value.borrow_mut(),
1500            Self::RefMut(value) => value.borrow_mut(),
1501            _ => None,
1502        }
1503    }
1504
1505    pub fn lazy(&self) -> Option<DynamicManagedLazy> {
1506        match self {
1507            Self::Owned(value) => Some(value.lazy()),
1508            Self::Lazy(value) => Some(value.clone()),
1509            _ => None,
1510        }
1511    }
1512}
1513
1514impl From<DynamicManaged> for DynamicManagedValue {
1515    fn from(value: DynamicManaged) -> Self {
1516        Self::Owned(value)
1517    }
1518}
1519
1520impl From<DynamicManagedRef> for DynamicManagedValue {
1521    fn from(value: DynamicManagedRef) -> Self {
1522        Self::Ref(value)
1523    }
1524}
1525
1526impl From<DynamicManagedRefMut> for DynamicManagedValue {
1527    fn from(value: DynamicManagedRefMut) -> Self {
1528        Self::RefMut(value)
1529    }
1530}
1531
1532impl From<DynamicManagedLazy> for DynamicManagedValue {
1533    fn from(value: DynamicManagedLazy) -> Self {
1534        Self::Lazy(value)
1535    }
1536}
1537
1538#[cfg(test)]
1539mod tests {
1540    use super::*;
1541    use std::any::Any;
1542
1543    fn is_async<T: Send + Sync + ?Sized>() {}
1544
1545    #[test]
1546    fn test_managed() {
1547        is_async::<Managed<()>>();
1548        is_async::<ManagedRef<()>>();
1549        is_async::<ManagedRefMut<()>>();
1550        is_async::<ManagedLazy<()>>();
1551
1552        let mut value = Managed::new(42);
1553        let mut value_ref = value.borrow_mut().unwrap();
1554        assert!(value_ref.write().is_some());
1555        let mut value_ref2 = value_ref.borrow_mut().unwrap();
1556        assert!(value_ref.write().is_some());
1557        assert!(value_ref2.write().is_some());
1558        drop(value_ref);
1559        let value_ref = value.borrow().unwrap();
1560        assert!(value.borrow().is_some());
1561        assert!(value.borrow_mut().is_none());
1562        drop(value_ref);
1563        assert!(value.borrow().is_some());
1564        assert!(value.borrow_mut().is_some());
1565        *value.write().unwrap() = 40;
1566        assert_eq!(*value.read().unwrap(), 40);
1567        *value.borrow_mut().unwrap().write().unwrap() = 2;
1568        assert_eq!(*value.read().unwrap(), 2);
1569        let value_ref = value.borrow().unwrap();
1570        let value_ref2 = value_ref.borrow().unwrap();
1571        drop(value_ref);
1572        assert!(value_ref2.read().is_some());
1573        let value_ref = value.borrow().unwrap();
1574        let value_lazy = value.lazy();
1575        assert_eq!(*value_lazy.read().unwrap(), 2);
1576        *value_lazy.write().unwrap() = 42;
1577        assert_eq!(*value_lazy.read().unwrap(), 42);
1578        drop(value);
1579        assert!(value_ref.read().is_none());
1580        assert!(value_ref2.read().is_none());
1581        assert!(value_lazy.read().is_none());
1582    }
1583
1584    #[test]
1585    fn test_dynamic_managed() {
1586        is_async::<DynamicManaged>();
1587        is_async::<DynamicManagedRef>();
1588        is_async::<DynamicManagedRefMut>();
1589        is_async::<DynamicManagedLazy>();
1590
1591        let mut value = DynamicManaged::new(42).unwrap();
1592        let mut value_ref = value.borrow_mut().unwrap();
1593        assert!(value_ref.write::<i32>().is_some());
1594        let mut value_ref2 = value_ref.borrow_mut().unwrap();
1595        assert!(value_ref.write::<i32>().is_some());
1596        assert!(value_ref2.write::<i32>().is_some());
1597        drop(value_ref);
1598        let value_ref = value.borrow().unwrap();
1599        assert!(value.borrow().is_some());
1600        assert!(value.borrow_mut().is_none());
1601        drop(value_ref);
1602        assert!(value.borrow().is_some());
1603        assert!(value.borrow_mut().is_some());
1604        *value.write::<i32>().unwrap() = 40;
1605        assert_eq!(*value.read::<i32>().unwrap(), 40);
1606        *value.borrow_mut().unwrap().write::<i32>().unwrap() = 2;
1607        assert_eq!(*value.read::<i32>().unwrap(), 2);
1608        let value_ref = value.borrow().unwrap();
1609        let value_ref2 = value_ref.borrow().unwrap();
1610        drop(value_ref);
1611        assert!(value_ref2.read::<i32>().is_some());
1612        let value_ref = value.borrow().unwrap();
1613        let value_lazy = value.lazy();
1614        assert_eq!(*value_lazy.read::<i32>().unwrap(), 2);
1615        *value_lazy.write::<i32>().unwrap() = 42;
1616        assert_eq!(*value_lazy.read::<i32>().unwrap(), 42);
1617        drop(value);
1618        assert!(value_ref.read::<i32>().is_none());
1619        assert!(value_ref2.read::<i32>().is_none());
1620        assert!(value_lazy.read::<i32>().is_none());
1621        let value = DynamicManaged::new("hello".to_owned()).unwrap();
1622        let value = value.consume::<String>().ok().unwrap();
1623        assert_eq!(value.as_str(), "hello");
1624    }
1625
1626    #[test]
1627    fn test_conversion() {
1628        let value = Managed::new(42);
1629        assert_eq!(*value.read().unwrap(), 42);
1630        let value = value.into_dynamic().unwrap();
1631        assert_eq!(*value.read::<i32>().unwrap(), 42);
1632        let mut value = value.into_typed::<i32>().ok().unwrap();
1633        assert_eq!(*value.read().unwrap(), 42);
1634
1635        let value_ref = value.borrow().unwrap();
1636        assert_eq!(*value.read().unwrap(), 42);
1637        let value_ref = value_ref.into_dynamic();
1638        assert_eq!(*value_ref.read::<i32>().unwrap(), 42);
1639        let value_ref = value_ref.into_typed::<i32>().ok().unwrap();
1640        assert_eq!(*value_ref.read().unwrap(), 42);
1641        drop(value_ref);
1642
1643        let value_ref_mut = value.borrow_mut().unwrap();
1644        assert_eq!(*value.read().unwrap(), 42);
1645        let value_ref_mut = value_ref_mut.into_dynamic();
1646        assert_eq!(*value_ref_mut.read::<i32>().unwrap(), 42);
1647        let value_ref_mut = value_ref_mut.into_typed::<i32>().ok().unwrap();
1648        assert_eq!(*value_ref_mut.read().unwrap(), 42);
1649
1650        let value_lazy = value.lazy();
1651        assert_eq!(*value.read().unwrap(), 42);
1652        let value_lazy = value_lazy.into_dynamic();
1653        assert_eq!(*value_lazy.read::<i32>().unwrap(), 42);
1654        let value_lazy = value_lazy.into_typed::<i32>().ok().unwrap();
1655        assert_eq!(*value_lazy.read().unwrap(), 42);
1656    }
1657
1658    #[test]
1659    fn test_unsized() {
1660        let lifetime = Lifetime::default();
1661        let mut data = 42usize;
1662        {
1663            let foo = ManagedRef::<dyn Any>::new(&data, lifetime.borrow().unwrap());
1664            assert_eq!(
1665                *foo.read().unwrap().downcast_ref::<usize>().unwrap(),
1666                42usize
1667            );
1668        }
1669        {
1670            let mut foo = ManagedRefMut::<dyn Any>::new(&mut data, lifetime.borrow_mut().unwrap());
1671            *foo.write().unwrap().downcast_mut::<usize>().unwrap() = 100;
1672        }
1673        {
1674            let foo = ManagedLazy::<dyn Any>::new(&mut data, lifetime.lazy());
1675            assert_eq!(
1676                *foo.read().unwrap().downcast_ref::<usize>().unwrap(),
1677                100usize
1678            );
1679        }
1680
1681        let lifetime = Lifetime::default();
1682        let mut data = [0, 1, 2, 3];
1683        {
1684            let foo = ManagedRef::<[i32]>::new(&data, lifetime.borrow().unwrap());
1685            assert_eq!(*foo.read().unwrap(), [0, 1, 2, 3]);
1686        }
1687        {
1688            let mut foo = ManagedRefMut::<[i32]>::new(&mut data, lifetime.borrow_mut().unwrap());
1689            foo.write().unwrap().sort_by(|a, b| a.cmp(b).reverse());
1690        }
1691        {
1692            let foo = ManagedLazy::<[i32]>::new(&mut data, lifetime.lazy());
1693            assert_eq!(*foo.read().unwrap(), [3, 2, 1, 0]);
1694        }
1695    }
1696
1697    #[test]
1698    fn test_moves() {
1699        let mut value = Managed::new(42);
1700        assert_eq!(*value.read().unwrap(), 42);
1701        {
1702            let value_ref = value.borrow_mut().unwrap();
1703            Managed::new(1).move_into_ref(value_ref).ok().unwrap();
1704            assert_eq!(*value.read().unwrap(), 1);
1705        }
1706        {
1707            let value_lazy = value.lazy();
1708            Managed::new(2).move_into_lazy(value_lazy).ok().unwrap();
1709            assert_eq!(*value.read().unwrap(), 2);
1710        }
1711
1712        let mut value = DynamicManaged::new(42).unwrap();
1713        assert_eq!(*value.read::<i32>().unwrap(), 42);
1714        {
1715            let value_ref = value.borrow_mut().unwrap();
1716            DynamicManaged::new(1)
1717                .unwrap()
1718                .move_into_ref(value_ref)
1719                .ok()
1720                .unwrap();
1721            assert_eq!(*value.read::<i32>().unwrap(), 1);
1722        }
1723        {
1724            let value_lazy = value.lazy();
1725            DynamicManaged::new(2)
1726                .unwrap()
1727                .move_into_lazy(value_lazy)
1728                .ok()
1729                .unwrap();
1730            assert_eq!(*value.read::<i32>().unwrap(), 2);
1731        }
1732    }
1733
1734    #[test]
1735    fn test_move_invalidation() {
1736        let value = Managed::new(42);
1737        let value_ref = value.borrow().unwrap();
1738        assert_eq!(value.lifetime().tag(), value_ref.lifetime().tag());
1739        assert!(value_ref.lifetime().exists());
1740        let value = Box::new(value);
1741        assert_ne!(value.lifetime().tag(), value_ref.lifetime().tag());
1742        assert!(!value_ref.lifetime().exists());
1743        let value = *value;
1744        assert_ne!(value.lifetime().tag(), value_ref.lifetime().tag());
1745        assert!(!value_ref.lifetime().exists());
1746    }
1747}