Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Created November 24, 2024 15:42
Show Gist options
  • Save gordonbrander/3157c220918666f33311dc9c97b3f327 to your computer and use it in GitHub Desktop.
Save gordonbrander/3157c220918666f33311dc9c97b3f327 to your computer and use it in GitHub Desktop.
pipe.rs - rust pipeline macro
#[macro_export]
macro_rules! pipe {
// Base case - single function
($value:expr, $func:expr) => {
$func($value)
};
// Recursive case - multiple functions
($value:expr, $func:expr, $($rest:expr),+) => {
pipe!($func($value), $($rest),+)
};
}
// Example usage and tests
#[cfg(test)]
mod tests {
#[test]
fn test_pipe_macro() {
// Test with functions that maintain the same type
let add_one = |x: i32| x + 1;
let multiply_by_two = |x: i32| x * 2;
let subtract_three = |x: i32| x - 3;
let result = pipe!(5, add_one, multiply_by_two, subtract_three);
assert_eq!(result, 9); // ((5 + 1) * 2) - 3 = 9
// Test with functions that change types
let to_string = |x: i32| x.to_string();
let add_exclamation = |s: String| s + "!";
let to_uppercase = |s: String| s.to_uppercase();
let result = pipe!(42, to_string, add_exclamation, to_uppercase);
assert_eq!(result, "42!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment