servicepoint-binding-c/src/containers/cp437_grid.rs
2025-06-18 20:42:33 +02:00

104 lines
2.7 KiB
Rust

use crate::macros::wrap_functions;
use crate::{
containers::ByteSlice,
macros::{wrap_clone, wrap_free, wrap_methods},
mem::{heap_move_nonnull, heap_move_ok, heap_move_some, heap_remove},
};
use servicepoint::{
Cp437Grid, Cp437GridCommand, DataRef, Grid, Origin, Packet,
};
use std::ptr::NonNull;
wrap_functions!(sp_cp437_grid;
/// Creates a new [Cp437Grid] with the specified dimensions.
///
/// returns: [Cp437Grid] initialized to 0.
fn new(
width: usize,
height: usize,
) -> NonNull<Cp437Grid> {
heap_move_nonnull(Cp437Grid::new(width, height))
}
/// Loads a [Cp437Grid] with the specified dimensions from the provided data.
fn load(
width: usize,
height: usize,
data: ByteSlice,
) -> *mut Cp437Grid {
let data = unsafe { data.as_slice() };
heap_move_some(Cp437Grid::load(width, height, data))
}
/// Creates a [Cp437GridCommand] and immediately turns that into a [Packet].
///
/// The provided [Cp437Grid] gets consumed.
///
/// Returns NULL in case of an error.
fn into_packet(
grid: NonNull<Cp437Grid>,
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
heap_move_ok(Packet::try_from(Cp437GridCommand {
grid,
origin: Origin::new(x, y),
}))
}
);
wrap_clone!(sp_cp437_grid::Cp437Grid);
wrap_free!(sp_cp437_grid::Cp437Grid);
wrap_methods!(
sp_cp437_grid::Cp437Grid;
/// Gets the current value at the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell to read
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
ref fn get(x: usize, y: usize) -> u8;
/// Sets the value at the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// returns: old value of the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
mut fn set(x: usize, y: usize, value: u8);
/// Sets the value of all cells in the grid.
///
/// # Arguments
///
/// - `cp437_grid`: instance to write to
/// - `value`: the value to set all cells to
mut fn fill(value: u8);
/// Gets the width of the grid.
ref fn width() -> usize;
/// Gets the height of the grid.
ref fn height() -> usize;
/// Gets an unsafe reference to the data of the grid.
///
/// The returned memory is valid for the lifetime of the instance.
mut fn data_ref_mut() -> ByteSlice {
return(slice) { unsafe { ByteSlice::from_slice(slice) } };
};
);