HandlerRef
The by-reference member of the handler family's general corner: a Handler that
borrows its input.
Overview
In Context-Generic Programming (CGP), HandlerRef is a Handler that
takes its input by reference. CGP enables pluggable trait implementations in Rust, and HandlerRef
is the component that lets a context plug in an async, fallible computation that reads its input. It is asynchronous
and fallible like the general handler, so it awaits and may return the abstract error of the
context, the type the implementation runs against, but its
method receives &Input where CanHandle receives Input. It suits an async, fallible computation
that reads its argument rather than consuming it, such as a request handler that inspects a borrowed
request.
Because it can fail, it has HasErrorType as a
supertrait, which supplies the Error it names in its
Result. See the handler family overview for how the members relate and promote.
Definition
CanHandleRef is defined as:
#[async_trait]
#[cgp_component(HandlerRef)]
#[prefix(@cgp.extra.handler in DefaultNamespace)]
#[derive_delegate(UseDelegate<Code>)]
#[derive_delegate(UseInputDelegate<Input>)]
#[use_type(HasErrorType.Error)]
pub trait CanHandleRef<Code, Input> {
type Output;
async fn handle_ref(
&self,
_tag: PhantomData<Code>,
input: &Input,
) -> Result<Self::Output, Error>;
}
Its attributes:
#[async_trait]— rewrites theasync fninto a method returning-> impl Future, the lint-clean, allocation-free form, which adds noSendbound to the future.#[cgp_component]— turns the trait into a component: its argument names the provider traitHandlerRefthat implementations target and the wiring keyHandlerRefComponent, whileCanHandleRefstays the consumer trait callers use.#[prefix]— registers the component inDefaultNamespaceunder the path@cgp.extra.handler, so a context that joins that namespace binds its provider at@cgp.extra.handler.HandlerRefComponentrather than at the bare key.#[derive_delegate]— generates the legacyUseDelegateandUseInputDelegateproviders, which dispatch on theCodetag and on theInputtype through an inner table; theopenstatement replaces both, dispatching on either parameter or on the pair.#[use_type]— addsHasErrorTypeas a supertrait and rewrites the bareErrorto<Self as HasErrorType>::Error.
Usage
HandlerRefComponent, the provider trait HandlerRef, and the consumer trait CanHandleRef are
not in the prelude, and are imported from cgp::extra::handler. The method is async, borrows
the input, and returns a Result:
async fn handle_ref(&self, _tag: PhantomData<Code>, input: &Input) -> Result<Self::Output, Error>;
A context gains the operation by wiring HandlerRefComponent to a provider and by wiring an error
type, and the component dispatches on both the Code tag and the Input type. Besides a
hand-written provider, the PromoteRef combinator answers
it from a Handler written for &'a Input at every lifetime, which is the HandlerRefComponent
entry of every promotion bundle. In the other direction it lets a HandlerRef provider answer
handle for an owned input that dereferences to its Input. See
ComputerRef for the two directions, which work the same way here.
Examples
An async, fallible provider over a borrowed request, wired into a context and awaited:
use core::marker::PhantomData;
use cgp::extra::handler::{CanHandleRef, HandlerRef, HandlerRefComponent};
use cgp::prelude::*;
use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent};
use cgp::extra::error::RaiseFrom;
#[cgp_impl(new NonEmptyLength)]
#[uses(CanRaiseError<String>)]
#[use_type(HasErrorType.Error)]
impl<Code> HandlerRef<Code, String> {
type Output = usize;
async fn handle_ref(
&self,
_code: PhantomData<Code>,
input: &String,
) -> Result<Self::Output, Error> {
if input.is_empty() {
return Err(Self::raise_error("empty request".to_owned()));
}
Ok(input.len())
}
}
pub struct App;
delegate_components! {
App {
ErrorTypeProviderComponent: UseType<String>,
ErrorRaiserComponent: RaiseFrom,
HandlerRefComponent: NonEmptyLength,
}
}
check_components! {
App {
HandlerRefComponent: ((), String),
}
}
pub async fn demo() {
let request = "GET /".to_owned();
assert_eq!(App.handle_ref(PhantomData::<()>, &request).await, Ok(5));
assert_eq!(
App.handle_ref(PhantomData::<()>, &String::new()).await,
Err("empty request".to_owned())
);
}
NonEmptyLength raises a String message into the context's error, which App sets to String,
so RaiseFrom raises it through the identity From impl.
The caller keeps ownership of request. App is an environmental
context, and the component is
parameter-targeted: the computation
acts on the Input, while App decides the provider and the error type.
When to use it
Reach for HandlerRef when an async, fallible computation only needs to read its input. Generic
code bounded by CanHandleRef accepts a provider for any by-reference member that is lifted into
it, through a promotion bundle or a hand-written chain of promotions.
Reach for Handler instead when the computation takes the input by value, which is
the more common case, and for TryComputerRef when a borrowed-input
fallible computation is synchronous. Do not write a HandlerRef by hand when a simpler member fits:
implement that and let the wiring promote it.
Related constructs
Handler— the owned-input counterpart, and the family's general corner.TryComputerRef— the synchronous fallible by-reference computer.AsyncComputerRef— the infallible async by-reference computer.HasErrorType— the supertrait supplying theErrorthis returns.PromoteRef— bridgesHandlerandHandlerRef.
The ideas behind it:
- Handlers — the computation family and its sync, async, fallible, and input-passing axes.
- Recovering
Sendbounds — restoring theSendguarantee the async method does not carry.
Source
HandlerandHandlerRef:handler.rsPromoteRef:promote_ref.rs- Re-exported through
cgp::extra::handler.
An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.