aboutsummaryrefslogtreecommitdiff
path: root/mingling_core/src/asset
diff options
context:
space:
mode:
Diffstat (limited to 'mingling_core/src/asset')
-rw-r--r--mingling_core/src/asset/chain.rs1
-rw-r--r--mingling_core/src/asset/core_invokes.rs271
-rw-r--r--mingling_core/src/asset/global_resource.rs59
-rw-r--r--mingling_core/src/asset/lazy_resource.rs12
4 files changed, 316 insertions, 27 deletions
diff --git a/mingling_core/src/asset/chain.rs b/mingling_core/src/asset/chain.rs
index 423e218..bd504d0 100644
--- a/mingling_core/src/asset/chain.rs
+++ b/mingling_core/src/asset/chain.rs
@@ -12,6 +12,7 @@ pub trait Chain<G> {
#[cfg(feature = "async")]
fn proc(p: Self::Previous) -> impl Future<Output = ChainProcess<G>> + Send;
+ /// Process the previous value and return a future that resolves to a [`ChainProcess<G>`](./enum.ChainProcess.html)
#[cfg(not(feature = "async"))]
fn proc(p: Self::Previous) -> ChainProcess<G>;
}
diff --git a/mingling_core/src/asset/core_invokes.rs b/mingling_core/src/asset/core_invokes.rs
new file mode 100644
index 0000000..6a3da2d
--- /dev/null
+++ b/mingling_core/src/asset/core_invokes.rs
@@ -0,0 +1,271 @@
+use std::marker::PhantomData;
+
+use crate::{
+ AnyOutput, ChainProcess, Grouped, NextProcess, ProgramCollect, RenderResult, ResourceMarker,
+};
+
+/// Type used to invoke Renderers in Mingling
+///
+/// It is marked as `#[non_exhaustive]` and all internal fields are private.
+/// This type can only be implicitly created by the hidden external API
+/// `__resource_marker_default` of `ResourceMarker`.
+///
+/// ```rust,ignore
+/// // You can inject other renderers as types into the current function
+/// // |
+/// #[renderer(buffer)] // vvvvvvvvvvvvvvvvvvvv
+/// fn render_foo(_: ResultFoo, renderer: &RendererInvoker<Bar>) {
+/// let bar = Bar::default();
+/// r_append!(renderer.invoke(bar));
+/// }
+/// ```
+#[non_exhaustive]
+pub struct RendererInvoker<T> {
+ phantom: PhantomData<T>,
+ create_by_res_injection: bool,
+}
+
+impl<T> RendererInvoker<T>
+where
+ T: Send,
+{
+ /// Invoke the renderer with the given value.
+ ///
+ /// This function triggers the rendering pipeline for the provided value `T`.
+ /// It can only be executed when the `RendererInvoker` was created by the resource injection system
+ /// (i.e., via `__resource_marker_default`). If the invoker was created manually or cloned outside
+ /// the injection context, calling this method will panic.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the `RendererInvoker` was not created by the resource injection system.
+ ///
+ /// # Hook
+ ///
+ /// It will not execute any program hooks, because this type is used for **bypassing** or **reusing**, not for flow control.
+ pub fn invoke<C>(&self, value: T) -> RenderResult
+ where
+ C: ProgramCollect<Enum = C> + 'static,
+ T: Grouped<C>,
+ {
+ if !self.create_by_res_injection {
+ panic!(
+ "The current RendererInvoker was not created by the resource injection system, so it cannot be executed!"
+ );
+ }
+ C::render(AnyOutput::new(value))
+ }
+}
+
+impl<T> ResourceMarker for RendererInvoker<T> {
+ fn __resource_marker_clone(&self) -> Self {
+ RendererInvoker {
+ phantom: PhantomData,
+ create_by_res_injection: self.create_by_res_injection,
+ }
+ }
+
+ fn __resource_marker_default() -> Self {
+ // Create RendererInvoker with `create_by_res_injection` marked as true
+ //
+ // Reason: RendererInvoker is designed to only be created through resource injection.
+ // When the resource injection does not find a corresponding value,
+ // this method will be used to generate a default value to pass in.
+ RendererInvoker {
+ phantom: PhantomData,
+ create_by_res_injection: true,
+ }
+ }
+
+ fn __resource_marker_modify<C>(f: impl FnOnce(&mut Self))
+ where
+ C: ProgramCollect<Enum = C> + 'static,
+ {
+ // DO NOTHING
+ //
+ // When ResourceMarker is asked to modify, it should not execute anything.
+ let _ = f;
+ }
+}
+
+/// Type used to invoke Chain in Mingling
+///
+/// It is marked as `#[non_exhaustive]` and all internal fields are private.
+/// This type can only be implicitly created by the hidden external API
+/// `__resource_marker_default` of `ResourceMarker`.
+///
+/// ```rust,ignore
+/// // You can inject other chain as types into the current function
+/// // |
+/// #[chain] // vvvvvvvvvvvvvvvvvvvvv
+/// fn handle_foo(_: EntryFoo, chain: &ChainInvoker<StateBar>) {
+/// let bar = Bar::default();
+/// let next = chain.invoke_once(bar);
+/// }
+/// ```
+#[non_exhaustive]
+pub struct ChainInvoker<T> {
+ phantom: PhantomData<T>,
+ create_by_res_injection: bool,
+}
+
+impl<T> ChainInvoker<T>
+where
+ T: Send,
+{
+ /// Execute one step of the chain with the given value, returning the next state.
+ ///
+ /// This function performs **only a single step** of chain execution — it invokes the
+ /// current handler for value `T` and returns the next [`ChainProcess`] state, without
+ /// automatically continuing the chain. The caller is responsible for proceeding through
+ /// subsequent steps based on the returned state.
+ ///
+ /// It can only be executed when the `ChainInvoker` was created by the resource injection system
+ /// (i.e., via `__resource_marker_default`). If the invoker was created manually or cloned outside
+ /// the injection context, calling this method will panic.
+ ///
+ /// # Special Behavior
+ ///
+ /// If no chain exists for this type, it will convert itself into a `ChainProcess` that routes to the chain and return it.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the `ChainInvoker` was not created by the resource injection system.
+ ///
+ /// # Hooks
+ ///
+ /// It will not execute any program hooks, because this type is used for **bypassing** or **reusing**, not for flow control.
+ #[might_be_async::func]
+ pub fn invoke_once<C>(&self, value: T) -> ChainProcess<C>
+ where
+ C: ProgramCollect<Enum = C> + 'static,
+ T: Grouped<C>,
+ {
+ self.pre_check();
+
+ let any = AnyOutput::new(value);
+
+ if C::has_chain(&any) {
+ might_be_async::invoke!(C::do_chain(any))
+ } else {
+ ChainProcess::Ok((any, NextProcess::Chain))
+ }
+ }
+
+ /// Continuously execute the chain until it is routed to a renderer or can no longer continue
+ ///
+ /// This function can only be called when the `ChainInvoker` was created by the resource injection system
+ /// (i.e., via `__resource_marker_default`). If the invoker was created manually or cloned outside
+ /// the injection context, calling this method will panic.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the `ChainInvoker` was not created by the resource injection system.
+ ///
+ /// # Hooks
+ ///
+ /// It will not execute any program hooks, because this type is used for **bypassing** or **reusing**, not for flow control.
+ #[might_be_async::func]
+ pub fn invoke_to_last<C>(&self, value: T) -> ChainProcess<C>
+ where
+ C: ProgramCollect<Enum = C> + 'static,
+ T: Grouped<C>,
+ {
+ self.pre_check();
+
+ let mut current = might_be_async::invoke!(C::do_chain(AnyOutput::new(value)));
+
+ loop {
+ match current {
+ ChainProcess::Ok((any, NextProcess::Chain)) => {
+ if C::has_chain(&any) {
+ current = might_be_async::invoke!(C::do_chain(any));
+ } else {
+ // If the next step of this type does not have a Chain, reconstruct it back
+ return ChainProcess::Ok((any, NextProcess::Chain));
+ }
+ }
+ _ => return current,
+ }
+ }
+ }
+
+ /// Continuously execute the chain until it is rendered into a RenderResult
+ ///
+ /// This function can only be called when the `ChainInvoker` was created by the resource injection system
+ /// (i.e., via `__resource_marker_default`). If the invoker was created manually or cloned outside
+ /// the injection context, calling this method will panic.
+ ///
+ /// # Special Behavior
+ ///
+ /// If an error occurs during rendering, or the result type does not contain a renderer, it will be rendered as an empty RenderResult
+ ///
+ /// # Panics
+ ///
+ /// Panics if the `ChainInvoker` was not created by the resource injection system.
+ ///
+ /// # Hooks
+ ///
+ /// It will not execute any program hooks, because this type is used for **bypassing** or **reusing**, not for flow control.
+ #[might_be_async::func]
+ pub fn invoke_to_result<C>(&self, value: T) -> RenderResult
+ where
+ C: ProgramCollect<Enum = C> + 'static,
+ T: Grouped<C>,
+ {
+ self.pre_check();
+
+ let last = might_be_async::invoke!(self.invoke_to_last(value));
+
+ match last {
+ ChainProcess::Err(_) => RenderResult::new(),
+ ChainProcess::Ok((any, _)) => {
+ if C::has_renderer(&any) {
+ C::render(any)
+ } else {
+ RenderResult::new()
+ }
+ }
+ }
+ }
+
+ #[inline(always)]
+ fn pre_check(&self) {
+ if !self.create_by_res_injection {
+ panic!(
+ "The current ChainInvoker was not created by the resource injection system, so it cannot be executed!"
+ );
+ }
+ }
+}
+
+impl<T> ResourceMarker for ChainInvoker<T> {
+ fn __resource_marker_clone(&self) -> Self {
+ ChainInvoker {
+ phantom: PhantomData,
+ create_by_res_injection: self.create_by_res_injection,
+ }
+ }
+
+ fn __resource_marker_default() -> Self {
+ // Create ChainInvoker with `create_by_res_injection` marked as true
+ //
+ // Reason: ChainInvoker is designed to only be created through resource injection.
+ // When the resource injection does not find a corresponding value,
+ // this method will be used to generate a default value to pass in.
+ ChainInvoker {
+ phantom: PhantomData,
+ create_by_res_injection: true,
+ }
+ }
+
+ fn __resource_marker_modify<C>(f: impl FnOnce(&mut Self))
+ where
+ C: ProgramCollect<Enum = C> + 'static,
+ {
+ // DO NOTHING
+ //
+ // When ResourceMarker is asked to modify, it should not execute anything.
+ let _ = f;
+ }
+}
diff --git a/mingling_core/src/asset/global_resource.rs b/mingling_core/src/asset/global_resource.rs
index a610378..18e4446 100644
--- a/mingling_core/src/asset/global_resource.rs
+++ b/mingling_core/src/asset/global_resource.rs
@@ -38,7 +38,7 @@ where
{
let mut new_res = match Arc::try_unwrap(std::mem::take(arc_res)) {
Ok(val) => val,
- Err(arc) => (*arc).res_clone(),
+ Err(arc) => (*arc).__resource_marker_clone(),
};
let r = f(&mut new_res);
*arc_res = Arc::new(new_res);
@@ -57,7 +57,7 @@ where
Res: 'static + Default + ResourceMarker + Send + Sync,
{
let Ok(mut guard) = self.resources.lock() else {
- let mut default_res = Res::res_default();
+ let mut default_res = Res::__resource_marker_default();
return f(&mut default_res);
};
if let Some(arc_res) = guard
@@ -66,13 +66,13 @@ where
{
let mut new_res = match Arc::try_unwrap(std::mem::take(arc_res)) {
Ok(val) => val,
- Err(arc) => (*arc).res_clone(),
+ Err(arc) => (*arc).__resource_marker_clone(),
};
let r = f(&mut new_res);
*arc_res = Arc::new(new_res);
r
} else {
- let mut default_res = Res::res_default();
+ let mut default_res = Res::__resource_marker_default();
f(&mut default_res)
}
}
@@ -85,7 +85,7 @@ where
#[must_use]
pub fn __extract_res_mut<Res: 'static + Default + ResourceMarker + Send + Sync>(&self) -> Res {
let Ok(mut guard) = self.resources.lock() else {
- return Res::res_default();
+ return Res::__resource_marker_default();
};
if let Some(arc_res) = guard
.get_mut(&TypeId::of::<Res>())
@@ -93,10 +93,10 @@ where
{
match Arc::try_unwrap(std::mem::take(arc_res)) {
Ok(val) => val,
- Err(arc) => (*arc).res_clone(),
+ Err(arc) => (*arc).__resource_marker_clone(),
}
} else {
- Res::res_default()
+ Res::__resource_marker_default()
}
}
@@ -136,7 +136,7 @@ where
&self,
) -> GlobalResource<Res> {
self.res()
- .unwrap_or_else(|| GlobalResource::from(Arc::new(Res::res_default())))
+ .unwrap_or_else(|| GlobalResource::from(Arc::new(Res::__resource_marker_default())))
}
}
@@ -176,24 +176,38 @@ impl<ResType: 'static + Send + Sync> AsRef<ResType> for GlobalResource<ResType>
/// Resource marker trait, types that implement the Clone and Default traits can be considered as resources
pub trait ResourceMarker {
+ /// Clone the resource. This is an internal method used by the resource injection system
+ /// and should not be called directly by user code.
#[must_use]
- fn res_clone(&self) -> Self;
- fn res_default() -> Self;
- fn modify<C>(f: impl FnOnce(&mut Self))
+ #[doc(hidden)]
+ fn __resource_marker_clone(&self) -> Self;
+
+ /// Create a default instance of the resource. This is an internal method used by the
+ /// resource injection system and should not be called directly by user code.
+ #[doc(hidden)]
+ fn __resource_marker_default() -> Self;
+
+ /// Modify the resource using a closure. This is an internal method used by the resource
+ /// injection system and should not be called directly by user code.
+ #[doc(hidden)]
+ fn __resource_marker_modify<C>(f: impl FnOnce(&mut Self))
where
C: ProgramCollect<Enum = C> + 'static;
}
-impl<T: Default + Clone + Send + Sync + 'static> ResourceMarker for T {
- fn res_clone(&self) -> Self {
+impl<T> ResourceMarker for T
+where
+ T: Default + Clone + Send + Sync + 'static,
+{
+ fn __resource_marker_clone(&self) -> Self {
Clone::clone(self)
}
- fn res_default() -> Self {
+ fn __resource_marker_default() -> Self {
Default::default()
}
- fn modify<C>(f: impl FnOnce(&mut Self))
+ fn __resource_marker_modify<C>(f: impl FnOnce(&mut Self))
where
C: ProgramCollect<Enum = C> + 'static,
{
@@ -227,38 +241,41 @@ mod tests {
#[test]
fn resource_marker_i32_res_clone() {
let val = 42i32;
- let cloned = val.res_clone();
+ let cloned = val.__resource_marker_clone();
assert_eq!(cloned, 42);
}
#[test]
fn resource_marker_i32_res_default() {
- assert_eq!(<i32 as ResourceMarker>::res_default(), 0i32);
+ assert_eq!(<i32 as ResourceMarker>::__resource_marker_default(), 0i32);
}
#[test]
fn resource_marker_string_res_clone() {
let val = "hello".to_string();
- let cloned = val.res_clone();
+ let cloned = val.__resource_marker_clone();
assert_eq!(cloned, "hello");
}
#[test]
fn resource_marker_string_res_default() {
- assert_eq!(<String as ResourceMarker>::res_default(), "");
+ assert_eq!(<String as ResourceMarker>::__resource_marker_default(), "");
}
#[test]
fn resource_marker_vec_res_clone() {
let val = vec![1, 2, 3];
- let cloned = val.res_clone();
+ let cloned = val.__resource_marker_clone();
assert_eq!(cloned, vec![1, 2, 3]);
}
#[test]
fn resource_marker_vec_res_default() {
let empty: Vec<i32> = vec![];
- assert_eq!(<Vec<i32> as ResourceMarker>::res_default(), empty);
+ assert_eq!(
+ <Vec<i32> as ResourceMarker>::__resource_marker_default(),
+ empty
+ );
}
// Note: Tests for Program::with_resource, res(), res_or_route(), res_or_default(),
diff --git a/mingling_core/src/asset/lazy_resource.rs b/mingling_core/src/asset/lazy_resource.rs
index 918aeb2..3cb7563 100644
--- a/mingling_core/src/asset/lazy_resource.rs
+++ b/mingling_core/src/asset/lazy_resource.rs
@@ -280,7 +280,7 @@ where
{
/// Clones the lazy resource. The cloned resource retains any initialized value,
/// but the initializer is reset to `T::default()`.
- fn res_clone(&self) -> Self {
+ fn __resource_marker_clone(&self) -> Self {
match &self.inner {
LazyInner::Init(t, _) => Self {
inner: LazyInner::Init(t.clone(), None),
@@ -290,7 +290,7 @@ where
}
/// Returns a default lazy resource (uninitialized, using `T::default()` as the initializer).
- fn res_default() -> Self
+ fn __resource_marker_default() -> Self
where
T: Default,
{
@@ -298,7 +298,7 @@ where
}
/// Modifies the current lazy resource via the `this` context provided by `C`.
- fn modify<C>(f: impl FnOnce(&mut Self))
+ fn __resource_marker_modify<C>(f: impl FnOnce(&mut Self))
where
C: ProgramCollect<Enum = C> + 'static,
{
@@ -583,7 +583,7 @@ mod tests {
fn res_clone_of_initialized_clones_value() {
let mut r = LazyRes::new(|| vec![1, 2, 3]);
r.get_ref();
- let cloned = r.res_clone();
+ let cloned = r.__resource_marker_clone();
assert!(cloned.is_initialized());
assert_eq!(cloned.into_inner(), Some(vec![1, 2, 3]));
}
@@ -591,14 +591,14 @@ mod tests {
#[test]
fn res_clone_of_uninitialized_creates_default() {
let r: LazyRes<Vec<i32>> = LazyRes::new(|| vec![1, 2, 3]);
- let cloned = r.res_clone();
+ let cloned = r.__resource_marker_clone();
// The source is uninitialized, so res_clone returns a default lazy
assert!(!cloned.is_initialized());
}
#[test]
fn res_default_returns_uninitialized() {
- let r: LazyRes<i32> = LazyRes::<i32>::res_default();
+ let r: LazyRes<i32> = LazyRes::<i32>::__resource_marker_default();
assert!(!r.is_initialized());
}