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
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
use std::{
    mem::MaybeUninit,
    ptr::{NonNull, null_mut},
    sync::atomic::{AtomicPtr, AtomicU8, AtomicU16, AtomicU32, AtomicU64, Ordering},
    usize,
};

use jl_sys::jl_value_t;
use jlrs_sys::{jlrs_array_typetagdata, jlrs_lock_value, jlrs_unlock_value};

use super::{Value, WeakValue};
use crate::{
    data::{
        layout::valid_layout::ValidLayout,
        managed::{
            Managed,
            array::Array,
            datatype::{DataType, WeakDataType},
            private::ManagedPriv,
            union::{Union, nth_union_component},
        },
    },
    error::{AccessError, CANNOT_DISPLAY_TYPE, JlrsResult},
    private::Private,
};

#[repr(C, align(16))]
#[derive(Clone, Copy)]
union AtomicBuffer {
    bytes: [MaybeUninit<u8>; 16],
    ptr: *mut jl_value_t,
}

impl AtomicBuffer {
    fn new() -> Self {
        AtomicBuffer { ptr: null_mut() }
    }
}

#[derive(Copy, Clone, PartialEq)]
enum ViewState {
    Locked,
    Unlocked,
    AtomicBuffer,
    Array,
}

// TODO: track

/// Access the raw contents of a Julia value.
///
/// A `FieldAccessor` for a value can be created with [`Value::field_accessor`]. By chaining calls
/// to the `field` and `atomic_field` methods you can access deeply nested fields without
/// allocating temporary Julia data. These two methods support three kinds of field identifiers:
/// field names, numerical field indices, and n-dimensional array indices. The first two can be
/// used with types that have named fields, the second must be used with tuples, and the last one
/// with arrays.
pub struct FieldAccessor<'scope, 'data> {
    value: Option<WeakValue<'scope, 'data>>,
    current_field_type: Option<WeakDataType<'scope>>,
    buffer: AtomicBuffer,
    offset: u32,
    state: ViewState,
}

impl<'scope, 'data> FieldAccessor<'scope, 'data> {
    #[inline]
    pub(crate) fn new(value: Value<'scope, 'data>) -> Self {
        FieldAccessor {
            value: Some(value.as_weak()),
            current_field_type: Some(value.datatype().as_weak()),
            offset: 0,
            buffer: AtomicBuffer::new(),
            state: ViewState::Unlocked,
        }
    }
    /// Access the field the accessor is currenty pointing to as a value of type `T`.
    ///
    /// This method accesses the field using its concrete type. If the concrete type of the field
    /// has a matching managed type it can be accessed as a `WeakValue` or a `Weak` of that managed
    /// type. For example, a field that contains a `Module` can be accessed as a `ModuleRef`. In
    /// all other cases a layout type must be used. For example, an untyped field that currently
    /// holds a `Float64` must be accessed as `f64`.
    pub fn access<T: ValidLayout>(self) -> JlrsResult<T> {
        if self.current_field_type.is_none() {
            Err(AccessError::UndefRef)?;
        }

        if self.value.is_none() {
            Err(AccessError::UndefRef)?;
        }

        // Safety: in this block, the first check ensures that T is correct
        // for the data that is accessed. If the data is in the atomic buffer
        // it's read from there. If T is Weak, the pointer is converted. If
        // it's an array, the element at the desired position is read.
        // Otherwise, the field is read at the offset where it has been determined
        // to be stored.
        unsafe {
            let ty = self.current_field_type.unwrap().as_value();
            if !T::valid_layout(ty) {
                let value_type = ty.display_string_or(CANNOT_DISPLAY_TYPE).into();
                Err(AccessError::InvalidLayout { value_type })?;
            }

            if self.state == ViewState::AtomicBuffer {
                debug_assert!(!T::IS_REF);
                debug_assert!(std::mem::size_of::<T>() <= 8);
                return Ok(std::ptr::read(
                    self.buffer.bytes[self.offset as usize..].as_ptr() as *const T,
                ));
            }

            if T::IS_REF {
                Ok(std::mem::transmute_copy(&self.value))
            } else if self.state == ViewState::Array {
                Ok(self
                    .value
                    .unwrap()
                    .as_value()
                    .cast_unchecked::<Array>()
                    .data_ptr()
                    .cast::<u8>()
                    .add(self.offset as usize)
                    .cast::<T>()
                    .read())
            } else {
                Ok(self
                    .value
                    .unwrap()
                    .ptr()
                    .cast::<u8>()
                    .as_ptr()
                    .add(self.offset as usize)
                    .cast::<T>()
                    .read())
            }
        }
    }

    /// Returns `true` if `self.access::<T>()` will succeed, `false` if it will fail.
    #[inline]
    pub fn can_access_as<T: ValidLayout>(&self) -> bool {
        if self.current_field_type.is_none() {
            return false;
        }

        // Safety: the current_field_type field is not undefined.
        let ty = unsafe { self.current_field_type.unwrap().as_value() };
        if !T::valid_layout(ty) {
            return false;
        }

        true
    }

    /// Update the accessor to point to `field`.
    ///
    /// Three kinds of field indices exist: field names, numerical field indices, and
    /// n-dimensional array indices. The first two can be used with types that have named fields,
    /// the second must be used with tuples, and the last one with arrays.
    ///
    /// If `field` is an invalid identifier an error is returned. Calls to `field` can be chained
    /// to access nested fields.
    ///
    /// If the field is an atomic field the same ordering is used as Julia uses by default:
    /// `Relaxed` for pointer fields, `SeqCst` for small inline fields, and a lock for large
    /// inline fields.
    pub fn field<F: FieldIndex>(mut self, field: F) -> JlrsResult<Self> {
        if self.value.is_none() {
            Err(AccessError::UndefRef)?
        }

        if self.current_field_type.is_none() {
            Err(AccessError::UndefRef)?
        }

        // Safety: how to access the next field depends on the current view. If an array
        // is accessed the view is updated to the requested element. Otherwise, the offset
        // is adjusted to target the requested field. Because the starting point is assumed
        // to be rooted, all pointer fields are either reachablle or undefined. If a field is
        // atomic, atomic accesses (or locks for large atomic fields) are used.
        unsafe {
            let current_field_type = self.current_field_type.unwrap().as_managed();
            if self.state == ViewState::Array && current_field_type.is::<Array>() {
                let arr = self.value.unwrap().as_value().cast_unchecked::<Array>();
                // accessing an array, find the offset of the requested element
                let index = field.array_index(arr, Private)?;
                self.get_array_field(arr, index);
                return Ok(self);
            }

            let index = field.field_index(current_field_type, Private)?;

            let next_field_type = match current_field_type.field_type(index) {
                Some(ty) => ty,
                _ => Err(AccessError::UndefRef)?,
            };

            let is_pointer_field = current_field_type.is_pointer_field_unchecked(index);
            let field_offset = current_field_type.field_offset_unchecked(index);
            self.offset += field_offset;

            match self.state {
                ViewState::Array => {
                    self.get_inline_array_field(is_pointer_field, next_field_type)?
                }
                ViewState::Unlocked => self.get_unlocked_inline_field(
                    is_pointer_field,
                    current_field_type,
                    next_field_type,
                    index,
                    Ordering::Relaxed,
                    Ordering::SeqCst,
                ),
                ViewState::Locked => {
                    self.get_locked_inline_field(is_pointer_field, next_field_type)
                }
                ViewState::AtomicBuffer => {
                    self.get_atomic_buffer_field(is_pointer_field, next_field_type)
                }
            }
        }

        Ok(self)
    }

    /// Update the accessor to point to `field`.
    ///
    /// If the field is a small atomic field `ordering` is used to read it. The ordering is
    /// ignored for non-atomic fields and fields that require a lock to access. See
    /// [`FieldAccessor::field`] for more information.
    pub fn atomic_field<F: FieldIndex>(mut self, field: F, ordering: Ordering) -> JlrsResult<Self> {
        if self.value.is_none() {
            Err(AccessError::UndefRef)?
        }

        if self.current_field_type.is_none() {
            Err(AccessError::UndefRef)?
        }

        // Safety: how to access the next field depends on the current view. If an array
        // is accessed the view is updated to the requested element. Otherwise, the offset
        // is adjusted to target the requested field. Because the starting point is assumed
        // to be rooted, all pointer fields are either reachablle or undefined. If a field is
        // atomic, atomic accesses (or locks for large atomic fields) are used.
        unsafe {
            let current_field_type = self.current_field_type.unwrap().as_managed();
            if self.state == ViewState::Array && current_field_type.is::<Array>() {
                let arr = self.value.unwrap().as_value().cast_unchecked::<Array>();
                // accessing an array, find the offset of the requested element
                let index = field.array_index(arr, Private)?;
                self.get_array_field(arr, index);
                return Ok(self);
            }

            let index = field.field_index(current_field_type, Private)?;

            let next_field_type = match current_field_type.field_type(index) {
                Some(ty) => ty,
                _ => Err(AccessError::UndefRef)?,
            };

            let is_pointer_field = current_field_type.is_pointer_field_unchecked(index);
            let field_offset = current_field_type.field_offset_unchecked(index);
            self.offset += field_offset;

            match self.state {
                ViewState::Array => {
                    self.get_inline_array_field(is_pointer_field, next_field_type)?
                }
                ViewState::Unlocked => self.get_unlocked_inline_field(
                    is_pointer_field,
                    current_field_type,
                    next_field_type,
                    index,
                    ordering,
                    ordering,
                ),
                ViewState::Locked => {
                    self.get_locked_inline_field(is_pointer_field, next_field_type)
                }
                ViewState::AtomicBuffer => {
                    self.get_atomic_buffer_field(is_pointer_field, next_field_type)
                }
            }
        }

        Ok(self)
    }

    /// Try to clone this accessor and its state.
    ///
    /// If the current value this accessor is accessing is locked an error is returned.
    #[inline]
    pub fn try_clone(&self) -> JlrsResult<Self> {
        if self.state == ViewState::Locked {
            Err(AccessError::Locked)?;
        }

        Ok(FieldAccessor {
            value: self.value,
            current_field_type: self.current_field_type,
            offset: self.offset,
            buffer: self.buffer.clone(),
            state: self.state,
        })
    }

    #[inline]
    /// Returns `true` if the current value the accessor is accessing is locked.
    pub fn is_locked(&self) -> bool {
        self.state == ViewState::Locked
    }

    /// Returns the type of the field the accessor is currently pointing at.
    #[inline]
    pub fn current_field_type(&self) -> Option<WeakDataType<'scope>> {
        self.current_field_type
    }

    /// Returns the value the accessor is currently inspecting.
    #[inline]
    pub fn value(&self) -> Option<WeakValue<'scope, 'data>> {
        self.value
    }

    // Safety: the view state must be ViewState::AtomicBuffer
    unsafe fn get_atomic_buffer_field(
        &mut self,
        is_pointer_field: bool,
        next_field_type: Value<'scope, 'data>,
    ) {
        unsafe {
            if is_pointer_field {
                debug_assert_eq!(self.offset, 0);
                let ptr = self.buffer.ptr;
                if ptr.is_null() {
                    self.value = None;
                } else {
                    self.value = Some(WeakValue::wrap(NonNull::new_unchecked(ptr)));
                }

                self.state = ViewState::Unlocked;
                if self.value.is_none() {
                    match next_field_type.cast::<DataType>() {
                        Ok(ty) => {
                            if ty.is_concrete_type() {
                                self.current_field_type = Some(ty.as_weak());
                            } else {
                                self.current_field_type = None;
                            }
                        }
                        _ => {
                            self.current_field_type = None;
                        }
                    }
                } else {
                    self.current_field_type =
                        Some(self.value.unwrap().as_managed().datatype().as_weak());
                }
            } else {
                debug_assert!(next_field_type.is::<DataType>());
                self.current_field_type =
                    Some(next_field_type.cast_unchecked::<DataType>().as_weak());
            }
        }
    }

    // Safety: the view state must be ViewState::Unlocked
    unsafe fn get_unlocked_inline_field(
        &mut self,
        is_pointer_field: bool,
        current_field_type: DataType<'scope>,
        next_field_type: Value<'scope, 'data>,
        index: usize,
        pointer_ordering: Ordering,
        inline_ordering: Ordering,
    ) {
        unsafe {
            let is_atomic_field = current_field_type.is_atomic_field_unchecked(index);
            if is_pointer_field {
                if is_atomic_field {
                    self.get_atomic_pointer_field(next_field_type, pointer_ordering);
                } else {
                    self.get_pointer_field(false, next_field_type);
                }
            } else {
                match next_field_type.cast::<Union>() {
                    Ok(un) => {
                        self.get_bits_union_field(un);
                    }
                    _ => {
                        debug_assert!(next_field_type.is::<DataType>());
                        self.current_field_type =
                            Some(next_field_type.cast_unchecked::<DataType>().as_weak());

                        if is_atomic_field {
                            self.lock_or_copy_atomic(inline_ordering);
                        }
                    }
                }
            }
        }
    }

    // Safety: the view state must be ViewState::Locked
    unsafe fn get_locked_inline_field(
        &mut self,
        is_pointer_field: bool,
        next_field_type: Value<'scope, 'data>,
    ) {
        unsafe {
            if is_pointer_field {
                self.get_pointer_field(true, next_field_type);
            } else {
                match next_field_type.cast::<Union>() {
                    Ok(un) => {
                        self.get_bits_union_field(un);
                    }
                    _ => {
                        debug_assert!(next_field_type.is::<DataType>());
                        self.current_field_type =
                            Some(next_field_type.cast_unchecked::<DataType>().as_weak());
                    }
                }
            }
        }
    }

    // Safety: the view state must be ViewState::Array
    unsafe fn get_inline_array_field(
        &mut self,
        is_pointer_field: bool,
        next_field_type: Value<'scope, 'data>,
    ) -> JlrsResult<()> {
        unsafe {
            // Inline field of the current array
            if is_pointer_field {
                self.value = self
                    .value
                    .unwrap()
                    .as_value()
                    .cast::<Array>()?
                    .data_ptr()
                    .cast::<MaybeUninit<u8>>()
                    .add(self.offset as usize)
                    .cast::<Option<WeakValue>>()
                    .read();

                self.offset = 0;
                self.state = ViewState::Unlocked;

                if self.value.is_none() {
                    match next_field_type.cast::<DataType>() {
                        Ok(ty) => {
                            if ty.is_concrete_type() {
                                self.current_field_type = Some(ty.as_weak());
                            } else {
                                self.current_field_type = None;
                            }
                        }
                        _ => {
                            self.current_field_type = None;
                        }
                    }
                } else {
                    self.current_field_type =
                        Some(self.value.unwrap().as_value().datatype().as_weak());
                }
            } else {
                self.current_field_type = Some(next_field_type.cast::<DataType>()?.as_weak());
            }

            Ok(())
        }
    }

    // Safety: must only be used to read an atomic field
    unsafe fn lock_or_copy_atomic(&mut self, ordering: Ordering) {
        unsafe {
            let ptr = self
                .value
                .unwrap()
                .ptr()
                .cast::<MaybeUninit<u8>>()
                .as_ptr()
                .add(self.offset as usize);

            match self
                .current_field_type
                .unwrap()
                .as_managed()
                .size()
                .unwrap_or(std::mem::size_of::<usize>() as _)
            {
                0 => (),
                1 => {
                    let atomic = &*ptr.cast::<AtomicU8>();
                    let v = atomic.load(ordering);
                    let dst_ptr = self.buffer.bytes.as_mut_ptr();
                    std::ptr::copy_nonoverlapping(&v as *const _ as *const u8, dst_ptr as _, 1);
                    self.state = ViewState::AtomicBuffer;
                    self.offset = 0;
                }
                2 => {
                    let atomic = &*ptr.cast::<AtomicU16>();
                    let v = atomic.load(ordering);
                    let dst_ptr = self.buffer.bytes.as_mut_ptr();
                    std::ptr::copy_nonoverlapping(&v as *const _ as *const u8, dst_ptr as _, 2);
                    self.state = ViewState::AtomicBuffer;
                    self.offset = 0;
                }
                sz if sz <= 4 => {
                    let atomic = &*ptr.cast::<AtomicU32>();
                    let v = atomic.load(ordering);
                    let dst_ptr = self.buffer.bytes.as_mut_ptr();
                    std::ptr::copy_nonoverlapping(
                        &v as *const _ as *const u8,
                        dst_ptr as _,
                        sz as usize,
                    );
                    self.state = ViewState::AtomicBuffer;
                    self.offset = 0;
                }
                sz if sz <= 8 => {
                    let atomic = &*ptr.cast::<AtomicU64>();
                    let v = atomic.load(ordering);
                    let dst_ptr = self.buffer.bytes.as_mut_ptr();
                    std::ptr::copy_nonoverlapping(
                        &v as *const _ as *const u8,
                        dst_ptr as _,
                        sz as usize,
                    );
                    self.state = ViewState::AtomicBuffer;
                    self.offset = 0;
                }
                #[cfg(not(any(julia_1_10, julia_1_11)))]
                sz if sz <= 16 => {
                    let atomic = &*ptr.cast::<atomic::Atomic<u128>>();
                    let v = atomic.load(ordering);
                    let dst_ptr = self.buffer.bytes.as_mut_ptr();
                    std::ptr::copy_nonoverlapping(
                        &v as *const _ as *const u8,
                        dst_ptr as _,
                        sz as usize,
                    );
                    self.state = ViewState::AtomicBuffer;
                    self.offset = 0;
                }
                _ => {
                    jlrs_lock_value(self.value.unwrap().ptr().as_ptr());
                    self.state = ViewState::Locked;
                }
            }
        }
    }

    // Safety: must only be used to read an array element
    unsafe fn get_array_field(&mut self, arr: Array<'scope, 'data>, index: usize) {
        unsafe {
            debug_assert!(self.state == ViewState::Array);
            let el_size = arr.element_size() as usize;
            self.offset = (index * el_size) as u32;

            if arr.has_value_layout() {
                self.value = arr.data_ptr().cast::<Option<WeakValue>>().add(index).read();
                self.offset = 0;
                if self.value.is_none() {
                    match arr.element_type().cast::<DataType>() {
                        Ok(ty) => {
                            if ty.is_concrete_type() {
                                self.current_field_type = Some(ty.as_weak());
                            } else {
                                self.current_field_type = None;
                            }

                            if !ty.is::<Array>() {
                                self.state = ViewState::Unlocked;
                            }
                        }
                        _ => {
                            self.current_field_type = None;
                            self.state = ViewState::Unlocked;
                        }
                    }
                } else {
                    let ty = self.value.unwrap().as_value().datatype();
                    self.current_field_type = Some(ty.as_weak());
                    if !ty.is::<Array>() {
                        self.state = ViewState::Unlocked;
                    }
                }
            } else if arr.has_union_layout() {
                let mut tag = *jlrs_array_typetagdata(arr.unwrap(Private)).add(index) as i32;
                let component = nth_union_component(arr.element_type(), &mut tag);
                debug_assert!(component.is_some());
                let ty = component.unwrap_unchecked();
                debug_assert!(ty.is::<DataType>());
                let ty = ty.cast_unchecked::<DataType>();
                debug_assert!(ty.is_concrete_type());
                self.current_field_type = Some(ty.as_weak());
            } else {
                let ty = arr.element_type();
                debug_assert!(ty.is::<DataType>());
                self.current_field_type = Some(ty.cast_unchecked::<DataType>().as_weak());
            }
        }
    }

    // Safety: must only be used to read an pointer field
    unsafe fn get_pointer_field(&mut self, locked: bool, next_field_type: Value<'scope, 'data>) {
        unsafe {
            let value = self
                .value
                .unwrap()
                .ptr()
                .cast::<u8>()
                .as_ptr()
                .add(self.offset as usize)
                .cast::<Option<WeakValue>>()
                .read();

            if locked {
                jlrs_unlock_value(self.value.unwrap().ptr().as_ptr());
                self.state = ViewState::Unlocked;
            }

            self.value = value;
            self.offset = 0;

            if self.value.is_none() {
                match next_field_type.cast::<DataType>() {
                    Ok(ty) => {
                        if ty.is_concrete_type() {
                            self.current_field_type = Some(ty.as_weak());
                        } else {
                            self.current_field_type = None;
                        }
                    }
                    _ => {
                        self.current_field_type = None;
                    }
                }
            } else {
                let value = self.value.unwrap().as_value();
                self.current_field_type = Some(value.datatype().as_weak());
                if value.is::<Array>() {
                    self.state = ViewState::Array;
                }
            }
        }
    }

    // Safety: must only be used to read an atomic pointer field
    unsafe fn get_atomic_pointer_field(
        &mut self,
        next_field_type: Value<'scope, 'data>,
        ordering: Ordering,
    ) {
        unsafe {
            let v = &*self
                .value
                .unwrap()
                .ptr()
                .cast::<u8>()
                .as_ptr()
                .add(self.offset as usize)
                .cast::<AtomicPtr<jl_value_t>>();

            let ptr = v.load(ordering);
            if ptr.is_null() {
                self.value = None;
            } else {
                self.value = Some(WeakValue::wrap(NonNull::new_unchecked(ptr)));
            }

            self.offset = 0;

            if self.value.is_none() {
                match next_field_type.cast::<DataType>() {
                    Ok(ty) => {
                        if ty.is_concrete_type() {
                            self.current_field_type = Some(ty.as_weak());
                        } else {
                            self.current_field_type = None;
                        }
                    }
                    _ => {
                        self.current_field_type = None;
                    }
                }
            } else {
                let value = self.value.unwrap().as_value();
                self.current_field_type = Some(value.datatype().as_weak());
                if value.is::<Array>() {
                    self.state = ViewState::Array;
                }
            }
        }
    }

    // Safety: must only be used to read a bits union field
    unsafe fn get_bits_union_field(&mut self, union: Union<'scope>) {
        unsafe {
            let mut size = 0;
            let isbits = union.isbits_size_align(&mut size, &mut 0);
            debug_assert!(isbits);
            let flag_offset = self.offset as usize + size;
            let mut flag = self
                .value
                .unwrap()
                .ptr()
                .cast::<u8>()
                .as_ptr()
                .add(flag_offset)
                .read() as i32;

            let active_ty = nth_union_component(union.as_value(), &mut flag);
            debug_assert!(active_ty.is_some());
            let active_ty = active_ty.unwrap_unchecked();
            debug_assert!(active_ty.is::<DataType>());

            let ty = active_ty.cast_unchecked::<DataType>();
            debug_assert!(ty.is_concrete_type());
            self.current_field_type = Some(ty.as_weak());
        }
    }
}

impl Drop for FieldAccessor<'_, '_> {
    fn drop(&mut self) {
        if self.state == ViewState::Locked {
            debug_assert!(!self.value.is_none());
            // Safety: the value is currently locked.
            unsafe { jlrs_unlock_value(self.value.unwrap().ptr().as_ptr()) }
        }
    }
}
/// Trait implemented by types that can be used in combination with a
/// [`FieldAccessor`] as the index for a field.
///
/// [`FieldAccessor`]: crate::data::managed::value::field_accessor::FieldAccessor
pub trait FieldIndex: private::FieldIndexPriv {}
impl<I: private::FieldIndexPriv> FieldIndex for I {}

mod private {
    use crate::{
        convert::to_symbol::private::ToSymbolPriv,
        data::managed::{
            Managed,
            array::{Array, dimensions::Dims},
            datatype::DataType,
            string::JuliaString,
            symbol::Symbol,
        },
        error::{AccessError, CANNOT_DISPLAY_TYPE, CANNOT_DISPLAY_VALUE, JlrsResult},
        private::Private,
    };

    pub trait FieldIndexPriv: std::fmt::Debug {
        fn field_index(&self, ty: DataType, _: Private) -> JlrsResult<usize>;

        #[inline]
        fn array_index(&self, _data: Array, _: Private) -> JlrsResult<usize> {
            Err(AccessError::ArrayNeedsNumericalIndex)?
        }
    }

    impl FieldIndexPriv for &str {
        #[inline]
        fn field_index(&self, ty: DataType, _: Private) -> JlrsResult<usize> {
            // Safety: This method can only be called from a thread known to Julia
            let sym = unsafe { self.to_symbol_priv(Private) };

            let Some(idx) = ty.field_index(sym) else {
                Err(AccessError::NoSuchField {
                    type_name: ty.display_string_or(CANNOT_DISPLAY_TYPE),
                    field_name: self.to_string(),
                })?
            };

            Ok(idx as usize)
        }
    }

    impl FieldIndexPriv for Symbol<'_> {
        #[inline]
        fn field_index(&self, ty: DataType, _: Private) -> JlrsResult<usize> {
            let Some(idx) = ty.field_index(*self) else {
                Err(AccessError::NoSuchField {
                    type_name: ty.display_string_or(CANNOT_DISPLAY_TYPE),
                    field_name: self.display_string_or(CANNOT_DISPLAY_VALUE),
                })?
            };

            Ok(idx as usize)
        }
    }

    impl FieldIndexPriv for JuliaString<'_> {
        #[inline]
        fn field_index(&self, ty: DataType, _: Private) -> JlrsResult<usize> {
            let sym = unsafe { self.to_symbol_priv(Private) };

            let Some(idx) = ty.field_index(sym) else {
                Err(AccessError::NoSuchField {
                    type_name: ty.display_string_or(CANNOT_DISPLAY_TYPE),
                    field_name: self.as_str().unwrap_or(CANNOT_DISPLAY_VALUE).to_string(),
                })?
            };

            Ok(idx as usize)
        }
    }

    impl<D: Dims> FieldIndexPriv for D {
        #[inline]
        fn field_index(&self, ty: DataType, _: Private) -> JlrsResult<usize> {
            debug_assert!(!ty.is::<Array>());

            if self.rank() != 1 {
                Err(AccessError::FieldNeedsSimpleIndex)?
            }

            let n = self.size();
            let n_fields = ty.n_fields().ok_or_else(|| AccessError::NoFields {
                value_type: ty.display_string_or(CANNOT_DISPLAY_TYPE),
            })?;
            if n_fields as usize <= n {
                Err(AccessError::OutOfBoundsField {
                    idx: n,
                    n_fields: n_fields as usize,
                    value_type: ty.display_string_or(CANNOT_DISPLAY_TYPE),
                })?;
            }

            Ok(n)
        }

        #[inline]
        fn array_index(&self, data: Array, _: Private) -> JlrsResult<usize> {
            let res = data
                .dimensions()
                .index_of(self)
                .ok_or(AccessError::InvalidIndex {
                    idx: self.to_dimensions(),
                    sz: data.dimensions().to_dimensions(),
                })?;

            Ok(res)
        }
    }
}