use trussed_core::{
api::{Reply, Request},
Error,
};
use crate::{
platform::Platform,
service::ServiceResources,
types::{Context, CoreContext},
};
#[derive(Debug, Clone)]
pub enum BackendId<I> {
Core,
Custom(I),
}
pub trait Backend {
type Context: Default;
fn request<P: Platform>(
&mut self,
core_ctx: &mut CoreContext,
backend_ctx: &mut Self::Context,
request: &Request,
resources: &mut ServiceResources<P>,
) -> Result<Reply, Error> {
let _ = (core_ctx, backend_ctx, request, resources);
Err(Error::RequestNotAvailable)
}
}
pub trait Dispatch {
type BackendId: 'static;
type Context: Default;
fn request<P: Platform>(
&mut self,
backend: &Self::BackendId,
ctx: &mut Context<Self::Context>,
request: &Request,
resources: &mut ServiceResources<P>,
) -> Result<Reply, Error> {
let _ = (backend, ctx, request, resources);
Err(Error::RequestNotAvailable)
}
}
#[derive(Debug, Default)]
pub struct CoreOnly;
#[cfg(not(feature = "serde-extensions"))]
impl Dispatch for CoreOnly {
type BackendId = NoId;
type Context = crate::types::NoData;
}
pub enum NoId {}
impl TryFrom<u8> for NoId {
type Error = Error;
fn try_from(_: u8) -> Result<Self, Self::Error> {
Err(Error::InternalError)
}
}
#[derive(Debug)]
pub struct OptionalBackend<T>(Option<T>);
impl<T> OptionalBackend<T> {
pub fn new(backend: Option<T>) -> Self {
Self(backend)
}
pub fn inner(&mut self) -> Result<&mut T, Error> {
self.0.as_mut().ok_or(Error::RequestNotAvailable)
}
pub fn into_inner(self) -> Option<T> {
self.0
}
}
impl<T> Default for OptionalBackend<T> {
fn default() -> Self {
Self(None)
}
}
impl<T> From<T> for OptionalBackend<T> {
fn from(backend: T) -> Self {
Self(Some(backend))
}
}
impl<T> From<Option<T>> for OptionalBackend<T> {
fn from(backend: Option<T>) -> Self {
Self(backend)
}
}
impl<T: Backend> Backend for OptionalBackend<T> {
type Context = T::Context;
fn request<P: Platform>(
&mut self,
core_ctx: &mut CoreContext,
backend_ctx: &mut Self::Context,
request: &Request,
resources: &mut ServiceResources<P>,
) -> Result<Reply, Error> {
self.inner()?
.request(core_ctx, backend_ctx, request, resources)
}
}