Crate fluid_macro

Source
Expand description

Contains fluid, a macro that allows you to write long method call chains as a series of steps instead.

§Basic Usage

let x = fluid!("123", {
    parse::<i32>();
    unwrap_or_default();
    clamp(5, 100);
    to_string();
});

assert_eq!(x, "100");

This is equivalent to writing:

let x = Some(123).unwrap_or_default().clamp(5, 100).to_string();

assert_eq!(x, "100");

§Nested blocks

Methods that have a final argument that is a one-argument closure support an alternate block syntax:

struct Example(i32);

impl Example {
    fn add(mut self, arg: i32) -> Self {
        self.0 += arg;
        self
    }

    fn modify(mut self, f: impl FnOnce(i32) -> i32) -> Self {
        self.0 = f(self.0);
        self
    }
}

let x = fluid!(Example(0), {
    add(15);
    modify() {
        clamp(20, 50);
    }
    add(15);
});

assert_eq!(x.0, 35);

The above is equivalent to writing:

let x = Example(0).add(15).modify(|b| b.clamp(20, 50)).add(15);

assert_eq!(x.0, 35)

§Chaining in non-method things

Although it looks a bit weird, you can write casts and operations with this syntax:

let x = fluid!(5i32, {
    [+ 5];
    [as u8];
    to_string();
});

assert_eq!(x, "10");

The entire chained expression so far will be placed in the first position of the partial expression in square brackets.

The above expands to:

let x = ((5i32 + 5) as u8).to_string();

assert_eq!(x, "10");

§Known limitations

It’s not very friendly to the IDE whilst writing. You will have to already know the names of methods you want to use. After compilation, however, symbol lookup and the like works fine.

Macros§

fluid
General-purpose macro that allows you to write long method chains as a series of statements. See the crate documentation for more details.