acme_core/traits/
context.rs

1/*
2    Appellation: context <module>
3    Contrib: @FL03
4*/
5
6/// The base context considered by the `acme` framework.
7pub trait RawContext {
8    type Item;
9
10    private!();
11}
12
13pub trait Context {
14    type Ctx: RawContext;
15    /// returns an immutable reference to the current context.
16    fn ctx(&self) -> Self::Ctx;
17    /// returns a mutable reference to the current context
18    fn ctx_mut(&mut self) -> &mut Self::Ctx;
19    /// replace the current context with the given before returning the previous entry.
20    fn replace_ctx(&mut self, ctx: Self::Ctx) -> Self::Ctx;
21    /// update the current instance with the given context before returning a mutable reference
22    fn set_ctx(&mut self, ctx: Self::Ctx) -> &mut Self;
23}
24
25/// [`Contextual`] is a trait for denoting types that are associated with a particular context.
26pub trait Contextual {
27    type Ctx: RawContext;
28    /// returns an immutable reference to the current context.
29    fn ctx(&self) -> Self::Ctx;
30    /// returns a mutable reference to the current context
31    fn ctx_mut(&mut self) -> &mut Self::Ctx;
32    /// [`replace`](core::mem::replace) with another and return the previous context
33    fn replace_ctx(&mut self, ctx: Self::Ctx) -> Self::Ctx {
34        core::mem::replace(self.ctx_mut(), ctx)
35    }
36    /// update the current context and return a mutable reference to the instance
37    fn set_ctx(&mut self, ctx: Self::Ctx) -> &mut Self {
38        *self.ctx_mut() = ctx;
39        self
40    }
41    /// [`swap`](core::mem::swap) out the context's of two instances.
42    fn swap_ctx(&mut self, other: &mut Self) {
43        core::mem::swap(self.ctx_mut(), other.ctx_mut());
44    }
45    /// [`take`](core::mem::take) the current context and return it, leaving the default
46    /// context in its place.
47    fn take_ctx(&mut self) -> Self::Ctx
48    where
49        Self::Ctx: Default,
50    {
51        core::mem::take(self.ctx_mut())
52    }
53}