6 releases (stable)

2.0.2 Mar 19, 2023
2.0.1 Jul 7, 2021
1.0.0 Jan 17, 2021
0.1.0 Oct 31, 2019

#781 in Data structures

Download history 4/week @ 2024-03-10 30/week @ 2024-03-31 11/week @ 2024-04-21 3/week @ 2024-04-28

78 downloads per month
Used in 3 crates (via shtola)


72 lines


Immutable and mutable middleware chains.

Ware allows you to create middleware chains that pass through and modify a value as they go along. You can imagine a middleware chain as something like this:

let initial_value = 1;

fn middleware_1(value: i32) -> i32 {
	value + 1

fn middleware_2(value: i32) -> i32 {
	value * 5

let result = middleware_2(middleware_1(initial_value));
assert_eq!(result, 10);

Mutable middleware

The default is middleware that has free access to mutate the value that's being passed through, thanks to RefCell:

use ware::Ware;
use std::ops::{Add, Mul};

let mut middleware_chain: Ware<i32> = Ware::new();

middleware_chain.wrap(Box::new(|mut num| {
	*num = num.add(1);
middleware_chain.wrap(Box::new(|mut num| {
	*num = num.mul(5);

let result = middleware_chain.run(1);
assert_eq!(result, 10);

These middleware functions have to return a () unit struct, so the best choice is to leave out a return statement.

Remember to always dereference the argument in a middleware function when directly reassigning, because otherwise you're destroying the RefCell.

Immutable middleware

If you instead want to rely on immutability, replace ware::Ware with ware::im::Ware:

use ware::im::Ware;

let mut middleware_chain: Ware<i32> = Ware::new();

middleware_chain.wrap(Box::new(|num| num + 1));
middleware_chain.wrap(Box::new(|num| num * 5));

let result = middleware_chain.run(1);
assert_eq!(result, 10);

Functions that get registered as middleware cannot directly modify their variables, as they have be of the Fn trait. I would recommend using immutable data structures that are efficient when duplicating values.

Generally, I'd recommend immutable Ware when you're working with simple data or when immutability is absolutely critical to you. However, when you're working with more complex data structures such as a HashMap, that provides its own modification tools, you might want to opt for the mutable Ware instead. You cannot do both, either use the mutable or the immutable variety.


The documentation is available at https://docs.rs/ware.


Ware is licensed under the AGPL 3.0.

No runtime deps