use crate::{Context, Result};
#[async_trait::async_trait]
pub trait Guard {
async fn check(&self, ctx: &Context<'_>) -> Result<()>;
}
#[async_trait::async_trait]
impl<T> Guard for T
where
T: Fn(&Context<'_>) -> Result<()> + Send + Sync + 'static,
{
async fn check(&self, ctx: &Context<'_>) -> Result<()> {
self(ctx)
}
}
pub trait GuardExt: Guard + Sized {
fn and<R: Guard>(self, other: R) -> And<Self, R> {
And(self, other)
}
fn or<R: Guard>(self, other: R) -> Or<Self, R> {
Or(self, other)
}
}
impl<T: Guard> GuardExt for T {}
pub struct And<A: Guard, B: Guard>(A, B);
#[async_trait::async_trait]
impl<A: Guard + Send + Sync, B: Guard + Send + Sync> Guard for And<A, B> {
async fn check(&self, ctx: &Context<'_>) -> Result<()> {
self.0.check(ctx).await?;
self.1.check(ctx).await
}
}
pub struct Or<A: Guard, B: Guard>(A, B);
#[async_trait::async_trait]
impl<A: Guard + Send + Sync, B: Guard + Send + Sync> Guard for Or<A, B> {
async fn check(&self, ctx: &Context<'_>) -> Result<()> {
if self.0.check(ctx).await.is_ok() {
return Ok(());
}
self.1.check(ctx).await
}
}