Crates.io | matrix_match |
lib.rs | matrix_match |
version | 1.0.0 |
source | src |
created_at | 2023-02-06 00:30:23.470555 |
updated_at | 2023-02-06 00:30:23.470555 |
description | Macro to match on two values at the same time |
homepage | |
repository | https://github.com/EbbDrop/matrix_match |
max_upload_size | |
id | 777547 |
size | 23,655 |
This crate provides a macro to easily match on two values at the same time.
The macro takes a matrix of possible results and patterns for the rows and columns. The expression at the intersection of the matching patterns gets executed and possibly returned.
This crate can be used in no-std contexts.
use matrix_match::matrix_match;
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum Light {
Red,
Orange,
Green,
}
fn next(light: Light, car_waiting: bool) -> Light {
use Light::*;
matrix_match!(
(light, car_waiting) ; true , false =>
Red => Green , Red ;
Orange => Red , Red ;
Green => Green , Orange ;
)
}
fn main() {
assert_eq!(next(Light::Red, true ), Light::Green);
assert_eq!(next(Light::Red, false), Light::Red);
assert_eq!(next(Light::Orange, true ), Light::Red);
assert_eq!(next(Light::Orange, false), Light::Red);
assert_eq!(next(Light::Green, true ), Light::Green);
assert_eq!(next(Light::Green, false), Light::Orange);
}
The macro first creates a match for the row patterns and then for every row creates a match for the column patterns. There exists a implementation in the single-match branch that only creates a single match. After some benchmarking (also in that branch) it was determined that both implementation are just as fast at run time and so the simpler one was chosen.