cgp_component/types/use_context.rs
1use crate::WithProvider;
2
3/**
4 The `UseContext` pattern is used to define a trivial implementation of
5 a provider trait, by forwarding the implementation to the consumer trait
6 implementation of the context.
7
8 This pattern is the _dual_ of the blanket implementation of a consumer trait,
9 which forwards the implementation to its provider through the `CgpProvider` trait.
10
11 The main use case for `UseContext` is to be used as a _higher-order provider_
12 in the argument to a different provider implementation. This decouples the
13 dependencies between different CGP traits, and allows non-default providers
14 to be used within another provider implementation.
15
16 For obvious reasons, `UseContext` should not be used as the delegation target
17 from the context provider, as it would result in a cyclic dependency error.
18
19 The `UseContext` provider is automatically implemented for all CPG traits that
20 are generated from `#[cgp_component]`.
21
22 ## Example
23
24 Given the following component definition:
25
26 ```rust,ignore
27 #[cgp_component(Greeter)]
28 pub trait CanGreet {
29 fn greet(&self);
30 }
31 ```
32
33 The following `UseContext` implementation would be generated:
34
35 ```rust,ignore
36 impl<Context> Greeter<Context> for UseContext
37 where
38 Context: CanGreet,
39 {
40 fn greet(context: &Context) {
41 context.greet()
42 }
43 }
44 ```
45*/
46pub struct UseContext;
47
48pub type WithContext = WithProvider<UseContext>;