Skip to main content

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 trait ComputerRef that implementations target and the wiring key ComputerRefComponent, while CanComputeRef stays the consumer trait callers use.
  • #[prefix] — registers the component in DefaultNamespace under the path @cgp.extra.handler, so a context that joins that namespace binds its provider at @cgp.extra.handler.ComputerRefComponent rather than at the bare key.
  • #[derive_delegate] — generates the legacy UseDelegate and UseInputDelegate providers, which dispatch on the Code tag and on the Input type through an inner table; the open statement 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 a Computer takes an owned input that dereferences to Target, such as a Box<String> for Target = String, and calls the ComputerRef provider P on input.deref(). Any ComputerRef provider serves this direction.
  • PromoteRef<P> as a ComputerRef passes the borrow &Input through as the input of the Computer provider P, so P must implement Computer for &'a Input at every lifetime 'a. A computer written for an owned u64 does not, so it cannot answer compute_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.

The ideas behind it:

  • Handlers — the computation family and its sync, async, fallible, and input-passing axes.

Source​


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.