Skip to main content

for_each_row

Function for_each_row 

Source
pub fn for_each_row<E: Into<Box<dyn Error>>>(
    input: &str,
    hot_valid: impl Fn(u8) -> bool,
    invalid_error: impl Fn() -> E,
    callback: impl FnMut(usize, usize, &[u8]) -> Result<(), InputError>,
) -> Result<(usize, usize), InputError>
Expand description

Iterate over each row of a 2D grid and pass it to a callback after validation.

Unlike parse, this does not support padding or allocate a transformed grid. The callback receives the row index, column count and row input bytes. The callback may be called with one or more rows before an error is found in a later row.

ยงExamples

let mut row_masks = Vec::new();
let input = "#.#.#\n.#.#.\n#####";
let shape = grid::for_each_row(
    input,
    |b| matches!(b, b'.' | b'#'),
    || "expected '.' or '#'",
    |row, cols, row_bytes| {
        if row == 0 && cols > 32 {
            return Err(InputError::new(input, 0, "expected at most 32 columns"));
        }
        let mut bits = 0u32;
        for (col, &b) in row_bytes.iter().enumerate() {
            bits |= u32::from(b == b'#') << col;
        }
        row_masks.push(bits);
        Ok(())
    },
).unwrap();
assert_eq!(shape, (3, 5));
assert_eq!(row_masks, vec![0b10101, 0b01010, 0b11111]);