use generic_array::{sequence::GenericSequence, ArrayLength, GenericArray};
use std::marker::PhantomData;
use super::button::Button;
pub struct ButtonMatrix<W, H>
where
W: ArrayLength,
H: ArrayLength,
{
pub(crate) buttons: GenericArray<GenericArray<Button, W>, H>,
pub(crate) _width: PhantomData<W>,
pub(crate) _height: PhantomData<H>,
}
impl<W, H> Default for ButtonMatrix<W, H>
where
W: ArrayLength,
H: ArrayLength,
{
fn default() -> Self {
ButtonMatrix {
buttons: GenericArray::generate(|_| GenericArray::generate(|_| Button::default())),
_width: PhantomData,
_height: PhantomData,
}
}
}
impl<W, H> ButtonMatrix<W, H>
where
W: ArrayLength,
H: ArrayLength,
{
pub fn new() -> Self {
ButtonMatrix::default()
}
pub fn get_button_by_index(&self, index: usize) -> Option<&Button> {
if index < W::to_usize() * H::to_usize() {
let x = index % W::to_usize();
let y = index / W::to_usize();
Some(&self.buttons[y][x])
} else {
None
}
}
pub fn get_button(&self, x: usize, y: usize) -> Option<&Button> {
if x < W::to_usize() && y < H::to_usize() {
Some(&self.buttons[y][x])
} else {
None
}
}
pub fn set_button(
&mut self,
x: usize,
y: usize,
button: Button,
) -> Result<(), Box<dyn std::error::Error>> {
if x < W::to_usize() && y < H::to_usize() {
self.buttons[y][x] = button;
Ok(())
} else {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Button index out of bounds",
)))
}
}
pub fn set_button_by_index(
&mut self,
index: usize,
button: Button,
) -> Result<(), Box<dyn std::error::Error>> {
if index < W::to_usize() * H::to_usize() {
let x = index % W::to_usize();
let y = index / W::to_usize();
self.buttons[y][x] = button;
Ok(())
} else {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Button index out of bounds",
)))
}
}
pub fn width(&self) -> usize {
W::to_usize()
}
pub fn height(&self) -> usize {
H::to_usize()
}
pub fn size(&self) -> usize {
W::to_usize() * H::to_usize()
}
}