pdk_classy/extract/
from_context_once.rs

1// Copyright (c) 2025, Salesforce, Inc.,
2// All rights reserved.
3// For full license text, see the LICENSE.txt file
4
5use std::{
6    future::{ready, Future, Ready},
7    ops::Deref,
8};
9
10use super::FromContext;
11use crate::BoxError;
12
13mod mode {
14    pub enum Once {}
15
16    pub enum Repeat {}
17}
18
19#[doc(hidden)]
20pub struct Exclusive<'c, C> {
21    context: &'c C,
22}
23
24impl<'c, C> Exclusive<'c, C> {
25    pub(crate) fn new(context: &'c C) -> Self {
26        Self { context }
27    }
28
29    pub fn get(&self) -> &'c C {
30        self.context
31    }
32}
33
34impl<C> Deref for Exclusive<'_, C> {
35    type Target = C;
36
37    fn deref(&self) -> &Self::Target {
38        self.get()
39    }
40}
41
42/// Extract data from the given context. The extraction will only be possible once.
43pub trait FromContextOnce<C, M = mode::Once>: Sized {
44    type Error: Into<BoxError>;
45
46    type Future<'c>: Future<Output = Result<Self, Self::Error>> + 'c
47    where
48        C: 'c;
49
50    fn from_context_once(context: Exclusive<C>) -> Self::Future<'_>;
51}
52
53impl<C, T> FromContextOnce<C, mode::Repeat> for T
54where
55    for<'c> T: FromContext<C> + 'c,
56{
57    type Error = T::Error;
58
59    type Future<'c>
60        = Ready<Result<Self, Self::Error>>
61    where
62        C: 'c,
63        Self: 'c;
64
65    fn from_context_once(context: Exclusive<C>) -> Self::Future<'_> {
66        ready(T::from_context(&context))
67    }
68}