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
//! Context state management.

use crate::*;

impl<'a> Scope<'a> {
    /// Provides a context in the current [`Scope`]. The context can later be accessed by using
    /// [`use_context`](Self::use_context) lower in the scope hierarchy.
    ///
    /// The context can also be accessed in the same scope in which it is provided.
    ///
    /// This method is simply a wrapper around [`create_ref`](Self::create_ref) and
    /// [`provide_context_ref`](Self::provide_context_ref).
    ///
    /// # Panics
    /// This method panics if a context with the same type exists already in this scope.
    /// Note that if a context with the same type exists in a parent scope, the new context will
    /// shadow the old context.
    #[track_caller]
    pub fn provide_context<T: 'static>(&'a self, value: T) {
        let value = self.create_ref(value);
        self.provide_context_ref(value);
    }

    /// Provides a context in the current [`Scope`]. The context can later be accessed by using
    /// [`use_context`](Self::use_context) lower in the scope hierarchy.
    ///
    /// The context can also be accessed in the same scope in which it is provided.
    ///
    /// Unlike [`provide_context`](Self::provide_context), this method accepts a reference that
    /// lives at least as long as the scope.
    ///
    /// # Panics
    /// This method panics if a context with the same type exists already in this scope.
    /// Note that if a context with the same type exists in a parent scope, the new context will
    /// shadow the old context.
    #[track_caller]
    pub fn provide_context_ref<T: 'static>(&'a self, value: &'a T) {
        let type_id = TypeId::of::<T>();
        if self.contexts.borrow_mut().insert(type_id, value).is_some() {
            panic!("existing context with type exists already");
        }
    }

    /// Tries to get a context value of the given type. If no context with the right type found,
    /// returns `None`. For a panicking version, see [`use_context`](Self::use_context).
    pub fn try_use_context<T: 'static>(&'a self) -> Option<&'a T> {
        let type_id = TypeId::of::<T>();
        let mut this = Some(self);
        while let Some(current) = this {
            if let Some(value) = current.contexts.borrow_mut().get(&type_id) {
                let value = value.downcast_ref::<T>().unwrap();
                return Some(value);
            } else {
                // SAFETY: `current.parent` necessarily lives longer than `current`.
                this = current.parent.map(|x| unsafe { &*x });
            }
        }
        None
    }

    /// Gets a context value of the given type.
    ///
    /// # Panics
    /// This method panics if the context cannot be found in the current scope hierarchy.
    /// For a non-panicking version, see [`try_use_context`](Self::try_use_context).
    #[track_caller]
    pub fn use_context<T: 'static>(&'a self) -> &'a T {
        self.try_use_context().expect("context not found for type")
    }

    /// Returns the current depth of the scope. If the scope is the root scope, returns `0`.
    pub fn scope_depth(&self) -> u32 {
        let mut depth = 0;
        let mut this = Some(self);
        while let Some(current) = this {
            // SAFETY: `current.parent` necessarily lives longer than `current`.
            this = current.parent.map(|x| unsafe { &*x });
            depth += 1;
        }
        depth
    }
}

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

    #[test]
    fn context() {
        create_scope_immediate(|ctx| {
            ctx.provide_context(42i32);
            let x = ctx.use_context::<i32>();
            assert_eq!(*x, 42);
        });
    }

    #[test]
    fn context_in_nested_scope() {
        create_scope_immediate(|ctx| {
            ctx.provide_context(42i32);
            let _ = ctx.create_child_scope(|ctx| {
                let x = ctx.use_context::<i32>();
                assert_eq!(*x, 42);
            });
        });
    }
}