rpc_router/resource/
from_resources.rs

1use crate::Resources;
2use serde::Serialize;
3use std::any::type_name;
4
5pub trait FromResources {
6	fn from_resources(resources: &Resources) -> FromResourcesResult<Self>
7	where
8		Self: Sized + Clone + Send + Sync + 'static,
9	{
10		resources
11			.get::<Self>()
12			.ok_or_else(FromResourcesError::resource_not_found::<Self>)
13	}
14}
15
16/// Implements `FromResources` to allow requesting Option<T>
17/// when T implements FromResources.
18impl<T> FromResources for Option<T>
19where
20	T: FromResources,
21	T: Sized + Clone + Send + Sync + 'static,
22{
23	fn from_resources(resources: &Resources) -> FromResourcesResult<Self> {
24		Ok(resources.get::<T>())
25	}
26}
27
28// region:    --- Error
29
30pub type FromResourcesResult<T> = core::result::Result<T, FromResourcesError>;
31
32#[derive(Debug, Serialize)]
33pub enum FromResourcesError {
34	ResourceNotFound(&'static str),
35}
36
37impl FromResourcesError {
38	pub fn resource_not_found<T: ?Sized>() -> FromResourcesError {
39		let name: &'static str = type_name::<T>();
40		Self::ResourceNotFound(name)
41	}
42}
43
44impl core::fmt::Display for FromResourcesError {
45	fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
46		write!(fmt, "{self:?}")
47	}
48}
49
50impl std::error::Error for FromResourcesError {}
51
52// endregion: --- Error