1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! Frames store GC roots.
//!
//! Several frame types exist in jlrs. They all implement the [`Frame`] trait, which provides
//! methods that return info about that frame, like its capacity and current number of roots,
//! methods to reserve a new [`Output`] or [`ReusableSlot`], and methods to create a nested
//! scope with its own frame. Only [`AsyncGcFrame`] provides additional public methods.
//!
//! See the [`memory`] module for more information.
//!
//! [`Scope`]: crate::memory::scope::Scope
//! [`PartialScope`]: crate::memory::scope::PartialScope
//! [`CallAsync`]: crate::call::CallAsync
//! [`memory`]: crate::memory

use self::private::FrameOwner;
use crate::{
    error::JlrsResult,
    memory::{
        mode::Mode,
        output::Output,
        reusable_slot::ReusableSlot,
        stack_page::{Slot, StackPage},
    },
    private::Private,
};
use jl_sys::jl_value_t;
use std::ptr::NonNull;

pub(crate) const MIN_FRAME_CAPACITY: usize = 16;

pub(crate) struct FrameSlice<'frame> {
    raw_frame: &'frame [Slot],
    size: usize,
}

impl<'frame> FrameSlice<'frame> {
    // Safety: The slots must have been reserved in an existing frame and must have been set to
    // null.
    pub(crate) unsafe fn new(slots: &'frame [Slot]) -> Self {
        FrameSlice {
            raw_frame: slots,
            size: 0,
        }
    }
}

/// A frame that can be used to root Julia data.
///
/// Frames created with a capacity can store at least that number of roots. A frame's capacity is
/// at least 16.
pub struct GcFrame<'frame, M: Mode> {
    raw_frame: &'frame [Slot],
    page: Option<StackPage>,
    mode: M,
}

impl<'frame, M: Mode> GcFrame<'frame, M> {
    // Safety: frames must form a single nested hierarchy. A new frame owner must only be created
    // when entering a new scope.
    pub(crate) unsafe fn new(raw_frame: &'frame [Slot], mode: M) -> (Self, FrameOwner<'frame, M>) {
        let owner = FrameOwner::new(raw_frame, mode);
        let frame = GcFrame {
            raw_frame,
            page: None,
            mode,
        };

        (frame, owner)
    }

    // Safety: capacity >= n_slots, the n_roots pointers the garbage collector
    // can see must point to valid Julia data or be null pointers.
    pub(crate) unsafe fn set_n_roots(&self, n_roots: usize) {
        debug_assert!(self.capacity() >= n_roots);
        self.raw_frame.get_unchecked(0).set((n_roots << 2) as _);
    }

    // Safety: capacity > n_roots, value must point to valid Julia data
    pub(crate) unsafe fn root(&self, value: NonNull<jl_value_t>) {
        debug_assert!(self.n_roots() < self.capacity());

        let n_roots = self.n_roots();
        self.raw_frame
            .get_unchecked(n_roots + 2)
            .set(value.cast().as_ptr());
        self.set_n_roots(n_roots + 1);
    }
}

cfg_if::cfg_if! {
    if #[cfg(feature = "ccall")] {
        use crate::{ccall::CCall, error::AllocError};
        use std::marker::PhantomData;

        /// A frame that can't store any roots or be nested.
        ///
        /// A `NullFrame` can be used if you call Rust from Julia through `ccall` and want to
        /// borrow array data but not perform any allocations.
        pub struct NullFrame<'frame>(PhantomData<&'frame ()>);

        impl<'frame> NullFrame<'frame> {
            // Safety: frames must form a single nested hierarchy.
            pub(crate) unsafe fn new(_: &'frame CCall) -> Self {
                NullFrame(PhantomData)
            }
        }
    }
}

cfg_if::cfg_if! {
    if #[cfg(feature = "async")] {
        use super::mode::Async;
        use std::future::Future;

        /// A frame that can be used to root Julia data and call async methods.
        ///
        /// Frames created with a capacity can store at least that number of roots. A frame's
        /// capacity is at least 16.
        pub struct AsyncGcFrame<'frame> {
            raw_frame: &'frame [Slot],
            page: Option<StackPage>,
            mode: Async<'frame>,
            _marker: PhantomData<&'frame mut &'frame ()>
        }

        impl<'frame> AsyncGcFrame<'frame> {
            /// An async version of [`Frame::scope`].
            ///
            /// The closure `func` must return an async block. Note that the returned value is
            /// required to live at least as long the current frame.
            #[inline(never)]
            pub async fn async_scope<'nested, T, F, G>(&'nested mut self, func: F) -> JlrsResult<T>
            where
                T: 'frame,
                G: Future<Output = JlrsResult<T>>,
                F:  FnOnce(AsyncGcFrame<'nested>) -> G,
            {
                // Safety: the lifetime of the borrow is extended, but it's valid during the call
                // to func and data returned from func must live longer.
                let (nested, owner) = self.nest_async(0);
                let ret =  func(nested).await;
                std::mem::drop(owner);
                ret
            }

            /// An async version of [`Frame::scope_with_capacity`].
            ///
            /// The closure `func` must return an async block. Note that the returned value is
            /// required to live at least as long the current frame.
            #[inline(never)]
            pub async fn async_scope_with_capacity<'nested, T, F, G>(
                &'nested mut self,
                capacity: usize,
                func: F,
            ) -> JlrsResult<T>
            where
                T: 'frame,
                G: Future<Output = JlrsResult<T>>,
                F: FnOnce(AsyncGcFrame<'nested>) -> G,
            {
                // Safety: the lifetime of the borrow is extended, but it's valid during the call
                // to func and data returned from func must live longer.
                let (nested, owner) = self.nest_async(capacity);
                let ret =  func(nested).await;
                std::mem::drop(owner);
                ret
            }

            /// `AsyncFrame::async_scope` with less strict lifeitme bounds on the return value.
            ///
            /// Safety: because this method only requires that the returned data lives at least as
            /// long as the borow of `self`, it's possible to return data rooted in that scope.
            #[inline(never)]
            pub async unsafe fn relaxed_async_scope<'nested, T, F, G>(&'nested mut self, func: F) -> JlrsResult<T>
            where
                T: 'nested,
                G: Future<Output = JlrsResult<T>>,
                F: FnOnce(AsyncGcFrame<'nested>) -> G,
            {
                let (nested, owner) = self.nest_async(0);
                let ret =  func(nested).await;
                std::mem::drop(owner);
                ret
            }

            /// `AsyncFrame::async_scope_wit_capacity` with less strict lifeitme bounds on the
            /// return value.
            ///
            /// Safety: because this method only requires that the returned data lives at least as
            /// long as the borow of `self`, it's possible to return data rooted in that scope.
            #[inline(never)]
            pub async unsafe fn relaxed_async_scope_with_capacity<'nested, T, F, G>(
                &'nested mut self,
                capacity: usize,
                func: F,
            ) -> JlrsResult<T>
            where
                T: 'nested,
                G: Future<Output = JlrsResult<T>>,
                F: for<'n> FnOnce(AsyncGcFrame<'n>) -> G,
            {
                let (nested, owner) = self.nest_async(capacity);
                let ret =  func(nested).await;
                std::mem::drop(owner);
                ret
            }

            // Safety: frames must form a single nested hierarchy. A new frame owner must only be
            // created when entering a new scope.
            pub(crate) unsafe fn new(
                raw_frame: &'frame [Slot],
                mode: Async<'frame>,
            ) -> (Self, FrameOwner<'frame, Async<'frame>>) {
                // Is popped when this frame is dropped
                let owner = FrameOwner::new(raw_frame, mode);
                let frame = AsyncGcFrame {
                    raw_frame,
                    page: None,
                    mode,
                    _marker: PhantomData
                };

                (frame, owner)
            }

            pub(crate) fn nest_async<'nested>(
                &'nested mut self,
                capacity: usize,
            ) -> (AsyncGcFrame<'nested>, FrameOwner<'nested, Async<'nested>>) {
                let used = self.n_roots() + 2;
                let new_frame_size = MIN_FRAME_CAPACITY.max(capacity) + 2;
                let raw_frame = if self.page.is_some() {
                    // Safety: page is some
                    unsafe {
                        if new_frame_size <= self.page.as_ref().unwrap_unchecked().size() {
                            self.page.as_ref().unwrap_unchecked().as_ref()
                        } else {
                            self.page = Some(StackPage::new(new_frame_size));
                            self.page.as_ref().unwrap_unchecked().as_ref()
                        }
                    }
                } else if used + new_frame_size <= self.raw_frame.len() {
                    &self.raw_frame[used..]
                } else {
                    self.page = Some(StackPage::new(new_frame_size));
                    // Safety: page is some
                    unsafe { self.page.as_ref().unwrap_unchecked().as_ref() }
                };

                // Safety: nested hierarchy is maintained
                unsafe { AsyncGcFrame::new(raw_frame, self.mode) }
            }

            // Safety: capacity >= n_slots, the n_roots pointers the garbage collector
            // can see must point to valid Julia data or be null pointers.
            pub(crate) unsafe fn set_n_roots(&self, n_slots: usize) {
                debug_assert!(n_slots <= self.capacity());
                self.raw_frame.get_unchecked(0).set((n_slots << 2) as _);
            }

            // Safety: capacity > n_roots, value must point to valid Julia data
            pub(crate) unsafe fn root(&self, value: NonNull<jl_value_t>) {
                debug_assert!(self.n_roots() < self.capacity());

                let n_roots = self.n_roots();
                self.raw_frame
                    .get_unchecked(n_roots + 2)
                    .set(value.cast().as_ptr());
                self.set_n_roots(n_roots + 1);
            }
        }

        impl<'frame> Frame<'frame> for AsyncGcFrame<'frame> {
            fn reusable_slot(&mut self) -> JlrsResult<ReusableSlot<'frame>> {
                // Safety: the slot can only be used while the frame exists.
                unsafe {
                    let slot = <Self as private::FramePriv>::reserve_slot(self, Private)?;
                    Ok(ReusableSlot::new(slot))
                }
            }

            fn n_roots(&self) -> usize {
                self.raw_frame[0].get() as usize >> 2
            }

            fn capacity(&self) -> usize {
                self.raw_frame.len() - 2
            }

            fn output(&mut self) -> JlrsResult<Output<'frame>> {
                // Safety: the slot can only be used while the frame exists.
                unsafe {
                    let slot = <Self as private::FramePriv>::reserve_slot(self, Private)?;
                    Ok(Output::new(slot))
                }
            }
        }
    }
}

/// Functionality shared by the different frame types.
pub trait Frame<'frame>: private::FramePriv<'frame> {
    /// Convert the frame to a scope.
    ///
    /// This method takes a mutable reference to a frame and returns it, it can be used as an
    /// alternative to borrowing a frame with when a [`Scope`] or [`PartialScope`] is needed.
    ///
    /// [`Scope`]: crate::memory::scope::Scope
    /// [`PartialScope`]: crate::memory::scope::PartialScope
    fn as_scope(&mut self) -> &mut Self {
        self
    }

    /// Reserve a new output in the current frame.
    ///
    /// Returns an error if the frame is full.
    fn output(&mut self) -> JlrsResult<Output<'frame>>;

    /// Reserve a new reusable slot in the current frame.
    ///
    /// Returns an error if the frame is full.
    fn reusable_slot(&mut self) -> JlrsResult<ReusableSlot<'frame>>;

    /// Returns the number of values currently rooted in this frame.
    fn n_roots(&self) -> usize;

    /// Returns the maximum number of values that can be rooted in this frame.
    fn capacity(&self) -> usize;

    /// Create a new scope and call func with that scope's frame.
    ///
    /// The frame can store at least 16 roots.
    #[inline(never)]
    fn scope<T, F>(&mut self, func: F) -> JlrsResult<T>
    where
        for<'inner> F: FnOnce(GcFrame<'inner, Self::Mode>) -> JlrsResult<T>,
    {
        let (nested, owner) = self.nest(0, Private);
        let ret = func(nested);
        std::mem::drop(owner);
        ret
    }

    /// Create a new scope and call func with that scope's frame.
    ///
    /// The frame can store at least `capacity` roots.
    #[inline(never)]
    fn scope_with_capacity<T, F>(&mut self, capacity: usize, func: F) -> JlrsResult<T>
    where
        for<'inner> F: FnOnce(GcFrame<'inner, Self::Mode>) -> JlrsResult<T>,
    {
        let (nested, owner) = self.nest(capacity, Private);
        let ret = func(nested);
        std::mem::drop(owner);
        ret
    }
}

impl<'frame, M: Mode> Frame<'frame> for GcFrame<'frame, M> {
    fn reusable_slot(&mut self) -> JlrsResult<ReusableSlot<'frame>> {
        // Safety: the slot can only be used while the frame exists.
        unsafe {
            let slot = <Self as private::FramePriv>::reserve_slot(self, Private)?;
            Ok(ReusableSlot::new(slot))
        }
    }

    fn n_roots(&self) -> usize {
        self.raw_frame[0].get() as usize >> 2
    }

    fn capacity(&self) -> usize {
        self.raw_frame.len() - 2
    }

    fn output(&mut self) -> JlrsResult<Output<'frame>> {
        // Safety: the slot can only be used while the frame exists.
        unsafe {
            let slot = <Self as private::FramePriv>::reserve_slot(self, Private)?;
            Ok(Output::new(slot))
        }
    }
}

impl<'frame> Frame<'frame> for FrameSlice<'frame> {
    fn reusable_slot(&mut self) -> JlrsResult<ReusableSlot<'frame>> {
        unimplemented!()
    }

    fn n_roots(&self) -> usize {
        self.size
    }

    fn capacity(&self) -> usize {
        self.raw_frame.len()
    }

    fn output(&mut self) -> JlrsResult<Output<'frame>> {
        unimplemented!()
    }
}

#[cfg(feature = "ccall")]
impl<'frame> Frame<'frame> for NullFrame<'frame> {
    fn reusable_slot(&mut self) -> JlrsResult<ReusableSlot<'frame>> {
        Err(AllocError::NullFrame)?
    }

    fn n_roots(&self) -> usize {
        0
    }

    fn capacity(&self) -> usize {
        0
    }

    fn scope<T, F>(&mut self, _func: F) -> JlrsResult<T>
    where
        for<'inner> F: FnOnce(GcFrame<'inner, Self::Mode>) -> JlrsResult<T>,
    {
        Err(AllocError::NullFrame)?
    }

    fn scope_with_capacity<T, F>(&mut self, _capacity: usize, _func: F) -> JlrsResult<T>
    where
        for<'inner> F: FnOnce(GcFrame<'inner, Self::Mode>) -> JlrsResult<T>,
    {
        Err(AllocError::NullFrame)?
    }

    fn output(&mut self) -> JlrsResult<Output<'frame>> {
        Err(AllocError::NullFrame)?
    }
}

pub(crate) mod private {
    use crate::{
        error::{AllocError, JlrsResult},
        memory::{
            frame::{Frame, GcFrame, MIN_FRAME_CAPACITY},
            mode::Mode,
            stack_page::{Slot, StackPage},
        },
        private::Private,
        wrappers::ptr::private::WrapperPriv,
    };
    #[cfg(feature = "async")]
    use std::marker::PhantomData;
    use std::ptr::{null_mut, NonNull};

    use super::FrameSlice;

    pub struct FrameOwner<'frame, M: Mode> {
        mode: M,
        raw_frame: &'frame [Slot],
    }

    impl<'frame, M: Mode> FrameOwner<'frame, M> {
        // Only one owner must be created for a frame.
        pub(crate) unsafe fn new(raw_frame: &'frame [Slot], mode: M) -> Self {
            mode.push_frame(raw_frame, Private);
            FrameOwner { mode, raw_frame }
        }
    }

    #[cfg(feature = "async")]
    impl<'frame> FrameOwner<'frame, Async<'frame>> {
        // Safety: only one `AsyncGcFrame` must exist at a time
        pub(crate) unsafe fn reconstruct(&self) -> AsyncGcFrame<'frame> {
            AsyncGcFrame {
                raw_frame: self.raw_frame,
                page: None,
                mode: self.mode,
                _marker: PhantomData,
            }
        }
    }

    impl<M: Mode> Drop for FrameOwner<'_, M> {
        fn drop(&mut self) {
            unsafe { self.mode.pop_frame(self.raw_frame, Private) }
        }
    }

    pub trait FramePriv<'frame> {
        type Mode: Mode;
        // protect the value from being garbage collected while this frame is active.
        // safety: the value must be a valid pointer to a Julia value.
        unsafe fn push_root<'data, T: WrapperPriv<'frame, 'data>>(
            &mut self,
            value: NonNull<T::Wraps>,
            _: Private,
        ) -> Result<T, AllocError>;

        // safety: this slot must only be used while the frame exists.
        unsafe fn reserve_slot(&mut self, _: Private) -> JlrsResult<&'frame Slot>;

        unsafe fn reserve_slots<'borrow>(
            &'borrow mut self,
            slots: usize,
            _: Private,
        ) -> JlrsResult<&'frame [Slot]>;

        fn nest<'nested>(
            &'nested mut self,
            capacity: usize,
            _: Private,
        ) -> (
            GcFrame<'nested, Self::Mode>,
            FrameOwner<'nested, Self::Mode>,
        );
    }

    impl<'frame, M: Mode> FramePriv<'frame> for GcFrame<'frame, M> {
        type Mode = M;

        unsafe fn push_root<'data, T: WrapperPriv<'frame, 'data>>(
            &mut self,
            value: NonNull<T::Wraps>,
            _: Private,
        ) -> Result<T, AllocError> {
            let n_roots = self.n_roots();
            if n_roots == self.capacity() {
                Err(AllocError::Full { cap: n_roots })?
            }

            self.root(value.cast());
            Ok(T::wrap_non_null(value, Private))
        }

        unsafe fn reserve_slot(&mut self, _: Private) -> JlrsResult<&'frame Slot> {
            let n_roots = self.n_roots();
            if n_roots == self.capacity() {
                Err(AllocError::Full { cap: n_roots })?
            }

            self.raw_frame.get_unchecked(n_roots + 2).set(null_mut());
            self.set_n_roots(n_roots + 1);

            Ok(self.raw_frame.get_unchecked(n_roots + 2))
        }

        unsafe fn reserve_slots<'borrow>(
            &'borrow mut self,
            slots: usize,
            _: Private,
        ) -> JlrsResult<&'frame [Slot]> {
            let n_roots = self.n_roots();
            if n_roots + slots >= self.capacity() {
                Err(AllocError::Full { cap: n_roots })?
            }

            for i in 0..slots {
                self.raw_frame
                    .get_unchecked(n_roots + i + 2)
                    .set(null_mut());
            }

            self.set_n_roots(n_roots + slots);
            Ok(self.raw_frame[n_roots + 2..n_roots + slots + 2].as_ref())
        }

        fn nest<'nested>(
            &'nested mut self,
            capacity: usize,
            _: Private,
        ) -> (
            GcFrame<'nested, Self::Mode>,
            FrameOwner<'nested, Self::Mode>,
        ) {
            let used = self.n_roots() + 2;
            let new_frame_size = MIN_FRAME_CAPACITY.max(capacity) + 2;
            let raw_frame = if self.page.is_some() {
                // Safety: page is some
                unsafe {
                    if new_frame_size <= self.page.as_ref().unwrap_unchecked().size() {
                        self.page.as_ref().unwrap_unchecked().as_ref()
                    } else {
                        self.page = Some(StackPage::new(new_frame_size));
                        self.page.as_ref().unwrap_unchecked().as_ref()
                    }
                }
            } else if used + new_frame_size <= self.raw_frame.len() {
                &self.raw_frame[used..]
            } else {
                self.page = Some(StackPage::new(new_frame_size));
                // Safety: page is some
                unsafe { self.page.as_ref().unwrap_unchecked().as_ref() }
            };

            // Safety: nested hierarchy is maintained
            unsafe { GcFrame::new(raw_frame, self.mode) }
        }
    }

    impl<'frame> FramePriv<'frame> for FrameSlice<'frame> {
        type Mode = crate::memory::mode::Sync;

        unsafe fn push_root<'data, T: WrapperPriv<'frame, 'data>>(
            &mut self,
            value: NonNull<T::Wraps>,
            _: Private,
        ) -> Result<T, AllocError> {
            let n_roots = self.size;
            if n_roots == self.raw_frame.len() {
                Err(AllocError::Full { cap: n_roots })?
            }

            self.raw_frame
                .get_unchecked(self.size)
                .set(value.as_ptr().cast());
            self.size += 1;
            Ok(T::wrap_non_null(value, Private))
        }

        unsafe fn reserve_slot(&mut self, _: Private) -> JlrsResult<&'frame Slot> {
            unimplemented!()
        }

        unsafe fn reserve_slots<'borrow>(
            &'borrow mut self,
            _: usize,
            _: Private,
        ) -> JlrsResult<&'frame [Slot]> {
            unimplemented!()
        }

        fn nest<'nested>(
            &'nested mut self,
            _: usize,
            _: Private,
        ) -> (
            GcFrame<'nested, Self::Mode>,
            FrameOwner<'nested, Self::Mode>,
        ) {
            unimplemented!()
        }
    }

    cfg_if::cfg_if! {
        if #[cfg(feature = "ccall")] {
            use crate::memory::frame::NullFrame;
            use crate::memory::mode::Sync;

            impl<'frame> FramePriv<'frame> for NullFrame<'frame> {
                type Mode = Sync;

                unsafe fn push_root<'data, T: WrapperPriv<'frame, 'data>>(
                    &mut self,
                    _value: NonNull<T::Wraps>,
                    _: Private,
                ) -> Result<T, AllocError> {
                    Err(AllocError::NullFrame)?
                }

                unsafe fn reserve_slot(&mut self, _: Private) -> JlrsResult<&'frame Slot> {
                    Err(AllocError::NullFrame)?
                }

                unsafe fn reserve_slots<'borrow>(&'borrow mut self, _: usize, _: Private) -> JlrsResult<&'frame [Slot]> {
                    Err(AllocError::NullFrame)?
                }

                fn nest<'nested>(
                    &'nested mut self,
                    _capacity: usize,
                    _: Private,
                ) -> (GcFrame<'nested, Self::Mode>, FrameOwner<'nested, Self::Mode>) {
                    unreachable!()
                }
            }
        }
    }

    cfg_if::cfg_if! {
        if #[cfg(feature = "async")] {
            use super::AsyncGcFrame;
            use super::super::mode::Async;

            impl<'frame> FramePriv<'frame> for AsyncGcFrame<'frame> {
                type Mode = Async<'frame>;

                unsafe fn push_root<'data, T: WrapperPriv<'frame, 'data>>(
                    &mut self,
                    value: NonNull<T::Wraps>,
                    _: Private,
                ) -> Result<T, AllocError> {
                    let n_roots = self.n_roots();
                    if n_roots == self.capacity() {
                        Err(AllocError::Full { cap: n_roots })?
                    }

                    self.root(value.cast());
                    Ok(T::wrap_non_null(value, Private))
                }

                unsafe fn reserve_slot(&mut self, _: Private) -> JlrsResult<&'frame Slot> {
                    let n_roots = self.n_roots();
                    if n_roots == self.capacity() {
                        Err(AllocError::Full { cap: n_roots })?
                    }

                    self.raw_frame
                        .get_unchecked(n_roots + 2)
                        .set(null_mut());

                    self.set_n_roots(n_roots + 1);
                    Ok(self.raw_frame.get_unchecked(n_roots + 2))
                }

                unsafe fn reserve_slots<'borrow>(&'borrow mut self, slots: usize, _: Private) -> JlrsResult<&'frame [Slot]> {
                    let n_roots = self.n_roots();
                    if n_roots + slots >= self.capacity() {
                        Err(AllocError::Full { cap: n_roots })?
                    }

                    for i in 0..slots {
                        self.raw_frame.get_unchecked(n_roots + i + 2).set(null_mut());
                    }

                    self.set_n_roots(n_roots + slots);
                    Ok(self.raw_frame[n_roots + 2..n_roots + slots + 2].as_ref())
                }



                fn nest<'nested>(
                    &'nested mut self,
                    capacity: usize,
                    _: Private,
                ) -> (GcFrame<'nested, Self::Mode>, FrameOwner<'nested, Self::Mode>) {
                    let used = self.n_roots() + 2;
                    let new_frame_size = MIN_FRAME_CAPACITY.max(capacity) + 2;
                    let raw_frame = if self.page.is_some() {
                        // Safety: page is some
                        unsafe {
                            if new_frame_size <= self.page.as_ref().unwrap_unchecked().size() {
                                self.page.as_ref().unwrap_unchecked().as_ref()
                            } else {
                                self.page = Some(StackPage::new(new_frame_size));
                                self.page.as_ref().unwrap_unchecked().as_ref()
                            }
                        }
                    } else if used + new_frame_size <= self.raw_frame.len() {
                        &self.raw_frame[used..]
                    } else {
                        self.page = Some(StackPage::new(new_frame_size));
                        // Safety: page is some
                        unsafe { self.page.as_ref().unwrap_unchecked().as_ref() }
                    };

                    // Safety: nested hierarchy is maintained
                    unsafe { GcFrame::new(raw_frame, self.mode) }
                }
            }
        }
    }
}

#[cfg(test)]
#[cfg(feature = "sync-rt")]
mod tests {
    use super::private::FramePriv;
    use crate::{
        memory::{
            frame::{Frame as _, GcFrame},
            mode,
            stack_page::StackPage,
        },
        private::Private,
        util,
        wrappers::ptr::value::Value,
    };

    #[test]
    fn min_stack_pack_size() {
        let page = StackPage::new(0);
        assert_eq!(page.size(), 64);
    }

    #[test]
    fn create_base_frame() {
        util::JULIA.with(|julia| unsafe {
            let julia = julia.borrow_mut();
            let page = julia.get_page();
            let page_size = page.size();

            let frame = GcFrame::new(page.as_ref(), mode::Sync);
            assert_eq!(frame.0.capacity(), page_size - 2);
            assert_eq!(frame.0.n_roots(), 0);
        })
    }

    #[test]
    fn push_root() {
        util::JULIA.with(|julia| unsafe {
            let julia = julia.borrow_mut();
            let page = julia.get_page();
            let page_size = page.size();
            let mut frame = GcFrame::new(page.as_ref(), mode::Sync);
            let _value = Value::new(&mut frame.0, 1usize).unwrap();

            assert_eq!(frame.0.capacity(), page_size - 2);
            assert_eq!(frame.0.n_roots(), 1);
        })
    }

    #[test]
    fn push_too_many_roots() {
        util::JULIA.with(|julia| unsafe {
            let julia = julia.borrow_mut();
            let page = julia.get_page();
            let page_size = page.size();
            let mut frame = GcFrame::new(page.as_ref(), mode::Sync);

            for _ in 0..page_size - 2 {
                let _value = Value::new(&mut frame.0, 1usize).unwrap();
            }

            assert_eq!(frame.0.capacity(), page_size - 2);
            assert_eq!(frame.0.n_roots(), page_size - 2);
            assert!(Value::new(&mut frame.0, 1usize).is_err());
        })
    }

    #[test]
    fn push_new_frame() {
        util::JULIA.with(|julia| unsafe {
            let julia = julia.borrow_mut();
            let page = julia.get_page();
            let page_size = page.size();
            let mut frame = GcFrame::new(page.as_ref(), mode::Sync);

            {
                let nested = frame.0.nest(0, Private);
                let capacity = nested.0.capacity();
                assert_eq!(capacity, page_size - 4);
            }
        })
    }

    #[test]
    fn push_large_new_frame() {
        util::JULIA.with(|julia| unsafe {
            let julia = julia.borrow_mut();
            let page = julia.get_page();
            let page_size = page.size();
            let mut frame = GcFrame::new(page.as_ref(), mode::Sync);

            {
                let nested = frame.0.nest(2 * page_size, Private);
                let capacity = nested.0.capacity();
                let n_roots = nested.0.n_roots();
                assert_eq!(capacity, 2 * page_size);
                assert_eq!(n_roots, 0);
            }
        })
    }

    #[test]
    fn reuse_large_page() {
        util::JULIA.with(|julia| unsafe {
            let julia = julia.borrow_mut();
            let page = julia.get_page();
            let page_size = page.size();
            let mut frame = GcFrame::new(page.as_ref(), mode::Sync);

            {
                frame.0.nest(2 * page_size, Private);
            }

            {
                let nested = frame.0.nest(0, Private);
                let capacity = nested.0.capacity();
                let n_roots = nested.0.n_roots();
                assert_eq!(capacity, 2 * page_size);
                assert_eq!(n_roots, 0);
            }
        })
    }
}