pipe{i}
pipei provides a zero-cost, type-safe way to chain multi-argument functions using method syntax. It turns a function call f(x, y, z) into a method call x.pipe(f)(y, z).
It also includes a tap operator for side-effects (logging, mutation) that returns the original value.
This project is inspired by the UMCS proposal.
It generalizes the tap crate to support multi-argument pipelines.
Note: Requires #![feature(impl_trait_in_assoc_type)] on nightly.
To keep compile times as fast as possible, enable only the arities you need.
The crate supports arities from 0 (a single argument) up to 50. Use features like up_to_N (where N is a multiple of 5) or specific individual arity features
[]
= "*" # default: features = ["up_to_5"]
# pipei = { version = "*", features = ["up_to_20"] }
# pipei = { version = "*", features = ["0", "1", "3", "4"] }
Basic chaining
pipe passes the value into the function and returns the result. tap inspects or mutates the input, ignores the result, and returns the original value.
use ;
let maybe_num = 2
.pipe
.pipe
.pipe
.pipe;
assert_eq!;
let val = 2
.tap // Immutable: passes &i32
.tap // Mutable: passes &mut i32
assert_eq!;
Pipe for Method Binding
'pipe' can be used to convert a method into a standalone function. By binding a specific object as the 'self' argument, you create a reusable function that implicitly uses that object's state.
use Pipe;
let season_pass = Discount ;
let calculate_total = season_pass.pipe;
assert_eq!;
TapWith
tap_with runs a side-effect on a projection of the value. This is useful for adapting types (e.g. calling a method to get a different view) or selecting specific fields to reuse generic validation logic.
use TapWith;
// 1. Adapting types (String -> &[u8])
let data = Stringfrom;
data.tap_with;
// 2. Selecting fields
let srv = Server ;
srv.tap_with;
Comparison with the tap crate
The tap crate is the standard solution for continuous chaining. pipei extends this concept to multi-argument functions to address specific issues related to control flow, error handling, and nesting.
When function arguments are the results of other chains (nesting) and those chains involve fallible operations (using ?), standard closure-based chaining becomes difficult to manage.
Consider a workflow where we load a background, load and resize an overlay, composite them, and save the result. Both load and save are fallible (return Result).
Standard Rust:
The logic reads "inside-out": save is written first, but executes last.
save;
Using tap:
We can try to linearize it, but the secondary chain (overlay) must happen inside a closure. Because load("overlay")? uses the ? operator, the closure itself returns a Result.
load?
.pipe?
.pipe;
Using pipei:
The primary flow (load -> composite -> save) remains linear. The secondary flow (overlay -> resize) is handled inline. The ? operator works naturally without changing the pipeline types or requiring and_then.
load?
.pipe
.pipe;