servicepoint-binding-ruby/servicepoint2/src/byte_grid.rs

60 lines
1.5 KiB
Rust
Raw Normal View History

2024-05-12 01:30:55 +02:00
/// A grid of bytes
#[derive(Debug, Clone)]
2024-05-11 12:43:17 +02:00
pub struct ByteGrid {
pub width: usize,
pub height: usize,
data: Vec<u8>,
}
impl ByteGrid {
2024-05-12 01:30:55 +02:00
/// Creates a new byte grid with the specified dimensions.
///
/// returns: ByteGrid initialized to 0.
2024-05-11 12:43:17 +02:00
pub fn new(width: usize, height: usize) -> Self {
Self {
data: vec![0; width * height],
width,
height,
}
}
2024-05-12 01:30:55 +02:00
/// Loads a byte grid with the specified dimensions from the provided data.
///
/// returns: ByteGrid that contains a copy of the provided data
///
/// # Panics
///
/// - when the dimensions and data size do not match exactly.
2024-05-11 12:43:17 +02:00
pub fn load(width: usize, height: usize, data: &[u8]) -> Self {
assert_eq!(width * height, data.len());
Self {
data: Vec::from(data),
width,
height,
}
}
2024-05-12 01:30:55 +02:00
/// Get the current value at the specified position
///
/// returns: current byte value
2024-05-11 12:43:17 +02:00
pub fn get(&self, x: usize, y: usize) -> u8 {
self.data[x + y * self.width]
}
2024-05-12 01:30:55 +02:00
/// Sets the byte value at the specified position
2024-05-11 12:43:17 +02:00
pub fn set(&mut self, x: usize, y: usize, value: u8) {
self.data[x + y * self.width] = value;
}
2024-05-12 01:30:55 +02:00
/// Sets all bytes in the grid to the specified value
2024-05-11 23:28:08 +02:00
pub fn fill(&mut self, value: u8) {
2024-05-11 12:43:17 +02:00
self.data.fill(value)
}
}
impl Into<Vec<u8>> for ByteGrid {
fn into(self) -> Vec<u8> {
self.data
}
}