servicepoint-binding-c/src/containers/cp437_grid.rs
2025-06-17 22:21:11 +02:00

116 lines
2.8 KiB
Rust

use crate::{
containers::ByteSlice,
macros::{wrap_clone, wrap_free, wrap_method},
mem::{heap_move_nonnull, heap_move_ok, heap_move_some, heap_remove},
};
use servicepoint::{
Cp437Grid, Cp437GridCommand, DataRef, Grid, Origin, Packet,
};
use std::ptr::NonNull;
/// Creates a new [Cp437Grid] with the specified dimensions.
///
/// returns: [Cp437Grid] initialized to 0.
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_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.
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_load(
width: usize,
height: usize,
data: ByteSlice,
) -> *mut Cp437Grid {
let data = unsafe { data.as_slice() };
heap_move_some(Cp437Grid::load(width, height, data))
}
wrap_clone!(sp_cp437_grid::Cp437Grid);
wrap_free!(sp_cp437_grid::Cp437Grid);
wrap_method!(
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;
);
wrap_method!(
sp_cp437_grid::Cp437Grid;
/// 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);
);
wrap_method!(
sp_cp437_grid::Cp437Grid;
/// 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);
);
wrap_method!(
sp_cp437_grid::Cp437Grid;
/// Gets the width of the grid.
ref fn width() -> usize;
);
wrap_method!(
sp_cp437_grid::Cp437Grid;
/// Gets the height of the grid.
ref fn height() -> usize;
);
wrap_method!(
sp_cp437_grid::Cp437Grid;
/// 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;
| slice | unsafe { ByteSlice::from_slice(slice) };
);
/// Creates a [Cp437GridCommand] and immediately turns that into a [Packet].
///
/// The provided [Cp437Grid] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_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),
}))
}