token_cell/
monads.rs

1use core::convert::Infallible;
2
3use crate::{
4    core::{TokenGuard, TokenGuardMut},
5    prelude::*,
6};
7#[must_use = "TokenMaps must be applied to do anything. Note that the closure execution will be deferred to the call-site of `apply/try_apply`"]
8pub struct TokenMap<
9    'a,
10    T: ?Sized,
11    U,
12    F: FnOnce(TokenGuard<'a, T, Token>) -> U,
13    Cell: TokenCellTrait<T, Token> + ?Sized,
14    Token: TokenTrait + 'a,
15> {
16    pub(crate) cell: &'a Cell,
17    pub(crate) f: F,
18    pub(crate) marker: core::marker::PhantomData<(&'a T, U, Token)>,
19}
20impl<
21        'a,
22        T: ?Sized,
23        U,
24        F: FnOnce(TokenGuard<'a, T, Token>) -> U,
25        Token: TokenTrait,
26        Cell: TokenCellTrait<T, Token>,
27    > TokenMap<'a, T, U, F, Cell, Token>
28{
29    pub fn try_apply(self, token: &'a Token) -> Result<U, Token::ComparisonError> {
30        let borrowed = self.cell.try_guard(token)?;
31        Ok((self.f)(borrowed))
32    }
33    pub fn apply(self, token: &'a Token) -> U
34    where
35        Token: TokenTrait<ComparisonError = Infallible>,
36    {
37        let borrowed = self.cell.try_guard(token).unwrap();
38        (self.f)(borrowed)
39    }
40}
41#[must_use = "TokenMaps must be applied to do anything. Note that the closure execution will be deferred to the call-site of `apply/try_apply`"]
42pub struct TokenMapMut<
43    'a,
44    T: ?Sized,
45    U,
46    F: FnOnce(TokenGuardMut<'a, T, Token>) -> U,
47    Cell: TokenCellTrait<T, Token> + ?Sized,
48    Token: TokenTrait + 'a,
49> {
50    pub(crate) cell: &'a Cell,
51    pub(crate) f: F,
52    pub(crate) marker: core::marker::PhantomData<(&'a T, U, Token)>,
53}
54impl<
55        'a,
56        T: ?Sized,
57        U,
58        F: FnOnce(TokenGuardMut<'a, T, Token>) -> U,
59        Token: TokenTrait,
60        Cell: TokenCellTrait<T, Token>,
61    > TokenMapMut<'a, T, U, F, Cell, Token>
62{
63    pub fn try_apply(self, token: &'a mut Token) -> Result<U, Token::ComparisonError> {
64        let borrowed = self.cell.try_guard_mut(token)?;
65        Ok((self.f)(borrowed))
66    }
67    pub fn apply(self, token: &'a mut Token) -> U
68    where
69        Token: TokenTrait<ComparisonError = Infallible>,
70    {
71        let borrowed = self.cell.try_guard_mut(token).unwrap();
72        (self.f)(borrowed)
73    }
74}
75impl<T: ?Sized, Token: TokenTrait> TokenCell<T, Token> {}