Add ascii matrix macro

This commit is contained in:
tali 2022-12-13 14:19:24 -05:00
parent 908fa77d8a
commit 91ee995c71
3 changed files with 66 additions and 17 deletions

View File

@ -5,7 +5,8 @@ version = "0.1.0"
edition = "2021"
[features]
default = []
default = ["ascii"]
ascii = []
[dependencies]
# tracing = { version = "0.1", default-features = false}

View File

@ -3,3 +3,28 @@
pub mod matrix;
pub use matrix::Mat;
/// Allows constructing a `Mat` constant with string literals:
///
/// ```
/// # use mino::{mat, Mat};
/// # const MAT: &Mat =
/// mat! {
/// ".......xxx"; // top row (y=2)
/// "x.xxxxxxxx"; // middle row (y=1)
/// "xxxx.xxxxx"; // bottom row (y=0)
/// }
/// # ;
/// ```
#[cfg(any(feature = "ascii", test))]
#[macro_export]
macro_rules! mat {
($($row:literal);* $(;)?) => {
({
const MAT: &$crate::matrix::Mat = $crate::matrix::Mat::new(
&$crate::matrix::__ascii::parse([$($row),*]),
);
MAT
})
}
}

View File

@ -73,9 +73,38 @@ impl Mat {
}
}
#[cfg(any(feature = "ascii", test))]
#[doc(hidden)]
pub mod __ascii {
use super::*;
pub const fn parse<const N: usize>(strs: [&str; N]) -> [u16; N] {
let mut data = [EMPTY_ROW; N];
let mut i = 0;
while i < N {
let row = strs[i].as_bytes();
if row.len() != COLUMNS as usize {
panic!("wrong number of columns in ascii row");
}
let y = N - i - 1;
let mut x = 0i16;
while x < COLUMNS {
match row[x as usize] {
b'.' | b'_' | b' ' => {}
_ => data[y] |= 1 << x,
}
x += 1;
}
i += 1;
}
data
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::mat;
use core::ops::RangeInclusive;
@ -93,23 +122,17 @@ mod test {
}
}
const M1: &Mat = Mat::new(&[
// xx..xxxx.x y=0
0b1011110011 | EMPTY_ROW,
// ...x....x. y=1
0b0100001000 | EMPTY_ROW,
]);
const M1: &Mat = mat! {
"...x....x.";
"xx..xxxx.x";
};
const M2: &Mat = Mat::new(&[
// xxxx.xxxxx y=0
0b1111101111 | EMPTY_ROW,
// x.......xx y=1
0b1100000001 | EMPTY_ROW,
// .........x y=2
0b1000000000 | EMPTY_ROW,
// .........x y=3
0b1000000000 | EMPTY_ROW,
]);
const M2: &Mat = mat! {
".........x";
".........x";
"x.......xx";
"xxxx.xxxxx";
};
#[test]
fn test_dims() {