rive_rs/core/
object.rs

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
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::any::{self, Any, TypeId};
use std::marker::PhantomData;
use std::ops::Deref;
use std::rc::{Rc, Weak};
use std::{fmt, hash};

use crate::core::{Cast, Core, CoreContext, OnAdded};
use crate::importers::ImportStack;
use crate::status_code::StatusCode;

fn any_type_name<T: Any>() -> &'static str {
    any::type_name::<T>().rsplit("::").next().unwrap()
}

type OnAddedListener = fn(&Rc<dyn Core>, &dyn CoreContext) -> StatusCode;
type Importer = fn(&Rc<dyn Core>, Object, &ImportStack) -> StatusCode;

pub struct Object<T = ()> {
    weak: Weak<dyn Core>,
    on_added_dirty: Option<OnAddedListener>,
    pub on_added_clean: Option<OnAddedListener>,
    import: Option<Importer>,
    _phantom: PhantomData<T>,
}

impl<T> Object<T> {
    pub(crate) fn new(rc: &Rc<dyn Core>) -> Self {
        Self {
            weak: Rc::downgrade(rc),
            on_added_dirty: None,
            on_added_clean: None,
            import: None,
            _phantom: PhantomData,
        }
    }

    fn upgrade_rc(&self) -> Rc<dyn Core> {
        self.weak.upgrade().expect("File dropped while objects still in use")
    }

    pub fn as_ref(&self) -> ObjectRef<'_, T> {
        ObjectRef {
            core_ref: CoreRef::Rc(self.upgrade_rc()),
            on_added_dirty: self.on_added_dirty,
            on_added_clean: self.on_added_clean,
            import: self.import,
        }
    }

    pub fn ptr_eq<U>(&self, other: &Object<U>) -> bool {
        self.weak.ptr_eq(&other.weak)
    }
}

impl<T: Any> Object<T> {
    pub fn try_cast<C: Core>(&self) -> Option<Object<C>> {
        let rc = self.upgrade_rc();
        rc.is::<C>().then(|| Object {
            weak: Rc::downgrade(&rc),
            on_added_dirty: None,
            on_added_clean: None,
            import: None,
            _phantom: PhantomData,
        })
    }

    pub fn cast<C: Core>(&self) -> Object<C> {
        fn type_name<T: Any>() -> String {
            if TypeId::of::<T>() == TypeId::of::<()>() {
                return String::from("Object");
            }

            format!("Object<{}>", any_type_name::<T>())
        }

        self.try_cast().unwrap_or_else(|| {
            panic!("failed cast from {} to {}", type_name::<T>(), type_name::<C>(),)
        })
    }
}

impl<'a, T: Core> From<Object<T>> for Object
where
    ObjectRef<'a, T>: OnAdded,
{
    fn from(object: Object<T>) -> Self {
        fn on_added_dirty<'a, T: Core>(rc: &Rc<dyn Core>, context: &dyn CoreContext) -> StatusCode
        where
            ObjectRef<'a, T>: OnAdded + 'a,
        {
            let object_ref: ObjectRef<'_, T> = ObjectRef {
                core_ref: CoreRef::Rc(Rc::clone(rc)),
                on_added_dirty: None,
                on_added_clean: None,
                import: None,
            };
            object_ref.on_added_dirty(context)
        }

        fn on_added_clean<'a, T: Core>(rc: &Rc<dyn Core>, context: &dyn CoreContext) -> StatusCode
        where
            ObjectRef<'a, T>: OnAdded,
        {
            let object_ref: ObjectRef<'_, T> = ObjectRef {
                core_ref: CoreRef::Rc(Rc::clone(rc)),
                on_added_dirty: None,
                on_added_clean: None,
                import: None,
            };
            object_ref.on_added_clean(context)
        }

        fn import<'a, T: Core>(
            rc: &Rc<dyn Core>,
            object: Object,
            import_stack: &ImportStack,
        ) -> StatusCode
        where
            ObjectRef<'a, T>: OnAdded,
        {
            let object_ref: ObjectRef<'_, T> = ObjectRef {
                core_ref: CoreRef::Rc(Rc::clone(rc)),
                on_added_dirty: None,
                on_added_clean: None,
                import: None,
            };
            object_ref.import(object, import_stack)
        }

        Self {
            weak: object.weak,
            on_added_dirty: Some(on_added_dirty::<T>),
            on_added_clean: Some(on_added_clean::<T>),
            import: Some(import::<T>),
            _phantom: PhantomData,
        }
    }
}

impl<T> Clone for Object<T> {
    fn clone(&self) -> Self {
        Self {
            weak: self.weak.clone(),
            on_added_dirty: self.on_added_dirty,
            on_added_clean: self.on_added_clean,
            import: self.import,
            _phantom: PhantomData,
        }
    }
}

impl fmt::Debug for Object {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Object").finish()
    }
}

impl<T: Core + fmt::Debug> fmt::Debug for Object<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Object").finish()
    }
}

impl<T> hash::Hash for Object<T> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.weak.upgrade().map(|rc| &*rc as *const _).hash(state);
    }
}

impl<T> Eq for Object<T> {}

impl<T> PartialEq for Object<T> {
    fn eq(&self, other: &Self) -> bool {
        self.weak.ptr_eq(&other.weak)
    }
}

#[derive(Debug)]
enum CoreRef<'a, T = ()> {
    Rc(Rc<dyn Core>),
    Borrow(&'a T),
}

impl<'a> CoreRef<'a> {
    pub fn try_cast<'b, C: Core>(&'b self) -> Option<CoreRef<'a, C>> {
        match self {
            Self::Rc(rc) => rc.is::<C>().then(|| CoreRef::Rc(Rc::clone(rc))),
            _ => unreachable!(),
        }
    }
}

impl<'a, T: Core> CoreRef<'a, T> {
    pub fn try_cast<'b, C: Core>(&'b self) -> Option<CoreRef<'a, C>> {
        match self {
            Self::Rc(rc) => rc.is::<C>().then(|| CoreRef::Rc(Rc::clone(rc))),
            Self::Borrow(borrow) => <dyn Core>::try_cast::<C>(*borrow).map(CoreRef::Borrow),
        }
    }

    pub fn type_name(&self) -> &'static str {
        match self {
            Self::Rc(rc) => rc.type_name(),
            Self::Borrow(borrow) => borrow.type_name(),
        }
    }
}

impl Deref for CoreRef<'_> {
    type Target = dyn Core;

    fn deref(&self) -> &Self::Target {
        if let Self::Rc(rc) = self {
            return &**rc;
        }

        panic!("CoreRef<'_> must contain an Rc pointer");
    }
}

impl<T: Core> Deref for CoreRef<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Rc(rc) => rc.cast(),
            Self::Borrow(borrow) => borrow,
        }
    }
}

impl<T> Clone for CoreRef<'_, T> {
    fn clone(&self) -> Self {
        match self {
            Self::Rc(rc) => Self::Rc(Rc::clone(rc)),
            Self::Borrow(borrow) => Self::Borrow(borrow),
        }
    }
}

pub struct ObjectRef<'a, T = ()> {
    core_ref: CoreRef<'a, T>,
    on_added_dirty: Option<OnAddedListener>,
    on_added_clean: Option<OnAddedListener>,
    import: Option<Importer>,
}

impl<'a, T: Core> From<&'a T> for ObjectRef<'a, T> {
    fn from(borrow: &'a T) -> Self {
        Self {
            core_ref: CoreRef::Borrow(borrow),
            on_added_dirty: None,
            on_added_clean: None,
            import: None,
        }
    }
}

impl<T: Core> From<Rc<T>> for ObjectRef<'_, T> {
    fn from(rc: Rc<T>) -> Self {
        Self { core_ref: CoreRef::Rc(rc), on_added_dirty: None, on_added_clean: None, import: None }
    }
}

impl<'a, T: Core> ObjectRef<'a, T> {
    pub fn try_cast<'b, C: Core>(&'b self) -> Option<ObjectRef<'a, C>> {
        self.core_ref.try_cast().map(|core_ref| ObjectRef {
            core_ref,
            on_added_dirty: self.on_added_dirty,
            on_added_clean: self.on_added_clean,
            import: self.import,
        })
    }

    pub fn cast<'b, C: Core>(&'b self) -> ObjectRef<'a, C> {
        fn type_name<T: Any>() -> String {
            format!("ObjectRef<'_, {}>", any_type_name::<T>())
        }

        self.try_cast().unwrap_or_else(|| {
            panic!("failed cast from {} to {}", type_name::<T>(), type_name::<C>(),)
        })
    }

    pub fn type_name(&self) -> &'static str {
        self.core_ref.type_name()
    }
}

impl<'a> ObjectRef<'a> {
    pub fn try_cast<'b, C: Core>(&'b self) -> Option<ObjectRef<'a, C>> {
        self.core_ref.try_cast().map(|core_ref| ObjectRef {
            core_ref,
            on_added_dirty: self.on_added_dirty,
            on_added_clean: self.on_added_clean,
            import: self.import,
        })
    }

    pub fn cast<'b, C: Core>(&'b self) -> ObjectRef<'a, C> {
        self.try_cast().unwrap_or_else(|| {
            panic!("failed cast from ObjectRef<'_> to {}", any_type_name::<C>(),)
        })
    }

    pub fn on_added_dirty(&self, context: &dyn CoreContext) -> StatusCode {
        if let CoreRef::Rc(rc) = &self.core_ref {
            self.on_added_dirty.map(|f| f(rc, context)).unwrap_or(StatusCode::Ok)
        } else {
            panic!("on_added_dirty should not be called on ObjectRef from borrows");
        }
    }

    pub fn on_added_clean(&self, context: &dyn CoreContext) -> StatusCode {
        if let CoreRef::Rc(rc) = &self.core_ref {
            self.on_added_clean.map(|f| f(rc, context)).unwrap_or(StatusCode::Ok)
        } else {
            panic!("on_added_clean should not be called on ObjectRef from borrows");
        }
    }

    pub fn import(&self, object: Object, import_stack: &ImportStack) -> StatusCode {
        if let CoreRef::Rc(rc) = &self.core_ref {
            self.import.map(|f| f(rc, object, import_stack)).unwrap_or(StatusCode::Ok)
        } else {
            panic!("import should not be called on ObjectRef from borrows");
        }
    }
}

impl<T> ObjectRef<'_, T> {
    pub fn as_object(&self) -> Object<T> {
        if let CoreRef::Rc(rc) = &self.core_ref {
            Object {
                weak: Rc::downgrade(rc),
                on_added_dirty: self.on_added_dirty,
                on_added_clean: self.on_added_clean,
                import: self.import,
                _phantom: PhantomData,
            }
        } else {
            panic!("as_object should not be called on ObjectRef from borrows")
        }
    }
}

impl Deref for ObjectRef<'_> {
    type Target = dyn Core;

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

impl<T: Core> Deref for ObjectRef<'_, T> {
    type Target = T;

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

impl<T> Clone for ObjectRef<'_, T> {
    fn clone(&self) -> Self {
        Self {
            core_ref: self.core_ref.clone(),
            on_added_dirty: self.on_added_dirty,
            on_added_clean: self.on_added_clean,
            import: self.import,
        }
    }
}

impl fmt::Debug for ObjectRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&*self.core_ref, f)
    }
}

impl<T: Core + fmt::Debug> fmt::Debug for ObjectRef<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&*self.core_ref, f)
    }
}

impl<T: Eq> Eq for ObjectRef<'_, T> {}

impl<T: PartialEq> PartialEq for ObjectRef<'_, T> {
    fn eq(&self, other: &Self) -> bool {
        self.as_object() == other.as_object()
    }
}