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
#![allow(clippy::mut_from_ref)]

use std::{marker::PhantomData, mem::ManuallyDrop};



use super::{builtins::Object, layout::FieldLocation};

#[derive(Debug)]
/// A handle to a field in an object.
/// Can be trivially cloned around for efficient references to fields.
pub struct FieldRef<T> {
    object: *mut Object,
    field: FieldLocation,
    phantom: PhantomData<T>,
}

impl<T> FieldRef<T> {
    pub fn new(object: *mut Object, field: FieldLocation) -> Self {
        Self {
            object,
            field,
            phantom: PhantomData,
        }
    }

    pub fn copy_out(&self) -> T {
        assert!(!self.object.is_null(), "cannot read from null");

        let offset = self.field.offset;
        let data_ptr = unsafe { self.object.byte_add(offset).cast::<T>() };

        unsafe { data_ptr.read() }
    }

    pub fn borrow(&self) -> &T {
        assert!(!self.object.is_null(), "cannot read from null");

        let offset = self.field.offset;
        let data_ptr = unsafe { self.object.byte_add(offset).cast::<T>() };
        unsafe { data_ptr.as_ref().unwrap() }
    }

    pub fn write(&self, value: T) {
        assert!(!self.object.is_null(), "cannot write to null");

        let offset = self.field.offset;
        let data_ptr = unsafe { self.object.byte_add(offset).cast::<T>() };
        unsafe { data_ptr.write(value) };
    }

    pub fn object(&self) -> Option<&Object> {
        assert!(!self.object.is_null(), "cannot ref to null");

        unsafe { self.object.as_ref() }
    }

    pub fn object_mut(&self) -> Option<&mut Object> {
        assert!(!self.object.is_null(), "cannot ref to null");

        unsafe { self.object.as_mut() }
    }
}

impl<T> Drop for FieldRef<T> {
    fn drop(&mut self) {
        let object = self.object_mut().unwrap();
        let binding = ManuallyDrop::new(object.class());
        let layout = ManuallyDrop::new(binding.borrow().instance_layout());

        // We are the last ref, deallocate the entire object we refer to
        if object.ref_count == 1 {
            unsafe { std::alloc::dealloc(self.object as *mut u8, layout.layout()) };
            return;
        }

        object.ref_count -= 1;
    }
}

impl<T> Clone for FieldRef<T> {
    fn clone(&self) -> Self {
        let object = self.object_mut().unwrap();
        object.ref_count += 1;

        Self {
            object: self.object,
            field: self.field,
            phantom: self.phantom,
        }
    }
}

#[derive(Debug)]
pub struct RefTo<T: HasObjectHeader<T>> {
    object: *mut Object,
    phantom: PhantomData<T>,
}

impl<T: HasObjectHeader<T>> PartialEq for RefTo<T> {
    fn eq(&self, other: &Self) -> bool {
        self.object == other.object
    }
}

impl<T: HasObjectHeader<T>> Eq for RefTo<T> {}

pub trait HasObjectHeader<T> {
    fn header(&self) -> &Object;
    fn header_mut(&mut self) -> &mut Object;
}

impl<T: HasObjectHeader<T>> RefTo<T> {
    pub fn new(object: impl HasObjectHeader<T> + 'static) -> Self {
        let b = Box::new(object);
        let leak = Box::leak::<'static>(b);
        let object = leak.header_mut();
        let ptr = object as *mut Object;

        Self {
            object: ptr,
            phantom: PhantomData,
        }
    }

    pub unsafe fn from_ptr(object_ptr: *mut Object) -> Self {
        Self {
            object: object_ptr,
            phantom: PhantomData,
        }
    }

    pub fn copy_out(&self) -> Option<T> {
        if self.object.is_null() {
            None
        } else {
            Some(unsafe { self.object.cast::<T>().read() })
        }
    }

    #[track_caller]
    pub fn borrow_mut(&self) -> &mut T {
        assert!(!self.object.is_null(), "ref was null");
        unsafe { self.object.cast::<T>().as_mut().unwrap() }
    }

    #[track_caller]
    pub fn borrow(&self) -> &T {
        assert!(!self.object.is_null(), "ref was null");
        unsafe { self.object.cast::<T>().as_ref().unwrap() }
    }

    pub fn as_ptr(&self) -> *const Object {
        self.object
    }

    pub fn is_null(&self) -> bool {
        self.object.is_null()
    }

    /// Safety: Caller must ensure object is of this type
    pub unsafe fn cast<U: HasObjectHeader<U>>(&self) -> RefTo<U> {
        RefTo {
            object: self.object,
            phantom: PhantomData,
        }
    }

    pub fn erase(self) -> RefTo<Object> {
        RefTo {
            object: self.object,
            phantom: PhantomData,
        }
    }

    pub fn null() -> Self {
        Self {
            object: std::ptr::null_mut(),
            phantom: PhantomData,
        }
    }

    pub fn into_option(&self) -> Option<&T> {
        if self.is_null() {
            None
        } else {
            Some(self.borrow())
        }
    }
}

impl<T: HasObjectHeader<T>> Clone for RefTo<T> {
    fn clone(&self) -> Self {
        // Null ptrs are all really the same.
        // They don't need ref counting.
        if self.is_null() {
            Self {
                object: self.object,
                phantom: PhantomData,
            }
        } else {
            let s = unsafe { self.object.as_mut().unwrap() };
            s.ref_count += 1;

            Self {
                object: self.object,
                phantom: PhantomData,
            }
        }
    }
}