intuicio_data/
managed.rs

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