ComputerRef
The by-reference member of the handler family: a Computer that borrows its input.
Overview
In Context-Generic Programming (CGP), ComputerRef is a Computer that
takes its input by reference instead of by value. CGP enables pluggable trait implementations in
Rust, and ComputerRef is the component that lets a context plug in a computation that reads its
input. A synchronous, infallible computation that only reads its argument fits ComputerRef,
whose method receives &Input where CanCompute receives Input, so the caller keeps ownership.
Everything else is the same: it turns the input into an Output under a phantom Code tag, against
a context (the type the implementation runs against), and
returns the Output directly with no failure path.
It differs from Computer on the input axis alone. Like Computer it never names an error type, so
it does not have HasErrorType as a
supertrait. See the handler family overview for
how the members relate.
Definition
CanComputeRef is defined as:
#[cgp_component(ComputerRef)]
#[prefix(@cgp.extra.handler in DefaultNamespace)]
#[derive_delegate(UseDelegate<Code>)]
#[derive_delegate(UseInputDelegate<Input>)]
pub trait CanComputeRef<Code, Input> {
type Output;
fn compute_ref(&self, _code: PhantomData<Code>, input: &Input) -> Self::Output;
}
Its attributes:
#[cgp_component]— turns the trait into a component: its argument names the provider traitComputerRefthat implementations target and the wiring keyComputerRefComponent, whileCanComputeRefstays 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.ComputerRefComponentrather 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.
Usage
ComputerRefComponent, the provider trait ComputerRef, and the consumer trait CanComputeRef
are imported from cgp::extra::handler. The method borrows the input:
fn compute_ref(&self, _code: PhantomData<Code>, input: &Input) -> Self::Output;
A context gains the operation by wiring ComputerRefComponent to a provider, and the component
dispatches on both the Code tag and the Input type. The
PromoteRef combinator, imported from
cgp::extra::handler, bridges the owned and borrowed forms in both directions, and the two
directions ask different things of the inner provider:
PromoteRef<P>as aComputertakes an owned input that dereferences toTarget, such as aBox<String>forTarget = String, and calls theComputerRefproviderPoninput.deref(). AnyComputerRefprovider serves this direction.PromoteRef<P>as aComputerRefpasses the borrow&Inputthrough as the input of theComputerproviderP, soPmust implementComputerfor&'a Inputat every lifetime'a. A computer written for an ownedu64does not, so it cannot answercompute_ref.
Its async counterpart is AsyncComputerRef.
Examples
A provider that measures a borrowed string, wired for borrowed input and, through PromoteRef, for
an owned input that dereferences to it:
use core::marker::PhantomData;
use cgp::extra::handler::{Computer, ComputerComponent, ComputerRefComponent};
use cgp::prelude::*;
use cgp::extra::handler::{CanCompute, CanComputeRef, ComputerRef, PromoteRef};
#[cgp_new_provider]
impl<Context, Code> ComputerRef<Context, Code, String> for StringLength {
type Output = usize;
fn compute_ref(_context: &Context, _code: PhantomData<Code>, input: &String) -> usize {
input.len()
}
}
pub struct App;
delegate_components! {
App {
ComputerRefComponent: StringLength,
ComputerComponent: PromoteRef<StringLength>,
}
}
check_components! {
App {
ComputerRefComponent: ((), String),
ComputerComponent: ((), Box<String>),
}
}
pub fn demo() {
let name = "hello".to_owned();
assert_eq!(App.compute_ref(PhantomData::<()>, &name), 5);
assert_eq!(App.compute(PhantomData::<()>, Box::new(name)), 5);
}
compute_ref reads name without taking it, so the caller can still move it into the Box on the
next line. The compute call hands over the owned Box<String>, and PromoteRef dereferences it
to the String that StringLength reads. App is an environmental
context, and the component is
parameter-targeted: the computation
acts on the Input, while App decides the provider.
When to use it
Reach for ComputerRef when a synchronous, infallible computation only needs to read its input.
It avoids handing ownership to a computation that does not consume the value, which matters when the
caller reuses the input afterwards.
Reach for Computer instead when the computation takes the input by value, which
is the more common case, and for AsyncComputerRef when a borrowed-input
computation must also await. If the computation can fail, use
TryComputerRef.
Common Mistakes
An owned-input Computer cannot answer compute_ref. Wiring ComputerRefComponent to
PromoteRef<Double>, for a Double that implements Computer for u64, fails at the check,
because the promotion asks Double for u64 borrowed at every lifetime. The compiler's note names
that requirement:
= note: required for `Double` to implement `for<'a> Computer<App, (), &'a u64>`
The same applies to the ComputerRefComponent entry of the PromoteComputer bundle and to a
#[cgp_computer] function over an owned parameter. Write the
provider as a ComputerRef, or give the function a reference parameter such as value: &u64.
Related constructs
Computer— the owned-input counterpart.AsyncComputerRef— the async version of this by-reference variant.TryComputerRef— the fallible by-reference computer.- Handler combinators — the
PromoteRefcombinator bridging owned and borrowed inputs.
The ideas behind it:
- Handlers — the computation family and its sync, async, fallible, and input-passing axes.
Source
ComputerandComputerRef:computer.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.