Crates.io | ware |
lib.rs | ware |
version | 2.0.2 |
source | src |
created_at | 2019-10-31 16:15:01.95721 |
updated_at | 2023-03-19 16:23:48.361586 |
description | Simple middleware chains |
homepage | https://codeberg.org/shadows_withal/shtola/src/branch/main/ware |
repository | https://codeberg.org/shadows_withal/shtola/src/branch/main/ware |
max_upload_size | |
id | 177175 |
size | 8,538 |
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);
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
.
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.