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