jlrs 0.23.0

jlrs provides bindings to the Julia C API that enable Julia code to be called from Rust and more.
Documentation
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
/// Tracked references to Julia arrays
///
/// It's very easy to create multiple aliasing references to Julia array data if you use the
/// access methods defined in the `array` module. To help avoid this problem, you can track
/// arrays by calling [`ArrayBase::track_shared`] or [`ArrayBase::track_exclusive`].
///
/// If you strictly use tracking before accessing an array, it's not possible to create multiple
/// aliasing references to this data in Rust. These last two words are important: access to this
/// array in Julia is in no way affected, and you are still responsible for ensuring you don't
/// access data that is in use in Julia.
///
/// [`ArrayBase::track_shared`]: crate::data::managed::array::ArrayBase::track_shared
/// [`ArrayBase::track_exclusive`]: crate::data::managed::array::ArrayBase::track_exclusive
use std::{ops::Deref, ptr::NonNull};

use jlrs_sys::jlrs_array_data_owner;

use super::{
    ArrayBase, Unknown,
    data::accessor::{
        BitsAccessor, BitsAccessorMut, BitsUnionAccessor, BitsUnionAccessorMut,
        IndeterminateAccessor, IndeterminateAccessorMut, InlineAccessor, InlineAccessorMut,
        ManagedAccessor, ManagedAccessorMut, ValueAccessor, ValueAccessorMut,
    },
};
use crate::{
    data::{
        layout::{is_bits::IsBits, typed_layout::HasLayout, valid_layout::ValidField},
        managed::{array::How, private::ManagedPriv},
        types::{
            construct_type::{BitsUnionCtor, ConstructType},
            typecheck::Typecheck,
        },
    },
    error::{ArrayLayoutError, CANNOT_DISPLAY_TYPE, TypeError},
    memory::context::ledger::Ledger,
    prelude::{JlrsResult, Managed, Value},
    private::Private,
};

/// A tracked array that provides immutable access
#[repr(transparent)]
pub struct TrackedArrayBase<'scope, 'data, T, const N: isize> {
    data: ArrayBase<'scope, 'data, T, N>,
}

// Accessors
impl<'scope, 'data, T, const N: isize> TrackedArrayBase<'scope, 'data, T, N> {
    /// Create an accessor for `isbits` data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be stored inline as an array
    /// of `T`s.
    pub fn bits_data<'borrow>(&'borrow self) -> BitsAccessor<'borrow, 'scope, 'data, T, T, N>
    where
        T: ConstructType + ValidField + IsBits,
    {
        // No need for checks, guaranteed to have isbits layout
        unsafe { BitsAccessor::new(&self.data) }
    }

    /// Create an accessor for `isbits` data with layout `L`.
    ///
    /// Thanks to the restrictions on `T` and `L` the elements are guaranteed to be stored inline
    /// as an array of `L`s.
    pub fn bits_data_with_layout<'borrow, L>(
        &'borrow self,
    ) -> BitsAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        T: ConstructType + HasLayout<'static, 'static, Layout = L>,
        L: IsBits + ValidField,
    {
        // No need for checks, guaranteed to have isbits layout and L is the layout of T
        unsafe { BitsAccessor::new(&self.data) }
    }

    /// Try to create an accessor for `isbits` data with layout `L`.
    ///
    /// If the array doesn't have an isbits layout `ArrayLayoutError::NotBits` is returned. If `L`
    /// is not a valid field layout for the element type `TypeError::InvalidLayout` is returned.
    pub fn try_bits_data<'borrow, L>(
        &'borrow self,
    ) -> JlrsResult<BitsAccessor<'borrow, 'scope, 'data, T, L, N>>
    where
        L: IsBits + ValidField,
    {
        if !self.has_bits_layout() {
            Err(ArrayLayoutError::NotBits {
                element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
            })?;
        }

        let ty = self.element_type();
        if !L::valid_field(ty) {
            Err(TypeError::InvalidLayout {
                value_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
            })?;
        }

        unsafe { Ok(BitsAccessor::new(&self.data)) }
    }

    /// Create an accessor for `isbits` data with layout `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// The element type must be an isbits type, and `L` must be a valid field layout of the
    /// element type.
    pub unsafe fn bits_data_unchecked<'borrow, L>(
        &'borrow self,
    ) -> BitsAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        L: IsBits + ValidField,
    {
        unsafe { BitsAccessor::new(&self.data) }
    }

    /// Create an accessor for inline data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be stored inline as an array
    /// of `T`s.
    pub fn inline_data<'borrow>(&'borrow self) -> InlineAccessor<'borrow, 'scope, 'data, T, T, N>
    where
        T: ConstructType + ValidField,
    {
        // No need for checks, guaranteed to have inline layout
        unsafe { InlineAccessor::new(&self.data) }
    }

    /// Create an accessor for inline data with layout `L`.
    ///
    /// Thanks to the restrictions on `T` and `L` the elements are guaranteed to be stored inline
    /// as an array of `L`s.
    pub fn inline_data_with_layout<'borrow, L>(
        &'borrow self,
    ) -> InlineAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        T: ConstructType + HasLayout<'scope, 'data, Layout = L>,
        L: ValidField,
    {
        // No need for checks, guaranteed to have inline layout and L is the layout of T
        unsafe { InlineAccessor::new(&self.data) }
    }

    /// Try to create an accessor for inline data with layout `L`.
    ///
    /// If the array doesn't have an inline layout `ArrayLayoutError::NotInline` is returned. If
    /// `L` is not a valid field layout for the element type `TypeError::InvalidLayout` is
    /// returned.
    pub fn try_inline_data<'borrow, L>(
        &'borrow self,
    ) -> JlrsResult<InlineAccessor<'borrow, 'scope, 'data, T, L, N>>
    where
        L: ValidField,
    {
        if !self.has_inline_layout() {
            Err(ArrayLayoutError::NotInline {
                element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
            })?;
        }

        let ty = self.element_type();
        if !L::valid_field(ty) {
            Err(TypeError::InvalidLayout {
                value_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
            })?;
        }

        unsafe { Ok(InlineAccessor::new(&self.data)) }
    }

    /// Create an accessor for inline data with layout `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// The elements must be stored inline, and `L` must be a valid field layout of the element
    /// type.
    pub unsafe fn inline_data_unchecked<'borrow, L>(
        &'borrow self,
    ) -> InlineAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        L: ValidField,
    {
        unsafe { InlineAccessor::new(&self.data) }
    }

    /// Create an accessor for unions of isbits types.
    ///
    /// This function panics if the array doesn't have a union layout.
    pub fn union_data<'borrow>(&'borrow self) -> BitsUnionAccessor<'borrow, 'scope, 'data, T, N>
    where
        T: BitsUnionCtor,
    {
        assert!(
            self.has_union_layout(),
            "Array does not have a union layout"
        );

        unsafe { BitsUnionAccessor::new(&self.data) }
    }

    /// Try to create an accessor for unions of isbits types.
    ///
    /// If the element type is not a union of isbits types `ArrayLayoutError::NotUnion` is
    /// returned.
    pub fn try_union_data<'borrow>(
        &'borrow self,
    ) -> JlrsResult<BitsUnionAccessor<'borrow, 'scope, 'data, T, N>> {
        if !self.has_union_layout() {
            Err(ArrayLayoutError::NotUnion {
                element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
            })?;
        }

        unsafe { Ok(BitsUnionAccessor::new(&self.data)) }
    }

    /// Create an accessor for unions of isbits types without checking any invariants.
    ///
    /// Safety:
    ///
    /// The element type must be a union of isbits types.
    pub unsafe fn union_data_unchecked<'borrow>(
        &'borrow self,
    ) -> BitsUnionAccessor<'borrow, 'scope, 'data, T, N> {
        unsafe { BitsUnionAccessor::new(&self.data) }
    }
    /// Create an accessor for managed data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be as an array of
    /// `Option<Weak<T>>`s.
    pub fn managed_data<'borrow>(&'borrow self) -> ManagedAccessor<'borrow, 'scope, 'data, T, T, N>
    where
        T: Managed<'scope, 'data> + ConstructType,
    {
        // No need for checks, guaranteed to have correct layout
        unsafe { ManagedAccessor::new(&self.data) }
    }

    /// Try to create an accessor for managed data of type `L`.
    ///
    /// If the element type is incompatible with `L` `ArrayLayoutError::NotManaged` is returned.
    pub fn try_managed_data<'borrow, L>(
        &'borrow self,
    ) -> JlrsResult<ManagedAccessor<'borrow, 'scope, 'data, T, L, N>>
    where
        L: Managed<'scope, 'data> + Typecheck,
    {
        if !self.has_managed_layout::<L>() {
            Err(ArrayLayoutError::NotManaged {
                element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                name: L::NAME.into(),
            })?;
        }

        unsafe { Ok(ManagedAccessor::new(&self.data)) }
    }

    /// Create an accessor for managed data of type `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// The element type must be compatible with `L`.
    pub unsafe fn managed_data_unchecked<'borrow, L>(
        &'borrow self,
    ) -> ManagedAccessor<'borrow, 'scope, 'data, T, L, N>
    where
        L: Managed<'scope, 'data>,
    {
        unsafe { ManagedAccessor::new(&self.data) }
    }

    /// Create an accessor for value data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be as an array of
    /// `Option<Weak<Value>>`s.
    pub fn value_data<'borrow>(&'borrow self) -> ValueAccessor<'borrow, 'scope, 'data, T, N>
    where
        T: Managed<'scope, 'data> + ConstructType,
    {
        // No need for checks, guaranteed to have inline layout
        unsafe { ValueAccessor::new(&self.data) }
    }

    /// Try to create an accessor for value data.
    ///
    /// If the elements are stored inline `ArrayLayoutError::NotPointer` is returned.
    pub fn try_value_data<'borrow>(
        &'borrow self,
    ) -> JlrsResult<ValueAccessor<'borrow, 'scope, 'data, T, N>> {
        if !self.has_value_layout() {
            Err(ArrayLayoutError::NotPointer {
                element_type: self.element_type().error_string_or(CANNOT_DISPLAY_TYPE),
            })?;
        }

        unsafe { Ok(ValueAccessor::new(&self.data)) }
    }

    /// Create an accessor for managed data of type `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// The elements must not be stored inline.
    pub unsafe fn value_data_unchecked<'borrow>(
        &'borrow self,
    ) -> ValueAccessor<'borrow, 'scope, 'data, T, N> {
        unsafe { ValueAccessor::new(&self.data) }
    }

    /// Create an accessor for indeterminate data.
    pub fn indeterminate_data<'borrow>(
        &'borrow self,
    ) -> IndeterminateAccessor<'borrow, 'scope, 'data, T, N> {
        unsafe { IndeterminateAccessor::new(&self.data) }
    }
}

impl<'scope, 'data, T, const N: isize> TrackedArrayBase<'scope, 'data, T, N> {
    pub(crate) fn track_shared(array: ArrayBase<'scope, 'data, T, N>) -> JlrsResult<Self> {
        unsafe {
            let mut array_v = array.as_value();
            if array.how() == How::PointerToOwner {
                let owner = jlrs_array_data_owner(array.unwrap(Private));
                array_v = Value::wrap_non_null(NonNull::new_unchecked(owner), Private);
            }

            let success = Ledger::try_borrow_shared(array_v)?;
            assert!(success);

            Ok(TrackedArrayBase { data: array })
        }
    }
}

impl<'scope, 'data, T, const N: isize> Clone for TrackedArrayBase<'scope, 'data, T, N> {
    fn clone(&self) -> Self {
        unsafe {
            let array = self.data;
            let mut array_v = array.as_value();
            if array.how() == How::PointerToOwner {
                let owner = jlrs_array_data_owner(array.unwrap(Private));
                array_v = Value::wrap_non_null(NonNull::new_unchecked(owner), Private);
            }

            Ledger::try_borrow_shared(array_v).unwrap();
        }
        Self { data: self.data }
    }
}

impl<'scope, 'data, T, const N: isize> Deref for TrackedArrayBase<'scope, 'data, T, N> {
    type Target = ArrayBase<'scope, 'data, T, N>;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl<T, const N: isize> Drop for TrackedArrayBase<'_, '_, T, N> {
    fn drop(&mut self) {
        unsafe {
            let array = self.data;
            let mut array_v = array.as_value();
            if array.how() == How::PointerToOwner {
                let owner = jlrs_array_data_owner(array.unwrap(Private));
                array_v = Value::wrap_non_null(NonNull::new_unchecked(owner), Private);
            }

            let _success = Ledger::unborrow_shared(array_v).expect("Failed to untrack shared");
        }
    }
}

/// A tracked array that provides mutable access
#[repr(transparent)]
pub struct TrackedArrayBaseMut<'scope, 'data, T, const N: isize> {
    data: ArrayBase<'scope, 'data, T, N>,
}

impl<'scope, 'data, T, const N: isize> TrackedArrayBaseMut<'scope, 'data, T, N> {
    /// Create a mutable accessor for `isbits` data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be stored inline as an array
    /// of `T`s.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn bits_data_mut<'borrow>(
        &'borrow mut self,
    ) -> BitsAccessorMut<'borrow, 'scope, 'data, T, T, N>
    where
        T: ConstructType + ValidField + IsBits,
    {
        unsafe {
            // No need for checks, guaranteed to have isbits layout
            BitsAccessorMut::new(&mut self.data)
        }
    }

    /// Create a mutable accessor for `isbits` data with layout `L`.
    ///
    /// Thanks to the restrictions on `T` and `L` the elements are guaranteed to be stored inline
    /// as an array of `L`s.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn bits_data_mut_with_layout<'borrow, L>(
        &'borrow mut self,
    ) -> BitsAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        T: HasLayout<'static, 'static, Layout = L>,
        L: IsBits + ValidField,
    {
        unsafe {
            // No need for checks, guaranteed to have isbits layout and L is the layout of T
            BitsAccessorMut::new(&mut self.data)
        }
    }

    /// Try to create a mutable accessor for `isbits` data with layout `L`.
    ///
    /// If the array doesn't have an isbits layout `ArrayLayoutError::NotBits` is returned. If `L`
    /// is not a valid field layout for the element type `TypeError::InvalidLayout` is returned.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn try_bits_data_mut<'borrow, L>(
        &'borrow mut self,
    ) -> JlrsResult<BitsAccessorMut<'borrow, 'scope, 'data, T, L, N>>
    where
        L: IsBits + ValidField,
    {
        unsafe {
            if !self.has_bits_layout() {
                Err(ArrayLayoutError::NotBits {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            let ty = self.element_type();
            if !L::valid_field(ty) {
                Err(TypeError::InvalidLayout {
                    value_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(BitsAccessorMut::new(&mut self.data))
        }
    }

    /// Create a mutable accessor for `isbits` data with layout `L` without checking any
    /// invariants.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data. The element type must
    /// be an isbits type, and `L` must be a valid field layout of the element type.
    pub unsafe fn bits_data_mut_unchecked<'borrow, L>(
        &'borrow mut self,
    ) -> BitsAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        L: IsBits + ValidField,
    {
        unsafe { BitsAccessorMut::new(&mut self.data) }
    }

    /// Create a mutable accessor for inline data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be stored inline as an array
    /// of `T`s.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn inline_data_mut<'borrow>(
        &'borrow mut self,
    ) -> InlineAccessorMut<'borrow, 'scope, 'data, T, T, N>
    where
        T: ConstructType + ValidField,
    {
        unsafe {
            // No need for checks, guaranteed to have inline layout
            InlineAccessorMut::new(&mut self.data)
        }
    }

    /// Create a mutable accessor for inline data with layout `L`.
    ///
    /// Thanks to the restrictions on `T` and `L` the elements are guaranteed to be stored inline
    /// as an array of `L`s.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn inline_data_mut_with_layout<'borrow, L>(
        &'borrow mut self,
    ) -> InlineAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        T: ConstructType + HasLayout<'scope, 'data, Layout = L>,
        L: ValidField,
    {
        unsafe {
            // No need for checks, guaranteed to have inline layout and L is the layout of T
            InlineAccessorMut::new(&mut self.data)
        }
    }

    /// Try to create a mutable accessor for inline data with layout `L`.
    ///
    /// If the array doesn't have an inline layout `ArrayLayoutError::NotInline` is returned. If
    /// `L` is not a valid field layout for the element type `TypeError::InvalidLayout` is
    /// returned.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn try_inline_data_mut<'borrow, L>(
        &'borrow mut self,
    ) -> JlrsResult<InlineAccessorMut<'borrow, 'scope, 'data, T, L, N>>
    where
        L: ValidField,
    {
        unsafe {
            if !self.has_inline_layout() {
                Err(ArrayLayoutError::NotInline {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            let ty = self.element_type();
            if !L::valid_field(ty) {
                Err(TypeError::InvalidLayout {
                    value_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(InlineAccessorMut::new(&mut self.data))
        }
    }

    /// Create a mutable  accessor for inline data with layout `L` without checking any
    /// invariants.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data. The elements must be
    /// stored inline, and `L` must be a valid field layout of the element type.
    pub unsafe fn inline_data_mut_unchecked<'borrow, L>(
        &'borrow mut self,
    ) -> InlineAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        L: ValidField,
    {
        unsafe { InlineAccessorMut::new(&mut self.data) }
    }

    /// Create a mutable accessor for unions of isbits types.
    ///
    /// This function panics if the array doesn't have a union layout.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn union_data_mut<'borrow>(
        &'borrow mut self,
    ) -> BitsUnionAccessorMut<'borrow, 'scope, 'data, T, N>
    where
        T: BitsUnionCtor,
    {
        unsafe {
            assert!(
                self.has_union_layout(),
                "Array does not have a union layout"
            );
            BitsUnionAccessorMut::new(&mut self.data)
        }
    }

    /// Try to create a mutable accessor for unions of isbits types.
    ///
    /// If the element type is not a union of isbits types `ArrayLayoutError::NotUnion` is
    /// returned.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn try_union_data_mut<'borrow>(
        &'borrow mut self,
    ) -> JlrsResult<BitsUnionAccessorMut<'borrow, 'scope, 'data, T, N>> {
        unsafe {
            if !self.has_union_layout() {
                Err(ArrayLayoutError::NotUnion {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(BitsUnionAccessorMut::new(&mut self.data))
        }
    }

    /// Create a mutable accessor for unions of isbits types without checking any invariants.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data. The element type must
    /// be a union of isbits types.
    pub unsafe fn union_data_mut_unchecked<'borrow>(
        &'borrow mut self,
    ) -> BitsUnionAccessorMut<'borrow, 'scope, 'data, T, N> {
        unsafe { BitsUnionAccessorMut::new(&mut self.data) }
    }

    /// Create a mutable accessor for managed data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be as an array of
    /// `Option<Weak<T>>`s.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn managed_data_mut<'borrow>(
        &'borrow mut self,
    ) -> ManagedAccessorMut<'borrow, 'scope, 'data, T, T, N>
    where
        T: Managed<'scope, 'data> + ConstructType,
    {
        unsafe {
            // No need for checks, guaranteed to have correct layout
            ManagedAccessorMut::new(&mut self.data)
        }
    }

    /// Try to create a mutable accessor for managed data of type `L`.
    ///
    /// If the element type is incompatible with `L` `ArrayLayoutError::NotManaged` is returned.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn try_managed_data_mut<'borrow, L>(
        &'borrow mut self,
    ) -> JlrsResult<ManagedAccessorMut<'borrow, 'scope, 'data, T, L, N>>
    where
        L: Managed<'scope, 'data> + Typecheck,
    {
        unsafe {
            if !self.has_managed_layout::<L>() {
                Err(ArrayLayoutError::NotManaged {
                    element_type: self.element_type().display_string_or(CANNOT_DISPLAY_TYPE),
                    name: L::NAME.into(),
                })?;
            }

            Ok(ManagedAccessorMut::new(&mut self.data))
        }
    }

    /// Create a mutable accessor for managed data of type `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data. The element type must
    /// be compatible with `L`.
    pub unsafe fn managed_data_mut_unchecked<'borrow, L>(
        &'borrow mut self,
    ) -> ManagedAccessorMut<'borrow, 'scope, 'data, T, L, N>
    where
        L: Managed<'scope, 'data>,
    {
        unsafe { ManagedAccessorMut::new(&mut self.data) }
    }

    /// Create a mutable accessor for value data.
    ///
    /// Thanks to the restrictions on `T` the data is guaranteed to be as an array of
    /// `Option<Weak<Value>>`s.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn value_data_mut<'borrow>(
        &'borrow mut self,
    ) -> ValueAccessorMut<'borrow, 'scope, 'data, T, N>
    where
        T: Managed<'scope, 'data> + ConstructType,
    {
        unsafe {
            // No need for checks, guaranteed to have inline layout
            ValueAccessorMut::new(&mut self.data)
        }
    }

    /// Try to create a mutable accessor for value data.
    ///
    /// If the elements are stored inline `ArrayLayoutError::NotPointer` is returned.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn try_value_data_mut<'borrow>(
        &'borrow mut self,
    ) -> JlrsResult<ValueAccessorMut<'borrow, 'scope, 'data, T, N>> {
        unsafe {
            if !self.has_value_layout() {
                Err(ArrayLayoutError::NotPointer {
                    element_type: self.element_type().error_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(ValueAccessorMut::new(&mut self.data))
        }
    }

    /// Create a mutable accessor for managed data of type `L` without checking any invariants.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data. The elements must not
    /// be stored inline.
    pub unsafe fn value_data_mut_unchecked<'borrow>(
        &'borrow mut self,
    ) -> ValueAccessorMut<'borrow, 'scope, 'data, T, N> {
        unsafe { ValueAccessorMut::new(&mut self.data) }
    }

    /// Create a mutable accessor for indeterminate data.
    ///
    /// Safety:
    ///
    /// Mutating Julia data is generally unsafe. You must guarantee that you're allowed to mutate
    /// its content, and that no running Julia code is accessing this data.
    pub unsafe fn indeterminate_data_mut<'borrow>(
        &'borrow mut self,
    ) -> IndeterminateAccessorMut<'borrow, 'scope, 'data, T, N> {
        unsafe { IndeterminateAccessorMut::new(&mut self.data) }
    }
}

impl<'scope, 'data, T, const N: isize> TrackedArrayBaseMut<'scope, 'data, T, N> {
    pub(crate) fn track_exclusive(array: ArrayBase<'scope, 'data, T, N>) -> JlrsResult<Self> {
        unsafe {
            let mut array_v = array.as_value();
            if array.how() == How::PointerToOwner {
                let owner = jlrs_array_data_owner(array.unwrap(Private));
                array_v = Value::wrap_non_null(NonNull::new_unchecked(owner), Private);
            }

            let success = Ledger::try_borrow_exclusive(array_v)?;
            assert!(success);

            Ok(TrackedArrayBaseMut { data: array })
        }
    }
}

impl<'scope, 'data, T, const N: isize> Deref for TrackedArrayBaseMut<'scope, 'data, T, N> {
    type Target = TrackedArrayBase<'scope, 'data, T, N>;

    fn deref(&self) -> &Self::Target {
        unsafe { std::mem::transmute(self) }
    }
}

impl<T, const N: isize> Drop for TrackedArrayBaseMut<'_, '_, T, N> {
    fn drop(&mut self) {
        unsafe {
            let array = self.data;
            let mut array_v = array.as_value();
            if array.how() == How::PointerToOwner {
                let owner = jlrs_array_data_owner(array.unwrap(Private));
                array_v = Value::wrap_non_null(NonNull::new_unchecked(owner), Private);
            }

            let success = Ledger::unborrow_exclusive(array_v).expect("Failed to untrack shared");
            assert!(success);
        }
    }
}

pub type TrackedArray<'scope, 'data> = TrackedArrayBase<'scope, 'data, Unknown, -1>;
pub type TrackedTypedArray<'scope, 'data, T> = TrackedArrayBase<'scope, 'data, T, -1>;
pub type TrackedRankedArray<'scope, 'data, const N: isize> =
    TrackedArrayBase<'scope, 'data, Unknown, N>;
pub type TrackedTypedRankedArray<'scope, 'data, T, const N: isize> =
    TrackedArrayBase<'scope, 'data, T, N>;

pub type TrackedVector<'scope, 'data> = TrackedArrayBase<'scope, 'data, Unknown, 1>;
pub type TrackedTypedVector<'scope, 'data, T> = TrackedArrayBase<'scope, 'data, T, 1>;

pub type TrackedMatrix<'scope, 'data> = TrackedArrayBase<'scope, 'data, Unknown, 2>;
pub type TrackedTypedMatrix<'scope, 'data, T> = TrackedArrayBase<'scope, 'data, T, 2>;

pub type TrackedArrayMut<'scope, 'data> = TrackedArrayBaseMut<'scope, 'data, Unknown, -1>;
pub type TrackedTypedArrayMut<'scope, 'data, T> = TrackedArrayBaseMut<'scope, 'data, T, -1>;
pub type TrackedRankedArrayMut<'scope, 'data, const N: isize> =
    TrackedArrayBaseMut<'scope, 'data, Unknown, N>;
pub type TrackedTypedRankedArrayMut<'scope, 'data, T, const N: isize> =
    TrackedArrayBaseMut<'scope, 'data, T, N>;

pub type TrackedVectorMut<'scope, 'data> = TrackedArrayBaseMut<'scope, 'data, Unknown, 1>;
pub type TrackedTypedVectorMut<'scope, 'data, T> = TrackedArrayBaseMut<'scope, 'data, T, 1>;

pub type TrackedMatrixMut<'scope, 'data> = TrackedArrayBaseMut<'scope, 'data, Unknown, 2>;
pub type TrackedTypedMatrixMut<'scope, 'data, T> = TrackedArrayBaseMut<'scope, 'data, T, 2>;