ori-core 0.1.0-alpha.1

Core library for Ori, a declarative UI framework for Rust.
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
use std::{
    cell::RefCell,
    iter::FilterMap,
    marker::PhantomData,
    mem,
    ops::Index,
    sync::atomic::{AtomicUsize, Ordering},
    vec::IntoIter,
};

use crate::{Lock, Lockable, ReadSignal, SendSync, Sendable, Shared, SharedSignal, Signal};

trait Item {}
impl<T> Item for T {}

#[derive(Default, Debug)]
struct ScopeArena<'a> {
    items: RefCell<Vec<*mut (dyn Item + 'a)>>,
}

// SAFETY: the access to `items` is thread-safe because it's only accessed from mutable references.
#[cfg(feature = "multithread")]
unsafe impl<'a> Sync for ScopeArena<'a> {}

impl<'a> ScopeArena<'a> {
    pub fn alloc_static<T: Sendable + 'static>(&self, item: T) -> &'a mut T {
        let item = Box::into_raw(Box::new(item));
        self.items.borrow_mut().push(item);
        unsafe { &mut *item }
    }

    /// # Safety
    /// - `item` must never reference any other item in the arena in it's [`Drop`] implementation.
    pub unsafe fn alloc<T: Sendable + 'a>(&self, item: T) -> &'a mut T {
        let item = Box::into_raw(Box::new(item));
        self.items.borrow_mut().push(item);
        &mut *item
    }

    /// Disposes all items in the arena.
    ///
    /// Calling this multiple times is a no-op.
    ///
    /// # Safety
    /// - There must be no other references to any item in the arena.
    pub unsafe fn dispose(&self) {
        let mut items = self.items.borrow_mut();
        Self::dispose_inner(&mut items);
    }

    unsafe fn dispose_inner(items: &mut Vec<*mut (dyn Item + 'a)>) {
        for &item in items.iter().rev() {
            // SAFETY: `item` is the only reference to the boxed value, so it's safe to drop it.
            unsafe { Box::from_raw(item) };
        }
        items.clear();
    }
}

impl<'a> Drop for ScopeArena<'a> {
    fn drop(&mut self) {
        let items = self.items.get_mut();
        unsafe { Self::dispose_inner(items) };
    }
}

#[derive(Clone, Debug)]
struct Sparse<T> {
    items: Vec<Option<T>>,
    free: Vec<usize>,
}

impl<T> Sparse<T> {
    pub const fn new() -> Self {
        Self {
            items: Vec::new(),
            free: Vec::new(),
        }
    }

    pub fn get(&self, index: usize) -> Option<&T> {
        self.items.get(index)?.as_ref()
    }

    pub fn insert(&mut self, item: T) -> usize {
        if let Some(index) = self.free.pop() {
            self.items[index] = Some(item);
            index
        } else {
            let index = self.items.len();
            self.items.push(Some(item));
            index
        }
    }

    pub fn remove(&mut self, index: usize) -> Option<T> {
        let item = self.items[index].take();
        self.free.push(index);
        item
    }

    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.items.iter().filter_map(|item| item.as_ref())
    }
}

impl<T> Default for Sparse<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Index<usize> for Sparse<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        self.items[index].as_ref().unwrap()
    }
}

impl<T> IntoIterator for Sparse<T> {
    type Item = T;
    type IntoIter = FilterMap<IntoIter<Option<T>>, fn(Option<T>) -> Option<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.items.into_iter().filter_map(|item| item)
    }
}

#[derive(Debug)]
struct RawScope<'a> {
    /// The arena that holds all items in this scope.
    arena: ScopeArena<'a>,

    /// A reference to the parent scope.
    #[allow(dead_code)]
    parent: Option<&'a RawScope<'a>>,

    /// A lock that prevents the scope from being dropped while an effect is running.
    /// This is used to prevent a use-after-free.
    drop_lock: AtomicUsize,

    /// A list of child scopes.
    children: RefCell<Sparse<*mut RawScope<'a>>>,

    /// A marker that ensures that 'a is invariant
    marker: PhantomData<&'a mut &'a ()>,
}

impl<'a> RawScope<'a> {
    fn new() -> Self {
        Self {
            arena: ScopeArena::default(),
            parent: None,
            drop_lock: AtomicUsize::new(0),
            children: RefCell::new(Sparse::new()),
            marker: PhantomData,
        }
    }

    fn child(parent: &'a RawScope<'a>) -> Self {
        Self {
            arena: ScopeArena::default(),
            parent: Some(parent),
            drop_lock: AtomicUsize::new(0),
            children: RefCell::new(Sparse::new()),
            marker: PhantomData,
        }
    }

    fn push_child(&self, child: *mut RawScope<'a>) -> usize {
        let mut children = self.children.borrow_mut();
        children.insert(child)
    }

    fn is_drop_locked(&self) -> bool {
        if self.drop_lock.load(Ordering::Acquire) > 0 {
            return true;
        }

        self.is_child_scopes_drop_locked()
    }

    fn is_child_scope_drop_locked(&self, index: usize) -> bool {
        let children = self.children.borrow();
        if let Some(&child) = children.get(index) {
            let child = unsafe { &*child };
            child.is_drop_locked()
        } else {
            false
        }
    }

    fn is_child_scopes_drop_locked(&self) -> bool {
        self.children.borrow().iter().any(|&child| {
            let child = unsafe { &*child };
            child.is_drop_locked()
        })
    }

    unsafe fn dispose(&self) {
        let mut children = self.children.borrow_mut();

        for child in mem::take(&mut *children).into_iter() {
            let cx = Box::from_raw(child);
            cx.dispose();
        }

        self.arena.dispose();
    }
}

impl<'a> Drop for RawScope<'a> {
    fn drop(&mut self) {
        unsafe { self.dispose() };
    }
}

pub type Scope<'a> = BoundedScope<'a, 'a>;

#[derive(Clone, Copy, Debug)]
pub struct BoundedScope<'a, 'b: 'a> {
    raw: &'a RawScope<'a>,
    marker: PhantomData<&'b ()>,
}

unsafe impl<'a, 'b> Send for BoundedScope<'a, 'b> {}
unsafe impl<'a, 'b> Sync for BoundedScope<'a, 'b> {}

impl<'a> Scope<'a> {
    /// Creates a new scope.
    ///
    /// This function returns a [`ScopeDisposer`] that must be used to dispose of the scope.
    /// If the disposer is not used, the scope will leak memory.
    #[must_use = "not calling `dispose` will leak memory"]
    pub fn new(f: impl FnOnce(Scope<'a>) + 'a) -> ScopeDisposer<'a> {
        let raw = Box::into_raw(Box::new(RawScope::new()));
        let scope = Scope {
            raw: unsafe { &*raw },
            marker: PhantomData,
        };
        super::effect::untrack(|| f(scope));
        ScopeDisposer::root(raw)
    }

    pub(crate) fn drop_lock(&self) {
        self.raw.drop_lock.fetch_add(1, Ordering::AcqRel);
    }

    pub(crate) fn release_drop_lock(&self) {
        self.raw.drop_lock.fetch_sub(1, Ordering::AcqRel);
    }

    /// Creates a new scope and immediately disposes it.
    pub fn immediate(f: impl FnOnce(Scope<'a>) + 'a) {
        let disposer = Self::new(f);

        // SAFETY: the scope is not accessed after this point.
        unsafe { disposer.dispose() };
    }

    /// Creates a new child scope.
    pub fn child(self, f: impl for<'b> FnOnce(BoundedScope<'b, 'a>)) -> ScopeDisposer<'a> {
        let raw = Box::into_raw(Box::new(RawScope::child(self.raw)));
        let index = self.raw.push_child(raw);
        let scope = Scope {
            raw: unsafe { &*raw },
            marker: PhantomData,
        };
        f(scope);
        ScopeDisposer::child(self.raw, index)
    }

    /// Allocates an item in the scope.
    pub fn alloc<T: Sendable + 'static>(&self, item: T) -> &'a T {
        self.raw.arena.alloc_static(item)
    }

    /// Allocates an item in the scope.
    ///
    /// # Safety
    /// - `item` must never reference any other item in the arena in it's [`Drop`] implementation.
    pub unsafe fn alloc_unsafe<T: Sendable + 'a>(self, item: T) -> &'a T {
        self.raw.arena.alloc(item)
    }

    /// Allocates an item in the scope.
    pub fn alloc_mut<T: Sendable + 'static>(&self, item: T) -> &'a mut T {
        self.raw.arena.alloc_static(item)
    }

    /// Allocates an item in the scope.
    ///
    /// # Safety
    /// - `item` must never reference any other item in the arena in it's [`Drop`] implementation.
    pub unsafe fn alloc_mut_unsafe<T: Sendable + 'a>(self, item: T) -> &'a mut T {
        self.raw.arena.alloc(item)
    }

    /// Creates a signal in the scope.
    pub fn signal<T: SendSync + 'static>(self, value: T) -> &'a Signal<T> {
        self.alloc(Signal::new(value))
    }

    /// Runs a scope without tracking any dependencies.
    pub fn untrack<T>(self, f: impl FnOnce() -> T) -> T {
        super::effect::untrack(f)
    }

    /// Creates an effect.
    ///
    /// Effects are callbacks that are run whenever a dependency changes (eg. a signal is updated).
    ///
    /// # Examples
    ///
    /// ```
    /// # use ori_core::*;
    /// # Scope::immediate(|cx| {
    /// let signal = cx.signal(0);
    ///
    /// cx.effect(|| {
    ///     println!("signal is {}", signal.get()); // prints "signal is 0"
    /// });
    ///
    /// signal.set(1); // prints "signal is 1"
    /// # });
    /// ```
    #[track_caller]
    pub fn effect(self, f: impl FnMut() + Sendable + 'a) {
        super::effect::create_effect(self, f);
    }

    /// Creates an effect in a child scope. See [`Scope::effect`].
    #[track_caller]
    pub fn effect_scoped(self, mut f: impl for<'b> FnMut(BoundedScope<'b, 'a>) + Sendable + 'a) {
        let mut disposer = None::<ScopeDisposer<'a>>;
        self.effect(move || {
            if let Some(disposer) = disposer.take() {
                if !disposer.is_drop_locked() {
                    // SAFETY: the scope is not accessed after this point.
                    unsafe { disposer.dispose() };
                } else {
                    tracing::trace!("scope is drop locked, leaking disposer");
                }
            }

            disposer = Some(self.child(|cx| {
                f(cx);
            }));
        });
    }

    /// Creates a signal that is recomputed every time a dependency is updated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use ori_core::*;
    /// # Scope::immediate(|cx| {
    /// let signal = cx.signal(0);
    ///
    /// let memo = cx.memo(|| *signal.get() * 2);
    ///
    /// assert_eq!(*memo, 0);
    ///
    /// signal.set(2);
    /// assert_eq!(*memo, 4);
    /// # });
    /// ```
    #[track_caller]
    pub fn memo<T: SendSync + 'static>(
        self,
        mut f: impl FnMut() -> T + Sendable + 'a,
    ) -> &'a ReadSignal<T> {
        let signal = Shared::new(Lock::new(None::<&'a Signal<T>>));

        self.effect({
            let signal = signal.clone();
            move || {
                let value = f();
                if signal.lock_mut().is_some() {
                    signal.lock_mut().unwrap().set(value);
                } else {
                    *signal.lock_mut() = Some(self.signal(value));
                }
            }
        });

        let signal = signal.lock_mut().unwrap();
        signal
    }

    /// This will create an effect that binds two signals together.
    /// Whenever one of the signals is updated, the other will be updated to the same value.
    /// This is useful for creating two-way bindings (eg. a checkbox).
    ///
    /// When initializing the binding, the value of `signal_b` will be used.
    #[track_caller]
    pub fn bind<T: Clone + PartialEq + SendSync + 'static>(
        self,
        signal_a: &'a Signal<T>,
        signal_b: &'a Signal<T>,
    ) {
        let prev = self.alloc(Lock::new(signal_a.cloned_untracked()));

        self.effect(move || {
            let a = signal_a.cloned();
            let b = signal_b.cloned();
            let mut prev = prev.lock_mut();

            if *prev != a {
                *prev = a.clone();
                signal_b.set(a);
            } else if *prev != b {
                *prev = b.clone();
                signal_a.set(b);
            }
        });
    }

    /// Creates a shared signal that is recomputed every time a dependency is updated.
    #[track_caller]
    pub fn dynamic<T: SendSync + 'static>(
        self,
        mut f: impl FnMut(BoundedScope<'_, 'a>) -> T + Sendable + 'a,
    ) -> SharedSignal<T> {
        let signal = self.alloc(Lock::new(None::<SharedSignal<T>>));

        self.effect_scoped(move |cx| {
            let value = f(cx);

            if signal.lock_mut().is_some() {
                signal.lock_mut().as_ref().unwrap().set(value);
            } else {
                *signal.lock_mut() = Some(SharedSignal::new(value));
            }
        });

        signal.lock_mut().as_ref().unwrap().clone()
    }
}

#[derive(Debug)]
enum ScopeDisposerInner<'a> {
    Root {
        raw: *mut RawScope<'a>,
    },
    Child {
        parent: &'a RawScope<'a>,
        index: usize,
    },
}

// SAFETY: ScopeDisposerInner is Send because it is only accessed from the main thread.
unsafe impl<'a> Send for ScopeDisposerInner<'a> {}

#[derive(Debug)]
pub struct ScopeDisposer<'a> {
    inner: ScopeDisposerInner<'a>,
}

impl<'a> ScopeDisposer<'a> {
    fn root(raw: *mut RawScope<'a>) -> Self {
        Self {
            inner: ScopeDisposerInner::Root { raw },
        }
    }

    fn child(parent: &'a RawScope<'a>, index: usize) -> Self {
        Self {
            inner: ScopeDisposerInner::Child { parent, index },
        }
    }

    fn is_drop_locked(&self) -> bool {
        match self.inner {
            ScopeDisposerInner::Root { .. } => false,
            ScopeDisposerInner::Child { parent, index } => parent.is_child_scope_drop_locked(index),
        }
    }

    /// Disposes the scope.
    ///
    /// # Safety
    /// - The scope must not be accessed after calling this method.
    pub unsafe fn dispose(self) {
        match self.inner {
            ScopeDisposerInner::Root { raw } => {
                // SAFETY: `raw` is the only reference to the scope.
                let cx = Box::from_raw(raw);
                cx.dispose();
            }
            ScopeDisposerInner::Child { parent, index } => {
                let mut children = parent.children.borrow_mut();
                let child = children.remove(index).unwrap();
                // SAFETY: `child` is the only reference to the scope.
                let cx = Box::from_raw(child);
                cx.dispose();
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_signal() {
        Scope::immediate(|cx| {
            let signal = cx.signal(0);

            let cell = cx.alloc(Lock::new(0));
            cx.effect(move || {
                *cell.lock_mut() = *signal.get();
            });
            signal.set(1);

            assert_eq!(*cell.lock_mut(), 1);
        });
    }

    #[test]
    fn test_memo() {
        Scope::immediate(|cx| {
            let signal = cx.signal(0);

            let memo = cx.memo(|| *signal.get() + 1);
            signal.set(1);

            assert_eq!(*memo, 2);
        });
    }
}