ware

Crates.ioware
lib.rsware
version2.0.2
sourcesrc
created_at2019-10-31 16:15:01.95721
updated_at2023-03-19 16:23:48.361586
descriptionSimple middleware chains
homepagehttps://codeberg.org/shadows_withal/shtola/src/branch/main/ware
repositoryhttps://codeberg.org/shadows_withal/shtola/src/branch/main/ware
max_upload_size
id177175
size8,538
liv (shadows-withal)

documentation

https://docs.rs/ware

README

Ware

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.

Documentation

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

License

Ware is licensed under the AGPL 3.0.

Commit count: 0

cargo fmt