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