WIP: next #4

Draft
vinzenz wants to merge 12 commits from next into main
26 changed files with 2051 additions and 678 deletions

View file

@ -1,9 +1,11 @@
# servicepoint_binding_c # servicepoint_binding_c
[![Release](https://git.berlin.ccc.de/servicepoint/servicepoint_binding_c/badges/release.svg)](https://git.berlin.ccc.de/servicepoint/servicepoint_binding_c/releases)
[![crates.io](https://img.shields.io/crates/v/servicepoint_binding_c.svg)](https://crates.io/crates/servicepoint) [![crates.io](https://img.shields.io/crates/v/servicepoint_binding_c.svg)](https://crates.io/crates/servicepoint)
[![Crates.io Total Downloads](https://img.shields.io/crates/d/servicepoint_binding_c)](https://crates.io/crates/servicepoint) [![Crates.io Total Downloads](https://img.shields.io/crates/d/servicepoint_binding_c)](https://crates.io/crates/servicepoint)
[![docs.rs](https://img.shields.io/docsrs/servicepoint_binding_c)](https://docs.rs/servicepoint/latest/servicepoint/) [![docs.rs](https://img.shields.io/docsrs/servicepoint_binding_c)](https://docs.rs/servicepoint/latest/servicepoint/)
[![GPLv3 licensed](https://img.shields.io/crates/l/servicepoint_binding_c)](./LICENSE) [![GPLv3 licensed](https://img.shields.io/crates/l/servicepoint_binding_c)](./LICENSE)
[![CI](https://git.berlin.ccc.de/servicepoint/servicepoint_binding_c/badges/workflows/rust.yml/badge.svg)](https://git.berlin.ccc.de/servicepoint/servicepoint_binding_c)
In [CCCB](https://berlin.ccc.de/), there is a big pixel matrix hanging on the wall. In [CCCB](https://berlin.ccc.de/), there is a big pixel matrix hanging on the wall.
It is called "Service Point Display" or "Airport Display". It is called "Service Point Display" or "Airport Display".
@ -12,7 +14,7 @@ This crate contains C bindings for the [servicepoint](https://git.berlin.ccc.de/
## Examples ## Examples
```c++ ```c
#include <stdio.h> #include <stdio.h>
#include "servicepoint.h" #include "servicepoint.h"

View file

@ -32,11 +32,11 @@ features = ["full"]
[export] [export]
include = [] include = []
exclude = [] exclude = ["BitVec"]
[export.rename] [export.rename]
"SpBitVec" = "BitVec" "SPCommand" = "Command"
"SpByteSlice" = "ByteSlice" "DisplayBitVec" = "BitVec"
[enum] [enum]
rename_variants = "QualifiedScreamingSnakeCase" rename_variants = "QualifiedScreamingSnakeCase"

View file

@ -1,30 +1,44 @@
#include "servicepoint.h" #include "servicepoint.h"
int main(void) { static UdpSocket *connection = NULL;
UdpSocket *connection = sp_udp_open_ipv4(172, 23, 42, 29, 2342);
//UdpSocket *connection = sp_udp_open_ipv4(127, 0, 0, 1, 2342);
if (connection == NULL)
return -1;
void enable_all_pixels(void) {
Bitmap *all_on = sp_bitmap_new_max_sized(); Bitmap *all_on = sp_bitmap_new_max_sized();
sp_bitmap_fill(all_on, true); sp_bitmap_fill(all_on, true);
Packet *packet = sp_bitmap_into_packet(all_on, 0, 0, COMPRESSION_CODE_UNCOMPRESSED); BitmapCommand *bitmapCommand = sp_cmd_bitmap_from_bitmap(all_on);
if (packet == NULL) Packet *packet = sp_cmd_bitmap_try_into_packet(bitmapCommand);
return -1; if (packet != NULL)
sp_udp_send_packet(connection, packet); sp_udp_send_packet(connection, packet);
}
BrightnessGrid *grid = sp_brightness_grid_new(TILE_WIDTH, TILE_HEIGHT); void make_brightness_pattern(BrightnessGrid *grid) {
ByteSlice slice = sp_brightness_grid_unsafe_data_ref(grid); ByteSlice slice = sp_brightness_grid_unsafe_data_ref(grid);
for (size_t index = 0; index < slice.length; index++) { for (size_t index = 0; index < slice.length; index++) {
slice.start[index] = (uint8_t) (index % ((size_t) Brightness_MAX)); slice.start[index] = (uint8_t) (index % ((size_t) Brightness_MAX));
} }
}
packet = sp_brightness_grid_into_packet(grid, 0, 0); void run_at_exit() {
sp_udp_send_packet(connection, packet);
sp_udp_free(connection); sp_udp_free(connection);
}
int main(void) {
//UdpSocket *connection = sp_udp_open_ipv4(172, 23, 42, 29, 2342);
connection = sp_udp_open_ipv4(127, 0, 0, 1, 2342);
if (connection == NULL)
return -1;
atexit(run_at_exit);
enable_all_pixels();
BrightnessGrid *grid = sp_brightness_grid_new(TILE_WIDTH, TILE_HEIGHT);
make_brightness_pattern(grid);
Packet *packet = sp_cmd_brightness_grid_into_packet(sp_cmd_brightness_grid_from_grid(grid));
if (packet == NULL)
return -2;
sp_udp_send_packet(connection, packet);
return 0; return 0;
} }

File diff suppressed because it is too large Load diff

View file

@ -1,174 +0,0 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice};
use servicepoint::{
BinaryOperation, BitVecCommand, CompressionCode, DisplayBitVec, Packet,
};
use std::ptr::NonNull;
/// A vector of bits
///
/// # Examples
/// ```C
/// SPBitVec vec = sp_bitvec_new(8);
/// sp_bitvec_set(vec, 5, true);
/// sp_bitvec_free(vec);
/// ```
pub struct SPBitVec(pub(crate) DisplayBitVec);
impl Clone for SPBitVec {
fn clone(&self) -> Self {
SPBitVec(self.0.clone())
}
}
/// Creates a new [SPBitVec] instance.
///
/// # Arguments
///
/// - `size`: size in bits.
///
/// returns: [SPBitVec] with all bits set to false.
///
/// # Panics
///
/// - when `size` is not divisible by 8.
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_new(size: usize) -> NonNull<SPBitVec> {
heap_move_nonnull(SPBitVec(DisplayBitVec::repeat(false, size)))
}
/// Interpret the data as a series of bits and load then into a new [SPBitVec] instance.
///
/// returns: [SPBitVec] instance containing data.
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_load(data: ByteSlice) -> NonNull<SPBitVec> {
let data = unsafe { data.as_slice() };
heap_move_nonnull(SPBitVec(DisplayBitVec::from_slice(data)))
}
/// Clones a [SPBitVec].
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_clone(
bit_vec: NonNull<SPBitVec>,
) -> NonNull<SPBitVec> {
heap_move_nonnull(unsafe { bit_vec.as_ref().clone() })
}
/// Deallocates a [SPBitVec].
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_free(bit_vec: NonNull<SPBitVec>) {
unsafe { heap_drop(bit_vec) }
}
/// Gets the value of a bit from the [SPBitVec].
///
/// # Arguments
///
/// - `bit_vec`: instance to read from
/// - `index`: the bit index to read
///
/// returns: value of the bit
///
/// # Panics
///
/// - when accessing `index` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_get(
bit_vec: NonNull<SPBitVec>,
index: usize,
) -> bool {
unsafe { *bit_vec.as_ref().0.get(index).unwrap() }
}
/// Sets the value of a bit in the [SPBitVec].
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
/// - `index`: the bit index to edit
/// - `value`: the value to set the bit to
///
/// # Panics
///
/// - when accessing `index` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_set(
bit_vec: NonNull<SPBitVec>,
index: usize,
value: bool,
) {
unsafe { (*bit_vec.as_ptr()).0.set(index, value) }
}
/// Sets the value of all bits in the [SPBitVec].
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
/// - `value`: the value to set all bits to
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_fill(
bit_vec: NonNull<SPBitVec>,
value: bool,
) {
unsafe { (*bit_vec.as_ptr()).0.fill(value) }
}
/// Gets the length of the [SPBitVec] in bits.
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_len(bit_vec: NonNull<SPBitVec>) -> usize {
unsafe { bit_vec.as_ref().0.len() }
}
/// Returns true if length is 0.
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_is_empty(
bit_vec: NonNull<SPBitVec>,
) -> bool {
unsafe { bit_vec.as_ref().0.is_empty() }
}
/// Gets an unsafe reference to the data of the [SPBitVec] instance.
///
/// The returned memory is valid for the lifetime of the bitvec.
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_unsafe_data_ref(
bit_vec: NonNull<SPBitVec>,
) -> ByteSlice {
unsafe { ByteSlice::from_slice((*bit_vec.as_ptr()).0.as_raw_mut_slice()) }
}
/// Creates a [BitVecCommand] and immediately turns that into a [Packet].
///
/// The provided [SPBitVec] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_into_packet(
bitvec: NonNull<SPBitVec>,
offset: usize,
operation: BinaryOperation,
compression: CompressionCode,
) -> *mut Packet {
let bitvec = unsafe { heap_remove(bitvec) }.0;
match Packet::try_from(BitVecCommand {
bitvec,
offset,
operation,
compression,
}) {
Ok(packet) => heap_move(packet),
Err(_) => std::ptr::null_mut(),
}
}

View file

@ -0,0 +1,130 @@
use crate::mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_remove,
};
use servicepoint::{Bitmap, BitmapCommand, CompressionCode, Origin, Packet};
use std::ptr::NonNull;
/// Sets a window of pixels to the specified values.
///
/// The passed [Bitmap] gets consumed.
///
/// Returns: a new [BitmapCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_new(
bitmap: NonNull<Bitmap>,
origin_x: usize,
origin_y: usize,
compression: CompressionCode,
) -> NonNull<BitmapCommand> {
heap_move_nonnull(BitmapCommand {
bitmap: unsafe { heap_remove(bitmap) },
origin: Origin::new(origin_x, origin_y),
compression,
})
}
/// Move the provided [Bitmap] into a new [BitmapCommand],
/// leaving other fields as their default values.
///
/// Rust equivalent: `BitmapCommand::from(bitmap)`
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_from_bitmap(
bitmap: NonNull<Bitmap>,
) -> NonNull<BitmapCommand> {
heap_move_nonnull(unsafe { heap_remove(bitmap) }.into())
}
/// Tries to turn a [BitmapCommand] into a [Packet].
///
/// Returns: NULL or a [Packet] containing the command.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_try_into_packet(
command: NonNull<BitmapCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
/// Clones an [BitmapCommand] instance.
///
/// returns: a new [BitmapCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_clone(
command: NonNull<BitmapCommand>,
) -> NonNull<BitmapCommand> {
unsafe { heap_clone(command) }
}
/// Deallocates a [BitmapCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_free(command: NonNull<BitmapCommand>) {
unsafe { heap_drop(command) }
}
/// Returns a pointer to the provided `BitmapCommand`.
///
/// # Safety
///
/// - The returned bitmap inherits the lifetime of the command in which it is contained.
/// - The returned pointer may not be used in a function that consumes the instance, e.g. to create a command.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_get(
mut command: NonNull<BitmapCommand>,
) -> NonNull<Bitmap> {
unsafe { NonNull::from(&mut (command.as_mut().bitmap)) }
}
/// Moves the provided [Bitmap] to be contained in the [BitmapCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_set(
mut command: NonNull<BitmapCommand>,
bitmap: NonNull<Bitmap>,
) {
unsafe {
command.as_mut().bitmap = heap_remove(bitmap);
}
}
/// Reads the origin field of the [BitmapCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_get_origin(
command: NonNull<BitmapCommand>,
origin_x: NonNull<usize>,
origin_y: NonNull<usize>,
) {
unsafe {
let origin = &command.as_ref().origin;
*origin_x.as_ptr() = origin.x;
*origin_y.as_ptr() = origin.y;
}
}
/// Overwrites the origin field of the [BitmapCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_set_origin(
mut command: NonNull<BitmapCommand>,
origin_x: usize,
origin_y: usize,
) {
unsafe {
command.as_mut().origin = Origin::new(origin_x, origin_y);
}
}
/// Overwrites the compression kind of the [BitmapCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_set_compression(
mut command: NonNull<BitmapCommand>,
compression: CompressionCode,
) {
unsafe {
command.as_mut().compression = compression;
}
}
/// Reads the compression kind of the [BitmapCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitmap_get_compression(
command: NonNull<BitmapCommand>,
) -> CompressionCode {
unsafe { command.as_ref().compression }
}

View file

@ -0,0 +1,137 @@
use crate::mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_remove,
};
use servicepoint::{
BinaryOperation, BitVecCommand, CompressionCode, DisplayBitVec, Offset,
Packet,
};
use std::ptr::NonNull;
/// Set pixel data starting at the pixel offset on screen.
///
/// The screen will continuously overwrite more pixel data without regarding the offset, meaning
/// once the starting row is full, overwriting will continue on column 0.
///
/// The [`BinaryOperation`] will be applied on the display comparing old and sent bit.
///
/// `new_bit = old_bit op sent_bit`
///
/// For example, [`BinaryOperation::Or`] can be used to turn on some pixels without affecting other pixels.
///
/// The contained [`DisplayBitVec`] is always uncompressed.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_new(
bitvec: NonNull<DisplayBitVec>,
offset: usize,
operation: BinaryOperation,
compression: CompressionCode,
) -> NonNull<BitVecCommand> {
heap_move_nonnull(BitVecCommand {
bitvec: unsafe { heap_remove(bitvec) },
offset,
operation,
compression,
})
}
/// Tries to turn a [BitVecCommand] into a [Packet].
///
/// Returns: NULL or a [Packet] containing the command.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_try_into_packet(
command: NonNull<BitVecCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
/// Clones an [BitVecCommand] instance.
///
/// returns: a new [BitVecCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_clone(
command: NonNull<BitVecCommand>,
) -> NonNull<BitVecCommand> {
unsafe { heap_clone(command) }
}
/// Deallocates a [BitVecCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_free(command: NonNull<BitVecCommand>) {
unsafe { heap_drop(command) }
}
/// Returns a pointer to the [BitVec] contained in the [BitVecCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_get(
mut command: NonNull<BitVecCommand>,
) -> *mut DisplayBitVec {
&mut unsafe { command.as_mut() }.bitvec
}
/// Moves the provided [BitVec] to be contained in the [BitVecCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_set(
mut command: NonNull<BitVecCommand>,
bitvec: NonNull<DisplayBitVec>,
) {
unsafe {
command.as_mut().bitvec = heap_remove(bitvec);
}
}
/// Reads the offset field of the [BitVecCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_get_offset(
command: NonNull<BitVecCommand>,
) -> Offset {
unsafe { command.as_ref().offset }
}
/// Overwrites the offset field of the [BitVecCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_set_offset(
mut command: NonNull<BitVecCommand>,
offset: Offset,
) {
unsafe {
command.as_mut().offset = offset;
}
}
/// Returns the [BinaryOperation] of the command.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_get_operation(
command: NonNull<BitVecCommand>,
) -> BinaryOperation {
unsafe { command.as_ref().operation.clone() } // TODO remove clone
}
/// Overwrites the [BinaryOperation] of the command.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_set_operation(
mut command: NonNull<BitVecCommand>,
operation: BinaryOperation,
) {
unsafe {
command.as_mut().operation = operation;
}
}
/// Overwrites the compression kind of the [BitVecCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_set_compression(
mut command: NonNull<BitVecCommand>,
compression: CompressionCode,
) {
unsafe {
command.as_mut().compression = compression;
}
}
/// Reads the compression kind of the [BitVecCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_bitvec_get_compression(
command: NonNull<BitVecCommand>,
) -> CompressionCode {
unsafe { command.as_ref().compression }
}

View file

@ -0,0 +1,106 @@
use crate::mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_remove,
};
use servicepoint::{
BitmapCommand, BrightnessGrid, BrightnessGridCommand, Origin, Packet,
};
use std::ptr::NonNull;
/// Set the brightness of individual tiles in a rectangular area of the display.
///
/// The passed [BrightnessGrid] gets consumed.
///
/// Returns: a new [BrightnessGridCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_grid_new(
grid: NonNull<BrightnessGrid>,
origin_x: usize,
origin_y: usize,
) -> NonNull<BrightnessGridCommand> {
heap_move_nonnull(BrightnessGridCommand {
grid: unsafe { heap_remove(grid) },
origin: Origin::new(origin_x, origin_y),
})
}
/// Moves the provided [BrightnessGrid] into a new [BrightnessGridCommand],
/// leaving other fields as their default values.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_grid_from_grid(
grid: NonNull<BrightnessGrid>,
) -> NonNull<BrightnessGridCommand> {
heap_move_nonnull(unsafe { heap_remove(grid) }.into())
}
/// Tries to turn a [BrightnessGridCommand] into a [Packet].
///
/// Returns: NULL or a [Packet] containing the command.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_grid_into_packet(
command: NonNull<BrightnessGridCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
/// Clones an [BrightnessGridCommand] instance.
///
/// returns: a new [BrightnessGridCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_grid_clone(
command: NonNull<BrightnessGridCommand>,
) -> NonNull<BrightnessGridCommand> {
unsafe { heap_clone(command) }
}
/// Deallocates a [BitmapCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_grid_free(
command: NonNull<BitmapCommand>,
) {
unsafe { heap_drop(command) }
}
/// Moves the provided [BrightnessGrid] to be contained in the [BrightnessGridCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_grid_set(
mut command: NonNull<BrightnessGridCommand>,
grid: NonNull<BrightnessGrid>,
) {
unsafe {
command.as_mut().grid = heap_remove(grid);
}
}
/// Returns a pointer to the [BrightnessGrid] contained in the [BrightnessGridCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_grid_get(
mut command: NonNull<BrightnessGridCommand>,
) -> *mut BrightnessGrid {
&mut unsafe { command.as_mut() }.grid
}
/// Overwrites the origin field of the [BrightnessGridCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_grid_get_origin(
command: NonNull<BrightnessGridCommand>,
origin_x: NonNull<usize>,
origin_y: NonNull<usize>,
) {
unsafe {
let origin = &command.as_ref().origin;
*origin_x.as_ptr() = origin.x;
*origin_y.as_ptr() = origin.y;
}
}
/// Reads the origin field of the [BrightnessGridCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_grid_set_origin(
mut command: NonNull<BrightnessGridCommand>,
origin_x: usize,
origin_y: usize,
) {
unsafe {
command.as_mut().origin = Origin::new(origin_x, origin_y);
}
}

View file

@ -0,0 +1,51 @@
use crate::mem::{heap_drop, heap_move_nonnull};
use servicepoint::{ClearCommand, FadeOutCommand, HardResetCommand};
use std::ptr::NonNull;
/// Set all pixels to the off state.
///
/// Does not affect brightness.
///
/// Returns: a new [ClearCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_clear_new() -> NonNull<ClearCommand> {
heap_move_nonnull(ClearCommand)
}
/// Deallocates a [ClearCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_clear_free(command: NonNull<ClearCommand>) {
unsafe { heap_drop(command) }
}
/// Kills the udp daemon on the display, which usually results in a restart.
///
/// Please do not send this in your normal program flow.
///
/// Returns: a new [HardResetCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_hard_reset_new() -> NonNull<HardResetCommand> {
heap_move_nonnull(HardResetCommand)
}
/// Deallocates a [HardResetCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_hard_reset_free(
command: NonNull<ClearCommand>,
) {
unsafe { heap_drop(command) }
}
/// A yet-to-be-tested command.
///
/// Returns: a new [FadeOutCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_fade_out_new() -> NonNull<FadeOutCommand> {
heap_move_nonnull(FadeOutCommand)
}
/// Deallocates a [FadeOutCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_fade_out_free(command: NonNull<ClearCommand>) {
unsafe { heap_drop(command) }
}

View file

@ -0,0 +1,104 @@
use crate::mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_remove,
};
use servicepoint::{BitmapCommand, CharGrid, CharGridCommand, Origin, Packet};
use std::ptr::NonNull;
/// Show UTF-8 encoded text on the screen.
///
/// The passed [CharGrid] gets consumed.
///
/// Returns: a new [CharGridCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_char_grid_new(
grid: NonNull<CharGrid>,
origin_x: usize,
origin_y: usize,
) -> NonNull<CharGridCommand> {
heap_move_nonnull(CharGridCommand {
grid: unsafe { heap_remove(grid) },
origin: Origin::new(origin_x, origin_y),
})
}
/// Moves the provided [CharGrid] into a new [CharGridCommand],
/// leaving other fields as their default values.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_char_grid_from_grid(
grid: NonNull<CharGrid>,
) -> NonNull<CharGridCommand> {
heap_move_nonnull(unsafe { heap_remove(grid) }.into())
}
/// Tries to turn a [CharGridCommand] into a [Packet].
///
/// Returns: NULL or a [Packet] containing the command.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_char_grid_try_into_packet(
command: NonNull<CharGridCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
/// Clones an [CharGridCommand] instance.
///
/// returns: a new [CharGridCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_char_grid_clone(
command: NonNull<CharGridCommand>,
) -> NonNull<CharGridCommand> {
unsafe { heap_clone(command) }
}
/// Deallocates a [BitmapCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_char_grid_free(
command: NonNull<BitmapCommand>,
) {
unsafe { heap_drop(command) }
}
/// Moves the provided [CharGrid] to be contained in the [CharGridCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_char_grid_set(
mut command: NonNull<CharGridCommand>,
grid: NonNull<CharGrid>,
) {
unsafe {
command.as_mut().grid = heap_remove(grid);
}
}
/// Returns a pointer to the [CharGrid] contained in the [CharGridCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_char_grid_get(
mut command: NonNull<CharGridCommand>,
) -> *mut CharGrid {
&mut unsafe { command.as_mut() }.grid
}
/// Reads the origin field of the [CharGridCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_char_grid_get_origin(
command: NonNull<CharGridCommand>,
origin_x: NonNull<usize>,
origin_y: NonNull<usize>,
) {
unsafe {
let origin = &command.as_ref().origin;
*origin_x.as_ptr() = origin.x;
*origin_y.as_ptr() = origin.y;
}
}
/// Overwrites the origin field of the [CharGridCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_char_grid_set_origin(
mut command: NonNull<CharGridCommand>,
origin_x: usize,
origin_y: usize,
) {
unsafe {
command.as_mut().origin = Origin::new(origin_x, origin_y);
}
}

View file

@ -0,0 +1,117 @@
use crate::mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_remove,
};
use servicepoint::{
BitmapCommand, Cp437Grid, Cp437GridCommand, Origin, Packet,
};
use std::ptr::NonNull;
/// Show text on the screen.
///
/// The text is sent in the form of a 2D grid of [CP-437] encoded characters.
///
/// The origin is relative to the top-left of the display.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_cp437_grid_new(
grid: NonNull<Cp437Grid>,
origin_x: usize,
origin_y: usize,
) -> NonNull<Cp437GridCommand> {
heap_move_nonnull(Cp437GridCommand {
grid: unsafe { heap_remove(grid) },
origin: Origin::new(origin_x, origin_y),
})
}
/// Moves the provided [Cp437Grid] into a new [Cp437GridCommand],
/// leaving other fields as their default values.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_cp437_grid_from_grid(
grid: NonNull<Cp437Grid>,
) -> NonNull<Cp437GridCommand> {
heap_move_nonnull(unsafe { heap_remove(grid) }.into())
}
/// Tries to turn a [Cp437GridCommand] into a [Packet].
///
/// Returns: NULL or a [Packet] containing the command.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_cp437_grid_try_into_packet(
command: NonNull<Cp437GridCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
/// Clones an [Cp437GridCommand] instance.
///
/// returns: a new [Cp437GridCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_cp437_grid_clone(
command: NonNull<Cp437GridCommand>,
) -> NonNull<Cp437GridCommand> {
unsafe { heap_clone(command) }
}
/// Deallocates a [Cp437GridCommand].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_cp437_grid_free(
command: NonNull<BitmapCommand>,
) {
unsafe { heap_drop(command) }
}
/// Moves the provided bitmap into the provided command.
///
/// This drops the previously contained [Cp437Grid].
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_cp437_grid_set(
mut command: NonNull<Cp437GridCommand>,
grid: NonNull<Cp437Grid>,
) {
unsafe {
command.as_mut().grid = heap_remove(grid);
}
}
/// Show text on the screen.
///
/// The text is sent in the form of a 2D grid of [CP-437] encoded characters.
/// For sending UTF-8 encoded characters, see [servicepoint::CharGridCommand].
///
/// [CP-437]: https://en.wikipedia.org/wiki/Code_page_437
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_cp437_grid_get(
mut command: NonNull<Cp437GridCommand>,
) -> *mut Cp437Grid {
&mut unsafe { command.as_mut() }.grid
}
/// Gets the origin field of the [Cp437GridCommand].
///
/// Rust equivalent: `cp437_command.origin`
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_cp437_grid_get_origin(
command: NonNull<Cp437GridCommand>,
origin_x: NonNull<usize>,
origin_y: NonNull<usize>,
) {
unsafe {
let origin = &command.as_ref().origin;
*origin_x.as_ptr() = origin.x;
*origin_y.as_ptr() = origin.y;
}
}
/// Sets the origin field of the [Cp437GridCommand].
///
/// Rust equivalent: `cp437_command.origin = Origin::new(origin_x, origin_y)`
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_cp437_grid_set_origin(
mut command: NonNull<Cp437GridCommand>,
origin_x: usize,
origin_y: usize,
) {
unsafe {
command.as_mut().origin = Origin::new(origin_x, origin_y);
}
}

View file

@ -0,0 +1,293 @@
use crate::mem::{
heap_clone, heap_drop, heap_move, heap_move_nonnull, heap_move_ok,
heap_remove,
};
use servicepoint::{
BitVecCommand, BitmapCommand, BrightnessGridCommand, CharGridCommand,
ClearCommand, Cp437GridCommand, FadeOutCommand, GlobalBrightnessCommand,
HardResetCommand, Packet, TypedCommand,
};
use std::ptr::{null_mut, NonNull};
/// Pointer to one of the available command structs.
#[repr(C)]
#[allow(missing_docs)]
pub union CommandUnion {
pub null: *mut u8,
pub bitmap: NonNull<BitmapCommand>,
pub bitvec: NonNull<BitVecCommand>,
pub brightness_grid: NonNull<BrightnessGridCommand>,
pub char_grid: NonNull<CharGridCommand>,
pub cp437_grid: NonNull<Cp437GridCommand>,
pub global_brightness: NonNull<GlobalBrightnessCommand>,
pub clear: NonNull<ClearCommand>,
#[allow(deprecated)]
pub bitmap_legacy: NonNull<servicepoint::BitmapLegacyCommand>,
pub hard_reset: NonNull<HardResetCommand>,
pub fade_out: NonNull<FadeOutCommand>,
}
/// Specifies the kind of command struct.
///
/// This is _not_ equivalent to the [servicepoint::CommandCode]s.
#[repr(u8)]
#[allow(missing_docs)]
pub enum CommandTag {
Invalid = 0,
Bitmap,
BitVec,
BrightnessGrid,
CharGrid,
Cp437Grid,
GlobalBrightness,
Clear,
HardReset,
FadeOut,
BitmapLegacy,
}
/// This struct represents a pointer to one of the possible command structs.
///
/// Only ever access `data` with the correct data type as specified by `tag`!
///
/// Rust equivalent: [TypedCommand].
#[repr(C)]
pub struct SPCommand {
/// Specifies which kind of command struct is contained in `data`
pub tag: CommandTag,
/// The pointer to the command struct
pub data: CommandUnion,
}
impl SPCommand {
const INVALID: SPCommand = SPCommand {
tag: CommandTag::Invalid,
data: CommandUnion { null: null_mut() },
};
}
/// Tries to turn a [Packet] into a [SPCommand].
///
/// The packet is dropped in the process.
///
/// Returns: pointer to new [SPCommand] instance or NULL if parsing failed.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_generic_try_from_packet(
packet: NonNull<Packet>,
) -> *mut SPCommand {
let packet = *unsafe { Box::from_raw(packet.as_ptr()) };
heap_move_ok(servicepoint::TypedCommand::try_from(packet).map(|value| {
match value {
TypedCommand::Clear(clear) => SPCommand {
tag: CommandTag::Clear,
data: CommandUnion {
clear: heap_move_nonnull(clear),
},
},
TypedCommand::CharGrid(char_grid) => SPCommand {
tag: CommandTag::CharGrid,
data: CommandUnion {
char_grid: heap_move_nonnull(char_grid),
},
},
TypedCommand::Cp437Grid(cp437_grid) => SPCommand {
tag: CommandTag::Cp437Grid,
data: CommandUnion {
cp437_grid: heap_move_nonnull(cp437_grid),
},
},
TypedCommand::Bitmap(bitmap) => SPCommand {
tag: CommandTag::Bitmap,
data: CommandUnion {
bitmap: heap_move_nonnull(bitmap),
},
},
TypedCommand::Brightness(global_brightness) => SPCommand {
tag: CommandTag::GlobalBrightness,
data: CommandUnion {
global_brightness: heap_move_nonnull(global_brightness),
},
},
TypedCommand::BrightnessGrid(brightness_grid) => SPCommand {
tag: CommandTag::BrightnessGrid,
data: CommandUnion {
brightness_grid: heap_move_nonnull(brightness_grid),
},
},
TypedCommand::BitVec(bitvec) => SPCommand {
tag: CommandTag::BitVec,
data: CommandUnion {
bitvec: heap_move_nonnull(bitvec),
},
},
TypedCommand::HardReset(hard_reset) => SPCommand {
tag: CommandTag::HardReset,
data: CommandUnion {
hard_reset: heap_move_nonnull(hard_reset),
},
},
TypedCommand::FadeOut(fade_out) => SPCommand {
tag: CommandTag::FadeOut,
data: CommandUnion {
fade_out: heap_move_nonnull(fade_out),
},
},
#[allow(deprecated)]
TypedCommand::BitmapLegacy(bitmap_legacy) => SPCommand {
tag: CommandTag::BitmapLegacy,
data: CommandUnion {
bitmap_legacy: heap_move_nonnull(bitmap_legacy),
},
},
}
}))
}
/// Clones an [SPCommand] instance.
///
/// returns: a new [SPCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_generic_clone(command: SPCommand) -> SPCommand {
unsafe {
match command.tag {
CommandTag::Clear => SPCommand {
tag: CommandTag::Clear,
data: CommandUnion {
clear: heap_clone(command.data.clear),
},
},
CommandTag::CharGrid => SPCommand {
tag: CommandTag::CharGrid,
data: CommandUnion {
char_grid: heap_clone(command.data.char_grid),
},
},
CommandTag::Cp437Grid => SPCommand {
tag: CommandTag::Cp437Grid,
data: CommandUnion {
cp437_grid: heap_clone(command.data.cp437_grid),
},
},
CommandTag::Bitmap => SPCommand {
tag: CommandTag::Bitmap,
data: CommandUnion {
bitmap: heap_clone(command.data.bitmap),
},
},
CommandTag::GlobalBrightness => SPCommand {
tag: CommandTag::GlobalBrightness,
data: CommandUnion {
global_brightness: heap_clone(
command.data.global_brightness,
),
},
},
CommandTag::BrightnessGrid => SPCommand {
tag: CommandTag::BrightnessGrid,
data: CommandUnion {
brightness_grid: heap_clone(command.data.brightness_grid),
},
},
CommandTag::BitVec => SPCommand {
tag: CommandTag::BitVec,
data: CommandUnion {
bitvec: heap_clone(command.data.bitvec),
},
},
CommandTag::HardReset => SPCommand {
tag: CommandTag::HardReset,
data: CommandUnion {
hard_reset: heap_clone(command.data.hard_reset),
},
},
CommandTag::FadeOut => SPCommand {
tag: CommandTag::FadeOut,
data: CommandUnion {
fade_out: heap_clone(command.data.fade_out),
},
},
#[allow(deprecated)]
CommandTag::BitmapLegacy => SPCommand {
tag: CommandTag::BitmapLegacy,
data: CommandUnion {
bitmap_legacy: heap_clone(command.data.bitmap_legacy),
},
},
CommandTag::Invalid => SPCommand::INVALID,
}
}
}
/// Deallocates an [SPCommand].
///
/// # Examples
///
/// ```C
/// SPCommand c = sp_cmd_clear_into_generic(sp_cmd_clear_new());
/// sp_command_free(c);
/// ```
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_generic_free(command: SPCommand) {
unsafe {
match command.tag {
CommandTag::Invalid => (),
CommandTag::Bitmap => heap_drop(command.data.bitmap),
CommandTag::BitVec => heap_drop(command.data.bitvec),
CommandTag::BrightnessGrid => {
heap_drop(command.data.brightness_grid)
}
CommandTag::CharGrid => heap_drop(command.data.char_grid),
CommandTag::Cp437Grid => heap_drop(command.data.cp437_grid),
CommandTag::GlobalBrightness => {
heap_drop(command.data.global_brightness)
}
CommandTag::Clear => heap_drop(command.data.clear),
CommandTag::HardReset => heap_drop(command.data.hard_reset),
CommandTag::FadeOut => heap_drop(command.data.fade_out),
CommandTag::BitmapLegacy => heap_drop(command.data.bitmap_legacy),
}
}
}
/// Tries to turn a [SPCommand] into a [Packet].
/// The [SPCommand] gets consumed.
///
/// Returns tag [CommandTag::Invalid] in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_generic_into_packet(
command: SPCommand,
) -> *mut Packet {
match command.tag {
CommandTag::Invalid => null_mut(),
CommandTag::Bitmap => {
heap_move_ok(unsafe { heap_remove(command.data.bitmap).try_into() })
}
CommandTag::BitVec => {
heap_move_ok(unsafe { heap_remove(command.data.bitvec).try_into() })
}
CommandTag::BrightnessGrid => heap_move_ok(unsafe {
heap_remove(command.data.brightness_grid).try_into()
}),
CommandTag::CharGrid => heap_move_ok(unsafe {
heap_remove(command.data.char_grid).try_into()
}),
CommandTag::Cp437Grid => heap_move_ok(unsafe {
heap_remove(command.data.cp437_grid).try_into()
}),
CommandTag::GlobalBrightness => heap_move(unsafe {
heap_remove(command.data.global_brightness).into()
}),
CommandTag::Clear => {
heap_move(unsafe { heap_remove(command.data.clear).into() })
}
CommandTag::HardReset => {
heap_move(unsafe { heap_remove(command.data.hard_reset).into() })
}
CommandTag::FadeOut => {
heap_move(unsafe { heap_remove(command.data.fade_out).into() })
}
CommandTag::BitmapLegacy => {
heap_move(unsafe { heap_remove(command.data.bitmap_legacy).into() })
}
}
}

View file

@ -0,0 +1,57 @@
use crate::mem::{heap_clone, heap_drop, heap_move_nonnull, heap_remove};
use servicepoint::{
BitmapCommand, Brightness, GlobalBrightnessCommand, Packet,
};
use std::ptr::NonNull;
/// Set the brightness of all tiles to the same value.
///
/// Returns: a new [GlobalBrightnessCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_global_new(
brightness: Brightness,
) -> NonNull<GlobalBrightnessCommand> {
heap_move_nonnull(GlobalBrightnessCommand::from(brightness))
}
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_global_into_packet(
command: NonNull<GlobalBrightnessCommand>,
) -> NonNull<Packet> {
heap_move_nonnull(unsafe { heap_remove(command) }.into())
}
/// Clones an [GlobalBrightnessCommand] instance.
///
/// returns: a new [GlobalBrightnessCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_global_clone(
command: NonNull<GlobalBrightnessCommand>,
) -> NonNull<GlobalBrightnessCommand> {
unsafe { heap_clone(command) }
}
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_global_free(
command: NonNull<BitmapCommand>,
) {
unsafe { heap_drop(command) }
}
/// Moves the provided bitmap to be contained in the command.
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_global_set(
mut command: NonNull<GlobalBrightnessCommand>,
brightness: Brightness,
) {
unsafe {
command.as_mut().brightness = brightness;
}
}
#[no_mangle]
pub unsafe extern "C" fn sp_cmd_brightness_global_get(
mut command: NonNull<GlobalBrightnessCommand>,
) -> *mut Brightness {
&mut unsafe { command.as_mut() }.brightness
}

15
src/commands/mod.rs Normal file
View file

@ -0,0 +1,15 @@
mod bitmap_command;
mod bitvec_command;
mod brightness_grid_command;
mod cc_only_commands;
mod char_grid_command;
mod cp437_grid_command;
mod generic_command;
mod global_brightness_command;
pub use bitmap_command::*;
pub use bitvec_command::*;
pub use brightness_grid_command::*;
pub use char_grid_command::*;
pub use cp437_grid_command::*;
pub use generic_command::*;

View file

@ -1,7 +1,13 @@
use crate::byte_slice::ByteSlice; use crate::{
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, SPBitVec}; containers::ByteSlice,
mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_move_some,
heap_remove,
},
};
use servicepoint::{ use servicepoint::{
Bitmap, BitmapCommand, CompressionCode, DataRef, Grid, Origin, Packet, Bitmap, BitmapCommand, CompressionCode, DataRef, DisplayBitVec, Grid,
Origin, Packet,
}; };
use std::ptr::NonNull; use std::ptr::NonNull;
@ -33,11 +39,7 @@ pub unsafe extern "C" fn sp_bitmap_new(
width: usize, width: usize,
height: usize, height: usize,
) -> *mut Bitmap { ) -> *mut Bitmap {
if let Some(bitmap) = Bitmap::new(width, height) { heap_move_some(Bitmap::new(width, height))
heap_move(bitmap)
} else {
std::ptr::null_mut()
}
} }
/// Creates a new [Bitmap] with a size matching the screen. /// Creates a new [Bitmap] with a size matching the screen.
@ -63,11 +65,7 @@ pub unsafe extern "C" fn sp_bitmap_load(
data: ByteSlice, data: ByteSlice,
) -> *mut Bitmap { ) -> *mut Bitmap {
let data = unsafe { data.as_slice() }; let data = unsafe { data.as_slice() };
if let Ok(bitmap) = Bitmap::load(width, height, data) { heap_move_ok(Bitmap::load(width, height, data))
heap_move(bitmap)
} else {
std::ptr::null_mut()
}
} }
/// Tries to convert the BitVec to a Bitmap. /// Tries to convert the BitVec to a Bitmap.
@ -78,14 +76,10 @@ pub unsafe extern "C" fn sp_bitmap_load(
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_from_bitvec( pub unsafe extern "C" fn sp_bitmap_from_bitvec(
width: usize, width: usize,
bitvec: NonNull<SPBitVec>, bitvec: NonNull<DisplayBitVec>,
) -> *mut Bitmap { ) -> *mut Bitmap {
let bitvec = unsafe { heap_remove(bitvec) }; let bitvec = unsafe { heap_remove(bitvec) };
if let Ok(bitmap) = Bitmap::from_bitvec(width, bitvec.0) { heap_move_ok(Bitmap::from_bitvec(width, bitvec))
heap_move(bitmap)
} else {
std::ptr::null_mut()
}
} }
/// Clones a [Bitmap]. /// Clones a [Bitmap].
@ -93,7 +87,7 @@ pub unsafe extern "C" fn sp_bitmap_from_bitvec(
pub unsafe extern "C" fn sp_bitmap_clone( pub unsafe extern "C" fn sp_bitmap_clone(
bitmap: NonNull<Bitmap>, bitmap: NonNull<Bitmap>,
) -> NonNull<Bitmap> { ) -> NonNull<Bitmap> {
heap_move_nonnull(unsafe { bitmap.as_ref().clone() }) unsafe { heap_clone(bitmap) }
} }
/// Deallocates a [Bitmap]. /// Deallocates a [Bitmap].
@ -197,9 +191,9 @@ pub unsafe extern "C" fn sp_bitmap_unsafe_data_ref(
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_into_bitvec( pub unsafe extern "C" fn sp_bitmap_into_bitvec(
bitmap: NonNull<Bitmap>, bitmap: NonNull<Bitmap>,
) -> NonNull<SPBitVec> { ) -> NonNull<DisplayBitVec> {
let bitmap = unsafe { heap_remove(bitmap) }; let bitmap = unsafe { heap_remove(bitmap) };
heap_move_nonnull(SPBitVec(bitmap.into())) heap_move_nonnull(bitmap.into())
} }
/// Creates a [BitmapCommand] and immediately turns that into a [Packet]. /// Creates a [BitmapCommand] and immediately turns that into a [Packet].
@ -215,12 +209,9 @@ pub unsafe extern "C" fn sp_bitmap_into_packet(
compression: CompressionCode, compression: CompressionCode,
) -> *mut Packet { ) -> *mut Packet {
let bitmap = unsafe { heap_remove(bitmap) }; let bitmap = unsafe { heap_remove(bitmap) };
match Packet::try_from(BitmapCommand { heap_move_ok(Packet::try_from(BitmapCommand {
bitmap, bitmap,
origin: Origin::new(x, y), origin: Origin::new(x, y),
compression, compression,
}) { }))
Ok(packet) => heap_move(packet),
Err(_) => std::ptr::null_mut(),
}
} }

164
src/containers/bitvec.rs Normal file
View file

@ -0,0 +1,164 @@
use crate::{
containers::ByteSlice,
mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_remove,
},
};
use servicepoint::{
BinaryOperation, BitVecCommand, CompressionCode, DisplayBitVec, Packet,
};
use std::ptr::NonNull;
/// Creates a new [DisplayBitVec] instance.
///
/// # Arguments
///
/// - `size`: size in bits.
///
/// returns: [DisplayBitVec] with all bits set to false.
///
/// # Panics
///
/// - when `size` is not divisible by 8.
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_new(size: usize) -> NonNull<DisplayBitVec> {
heap_move_nonnull(DisplayBitVec::repeat(false, size))
}
/// Interpret the data as a series of bits and load then into a new [DisplayBitVec] instance.
///
/// returns: [DisplayBitVec] instance containing data.
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_load(
data: ByteSlice,
) -> NonNull<DisplayBitVec> {
let data = unsafe { data.as_slice() };
heap_move_nonnull(DisplayBitVec::from_slice(data))
}
/// Clones a [DisplayBitVec].
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_clone(
bit_vec: NonNull<DisplayBitVec>,
) -> NonNull<DisplayBitVec> {
unsafe { heap_clone(bit_vec) }
}
/// Deallocates a [DisplayBitVec].
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_free(bit_vec: NonNull<DisplayBitVec>) {
unsafe { heap_drop(bit_vec) }
}
/// Gets the value of a bit from the [DisplayBitVec].
///
/// # Arguments
///
/// - `bit_vec`: instance to read from
/// - `index`: the bit index to read
///
/// returns: value of the bit
///
/// # Panics
///
/// - when accessing `index` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_get(
bit_vec: NonNull<DisplayBitVec>,
index: usize,
) -> bool {
unsafe { *bit_vec.as_ref().get(index).unwrap() }
}
/// Sets the value of a bit in the [DisplayBitVec].
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
/// - `index`: the bit index to edit
/// - `value`: the value to set the bit to
///
/// # Panics
///
/// - when accessing `index` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_set(
bit_vec: NonNull<DisplayBitVec>,
index: usize,
value: bool,
) {
unsafe { (*bit_vec.as_ptr()).set(index, value) }
}
/// Sets the value of all bits in the [DisplayBitVec].
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
/// - `value`: the value to set all bits to
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_fill(
bit_vec: NonNull<DisplayBitVec>,
value: bool,
) {
unsafe { (*bit_vec.as_ptr()).fill(value) }
}
/// Gets the length of the [DisplayBitVec] in bits.
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_len(
bit_vec: NonNull<DisplayBitVec>,
) -> usize {
unsafe { bit_vec.as_ref().len() }
}
/// Returns true if length is 0.
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_is_empty(
bit_vec: NonNull<DisplayBitVec>,
) -> bool {
unsafe { bit_vec.as_ref().is_empty() }
}
/// Gets an unsafe reference to the data of the [DisplayBitVec] instance.
///
/// The returned memory is valid for the lifetime of the bitvec.
///
/// # Arguments
///
/// - `bit_vec`: instance to write to
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_unsafe_data_ref(
bit_vec: NonNull<DisplayBitVec>,
) -> ByteSlice {
unsafe { ByteSlice::from_slice((*bit_vec.as_ptr()).as_raw_mut_slice()) }
}
/// Creates a [BitVecCommand] and immediately turns that into a [Packet].
///
/// The provided [DisplayBitVec] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_bitvec_into_packet(
bitvec: NonNull<DisplayBitVec>,
offset: usize,
operation: BinaryOperation,
compression: CompressionCode,
) -> *mut Packet {
let bitvec = unsafe { heap_remove(bitvec) };
heap_move_ok(Packet::try_from(BitVecCommand {
bitvec,
offset,
operation,
compression,
}))
}

View file

@ -1,4 +1,10 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice}; use crate::{
containers::ByteSlice,
mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_move_some,
heap_remove,
},
};
use servicepoint::{ use servicepoint::{
Brightness, BrightnessGrid, BrightnessGridCommand, ByteGrid, DataRef, Grid, Brightness, BrightnessGrid, BrightnessGridCommand, ByteGrid, DataRef, Grid,
Origin, Packet, Origin, Packet,
@ -12,15 +18,15 @@ use std::ptr::NonNull;
/// ///
/// # Examples /// # Examples
/// ```C /// ```C
/// UdpConnection connection = sp_udp_open("127.0.0.1:2342"); /// UdpSocket *connection = sp_udp_open("127.0.0.1:2342");
/// if (connection == NULL) /// if (connection == NULL)
/// return 1; /// return 1;
/// ///
/// BrightnessGrid grid = sp_brightness_grid_new(2, 2); /// BrightnessGrid *grid = sp_brightness_grid_new(2, 2);
/// sp_brightness_grid_set(grid, 0, 0, 0); /// sp_brightness_grid_set(grid, 0, 0, 0);
/// sp_brightness_grid_set(grid, 1, 1, 10); /// sp_brightness_grid_set(grid, 1, 1, 10);
/// ///
/// TypedCommand command = sp_command_char_brightness(grid); /// TypedCommand *command = sp_command_char_brightness(grid);
/// sp_udp_free(connection); /// sp_udp_free(connection);
/// ``` /// ```
#[no_mangle] #[no_mangle]
@ -43,21 +49,18 @@ pub unsafe extern "C" fn sp_brightness_grid_load(
data: ByteSlice, data: ByteSlice,
) -> *mut BrightnessGrid { ) -> *mut BrightnessGrid {
let data = unsafe { data.as_slice() }; let data = unsafe { data.as_slice() };
heap_move_some(
match ByteGrid::load(width, height, data) ByteGrid::load(width, height, data)
.map(move |grid| grid.map(Brightness::saturating_from)) .map(move |grid| grid.map(Brightness::saturating_from)),
{ )
None => std::ptr::null_mut(),
Some(grid) => heap_move(grid),
}
} }
/// Clones a [BrightnessGrid]. /// Clones a [BrightnessGrid].
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_clone( pub unsafe extern "C" fn sp_brightness_grid_clone(
brightness_grid: NonNull<BrightnessGrid>, grid: NonNull<BrightnessGrid>,
) -> NonNull<BrightnessGrid> { ) -> NonNull<BrightnessGrid> {
heap_move_nonnull(unsafe { brightness_grid.as_ref().clone() }) unsafe { heap_clone(grid) }
} }
/// Deallocates a [BrightnessGrid]. /// Deallocates a [BrightnessGrid].
@ -187,11 +190,8 @@ pub unsafe extern "C" fn sp_brightness_grid_into_packet(
y: usize, y: usize,
) -> *mut Packet { ) -> *mut Packet {
let grid = unsafe { heap_remove(grid) }; let grid = unsafe { heap_remove(grid) };
match Packet::try_from(BrightnessGridCommand { heap_move_ok(Packet::try_from(BrightnessGridCommand {
grid, grid,
origin: Origin::new(x, y), origin: Origin::new(x, y),
}) { }))
Ok(packet) => heap_move(packet),
Err(_) => std::ptr::null_mut(),
}
} }

View file

@ -1,4 +1,9 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice}; use crate::{
containers::ByteSlice,
mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_remove,
},
};
use servicepoint::{CharGrid, CharGridCommand, Grid, Origin, Packet}; use servicepoint::{CharGrid, CharGridCommand, Grid, Origin, Packet};
use std::ptr::NonNull; use std::ptr::NonNull;
@ -32,19 +37,15 @@ pub unsafe extern "C" fn sp_char_grid_load(
data: ByteSlice, data: ByteSlice,
) -> *mut CharGrid { ) -> *mut CharGrid {
let data = unsafe { data.as_slice() }; let data = unsafe { data.as_slice() };
if let Ok(grid) = CharGrid::load_utf8(width, height, data.to_vec()) { heap_move_ok(CharGrid::load_utf8(width, height, data.to_vec()))
heap_move(grid)
} else {
std::ptr::null_mut()
}
} }
/// Clones a [CharGrid]. /// Clones a [CharGrid].
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_char_grid_clone( pub unsafe extern "C" fn sp_char_grid_clone(
char_grid: NonNull<CharGrid>, grid: NonNull<CharGrid>,
) -> NonNull<CharGrid> { ) -> NonNull<CharGrid> {
heap_move_nonnull(unsafe { char_grid.as_ref().clone() }) unsafe { heap_clone(grid) }
} }
/// Deallocates a [CharGrid]. /// Deallocates a [CharGrid].
@ -145,11 +146,8 @@ pub unsafe extern "C" fn sp_char_grid_into_packet(
y: usize, y: usize,
) -> *mut Packet { ) -> *mut Packet {
let grid = unsafe { heap_remove(grid) }; let grid = unsafe { heap_remove(grid) };
match Packet::try_from(CharGridCommand { heap_move_ok(Packet::try_from(CharGridCommand {
grid, grid,
origin: Origin::new(x, y), origin: Origin::new(x, y),
}) { }))
Ok(packet) => heap_move(packet),
Err(_) => std::ptr::null_mut(),
}
} }

View file

@ -1,4 +1,10 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice}; use crate::{
containers::ByteSlice,
mem::{
heap_clone, heap_drop, heap_move_nonnull, heap_move_ok, heap_move_some,
heap_remove,
},
};
use servicepoint::{ use servicepoint::{
Cp437Grid, Cp437GridCommand, DataRef, Grid, Origin, Packet, Cp437Grid, Cp437GridCommand, DataRef, Grid, Origin, Packet,
}; };
@ -23,20 +29,15 @@ pub unsafe extern "C" fn sp_cp437_grid_load(
data: ByteSlice, data: ByteSlice,
) -> *mut Cp437Grid { ) -> *mut Cp437Grid {
let data = unsafe { data.as_slice() }; let data = unsafe { data.as_slice() };
let grid = Cp437Grid::load(width, height, data); heap_move_some(Cp437Grid::load(width, height, data))
if let Some(grid) = grid {
heap_move(grid)
} else {
std::ptr::null_mut()
}
} }
/// Clones a [Cp437Grid]. /// Clones a [Cp437Grid].
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_clone( pub unsafe extern "C" fn sp_cp437_grid_clone(
cp437_grid: NonNull<Cp437Grid>, grid: NonNull<Cp437Grid>,
) -> NonNull<Cp437Grid> { ) -> NonNull<Cp437Grid> {
heap_move_nonnull(unsafe { cp437_grid.as_ref().clone() }) unsafe { heap_clone(grid) }
} }
/// Deallocates a [Cp437Grid]. /// Deallocates a [Cp437Grid].
@ -147,11 +148,8 @@ pub unsafe extern "C" fn sp_cp437_grid_into_packet(
y: usize, y: usize,
) -> *mut Packet { ) -> *mut Packet {
let grid = unsafe { heap_remove(grid) }; let grid = unsafe { heap_remove(grid) };
match Packet::try_from(Cp437GridCommand { heap_move_ok(Packet::try_from(Cp437GridCommand {
grid, grid,
origin: Origin::new(x, y), origin: Origin::new(x, y),
}) { }))
Ok(packet) => heap_move(packet),
Err(_) => std::ptr::null_mut(),
}
} }

13
src/containers/mod.rs Normal file
View file

@ -0,0 +1,13 @@
mod bitmap;
mod bitvec;
mod brightness_grid;
mod byte_slice;
mod char_grid;
mod cp437_grid;
pub use bitmap::*;
pub use bitvec::*;
pub use brightness_grid::*;
pub use byte_slice::*;
pub use char_grid::*;
pub use cp437_grid::*;

View file

@ -9,7 +9,7 @@
//! #include "servicepoint.h" //! #include "servicepoint.h"
//! //!
//! int main(void) { //! int main(void) {
//! UdpConnection *connection = sp_udp_open("172.23.42.29:2342"); //! UdpSocket *connection = sp_udp_open("172.23.42.29:2342");
//! if (connection == NULL) //! if (connection == NULL)
//! return 1; //! return 1;
//! //!
@ -25,48 +25,23 @@
//! } //! }
//! ``` //! ```
pub use crate::bitmap::*; /// Functions related to commands.
pub use crate::bitvec::*; pub mod commands;
pub use crate::brightness_grid::*; /// Functions related to [servicepoint::Bitmap], [servicepoint::CharGrid] and friends.
pub use crate::byte_slice::*; pub mod containers;
pub use crate::char_grid::*; pub(crate) mod mem;
pub use crate::cp437_grid::*; /// Functions related to [Packet].
pub use crate::packet::*; pub mod packet;
pub use crate::typed_command::*; /// Functions related to [UdpSocket].
pub use crate::udp::*; pub mod udp;
pub use servicepoint::CommandCode;
use std::ptr::NonNull;
mod bitmap;
mod bitvec;
mod brightness_grid;
mod byte_slice;
mod char_grid;
mod cp437_grid;
mod packet;
mod typed_command;
mod udp;
use std::time::Duration; use std::time::Duration;
/// Actual hardware limit is around 28-29ms/frame. Rounded up for less dropped packets. /// Actual hardware limit is around 28-29ms/frame. Rounded up for less dropped packets.
pub const SP_FRAME_PACING_MS: u128 = Duration::from_millis(30).as_millis(); pub const SP_FRAME_PACING_MS: u128 = Duration::from_millis(30).as_millis();
pub(crate) fn heap_move<T>(x: T) -> *mut T {
Box::into_raw(Box::new(x))
}
pub(crate) fn heap_move_nonnull<T>(x: T) -> NonNull<T> {
NonNull::from(Box::leak(Box::new(x)))
}
pub(crate) unsafe fn heap_drop<T>(x: NonNull<T>) {
drop(unsafe { heap_remove(x) });
}
pub(crate) unsafe fn heap_remove<T>(x: NonNull<T>) -> T {
unsafe { *Box::from_raw(x.as_ptr()) }
}
/// This is a type only used by cbindgen to have a type for pointers. /// This is a type only used by cbindgen to have a type for pointers.
pub struct UdpSocket; pub struct UdpSocket;
/// This is a type only used by cbindgen to have a type for pointers.
pub struct DisplayBitVec;

29
src/mem.rs Normal file
View file

@ -0,0 +1,29 @@
use std::ptr::NonNull;
pub(crate) fn heap_move<T>(x: T) -> *mut T {
Box::into_raw(Box::new(x))
}
pub(crate) fn heap_move_nonnull<T>(x: T) -> NonNull<T> {
NonNull::from(Box::leak(Box::new(x)))
}
pub(crate) fn heap_move_ok<T, E>(x: Result<T, E>) -> *mut T {
x.map(|x| heap_move(x)).unwrap_or(std::ptr::null_mut())
}
pub(crate) fn heap_move_some<T>(x: Option<T>) -> *mut T {
x.map(|x| heap_move(x)).unwrap_or(std::ptr::null_mut())
}
pub(crate) unsafe fn heap_drop<T>(x: NonNull<T>) {
drop(unsafe { heap_remove(x) });
}
pub(crate) unsafe fn heap_remove<T>(x: NonNull<T>) -> T {
unsafe { *Box::from_raw(x.as_ptr()) }
}
pub(crate) unsafe fn heap_clone<T: Clone>(source: NonNull<T>) -> NonNull<T> {
heap_move_nonnull(unsafe { source.as_ref().clone() })
}

View file

@ -1,33 +1,17 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice}; use crate::{
use servicepoint::{CommandCode, Header, Packet, TypedCommand}; containers::ByteSlice,
mem::{heap_clone, heap_drop, heap_move_nonnull, heap_move_ok},
};
use servicepoint::{CommandCode, Header, Packet};
use std::ptr::NonNull; use std::ptr::NonNull;
/// Turns a [TypedCommand] into a [Packet].
/// The [TypedCommand] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_packet_from_command(
command: NonNull<TypedCommand>,
) -> *mut Packet {
let command = unsafe { heap_remove(command) };
if let Ok(packet) = command.try_into() {
heap_move(packet)
} else {
std::ptr::null_mut()
}
}
/// Tries to load a [Packet] from the passed array with the specified length. /// Tries to load a [Packet] from the passed array with the specified length.
/// ///
/// returns: NULL in case of an error, pointer to the allocated packet otherwise /// returns: NULL in case of an error, pointer to the allocated packet otherwise
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_packet_try_load(data: ByteSlice) -> *mut Packet { pub unsafe extern "C" fn sp_packet_try_load(data: ByteSlice) -> *mut Packet {
let data = unsafe { data.as_slice() }; let data = unsafe { data.as_slice() };
match servicepoint::Packet::try_from(data) { heap_move_ok(servicepoint::Packet::try_from(data))
Err(_) => std::ptr::null_mut(),
Ok(packet) => heap_move(packet),
}
} }
/// Creates a raw [Packet] from parts. /// Creates a raw [Packet] from parts.
@ -95,11 +79,13 @@ pub unsafe extern "C" fn sp_packet_serialize_to(
} }
/// Clones a [Packet]. /// Clones a [Packet].
///
/// returns: a new [Packet] instance.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_packet_clone( pub unsafe extern "C" fn sp_packet_clone(
packet: NonNull<Packet>, packet: NonNull<Packet>,
) -> NonNull<Packet> { ) -> NonNull<Packet> {
heap_move_nonnull(unsafe { packet.as_ref().clone() }) unsafe { heap_clone(packet) }
} }
/// Deallocates a [Packet]. /// Deallocates a [Packet].

View file

@ -1,201 +0,0 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, SPBitVec};
use servicepoint::{
BinaryOperation, Bitmap, Brightness, BrightnessGrid, CharGrid,
CompressionCode, Cp437Grid, GlobalBrightnessCommand, Packet, TypedCommand,
};
use std::ptr::NonNull;
/// Tries to turn a [Packet] into a [TypedCommand].
///
/// The packet is deallocated in the process.
///
/// Returns: pointer to new [TypedCommand] instance or NULL if parsing failed.
#[no_mangle]
pub unsafe extern "C" fn sp_command_try_from_packet(
packet: NonNull<Packet>,
) -> *mut TypedCommand {
let packet = *unsafe { Box::from_raw(packet.as_ptr()) };
match servicepoint::TypedCommand::try_from(packet) {
Err(_) => std::ptr::null_mut(),
Ok(command) => heap_move(command),
}
}
/// Clones a [TypedCommand] instance.
///
/// returns: new [TypedCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_command_clone(
command: NonNull<TypedCommand>,
) -> NonNull<TypedCommand> {
heap_move_nonnull(unsafe { command.as_ref().clone() })
}
/// Set all pixels to the off state.
///
/// Does not affect brightness.
///
/// Returns: a new [servicepoint::Command::Clear] instance.
///
/// # Examples
///
/// ```C
/// sp_udp_send_command(connection, sp_command_clear());
/// ```
#[no_mangle]
pub unsafe extern "C" fn sp_command_clear() -> NonNull<TypedCommand> {
heap_move_nonnull(servicepoint::ClearCommand.into())
}
/// Kills the udp daemon on the display, which usually results in a restart.
///
/// Please do not send this in your normal program flow.
///
/// Returns: a new [servicepoint::Command::HardReset] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_command_hard_reset() -> NonNull<TypedCommand> {
heap_move_nonnull(servicepoint::HardResetCommand.into())
}
/// A yet-to-be-tested command.
///
/// Returns: a new [servicepoint::Command::FadeOut] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_command_fade_out() -> NonNull<TypedCommand> {
heap_move_nonnull(servicepoint::FadeOutCommand.into())
}
/// Set the brightness of all tiles to the same value.
///
/// Returns: a new [servicepoint::Command::Brightness] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_command_global_brightness(
brightness: Brightness,
) -> NonNull<TypedCommand> {
heap_move_nonnull(GlobalBrightnessCommand::from(brightness).into())
}
/// Set the brightness of individual tiles in a rectangular area of the display.
///
/// The passed [BrightnessGrid] gets consumed.
///
/// Returns: a new [servicepoint::Command::CharBrightness] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_command_brightness_grid(
x: usize,
y: usize,
grid: NonNull<BrightnessGrid>,
) -> NonNull<TypedCommand> {
let grid = unsafe { *Box::from_raw(grid.as_ptr()) };
let result = servicepoint::BrightnessGridCommand {
origin: servicepoint::Origin::new(x, y),
grid,
}
.into();
heap_move_nonnull(result)
}
/// Set pixel data starting at the pixel offset on screen.
///
/// The screen will continuously overwrite more pixel data without regarding the offset, meaning
/// once the starting row is full, overwriting will continue on column 0.
///
/// The [`BinaryOperation`] will be applied on the display comparing old and sent bit.
///
/// `new_bit = old_bit op sent_bit`
///
/// For example, [`BinaryOperation::Or`] can be used to turn on some pixels without affecting other pixels.
///
/// The contained [`BitVecU8Msb0`] is always uncompressed.
#[no_mangle]
pub unsafe extern "C" fn sp_command_bitvec(
offset: usize,
bit_vec: NonNull<SPBitVec>,
compression: CompressionCode,
operation: BinaryOperation,
) -> *mut TypedCommand {
let bit_vec = unsafe { *Box::from_raw(bit_vec.as_ptr()) };
let command = servicepoint::BitVecCommand {
offset,
operation,
bitvec: bit_vec.0,
compression,
}
.into();
heap_move(command)
}
/// Show codepage 437 encoded text on the screen.
///
/// The passed [Cp437Grid] gets consumed.
///
/// Returns: a new [servicepoint::Cp437GridCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_command_cp437_grid(
x: usize,
y: usize,
grid: NonNull<Cp437Grid>,
) -> NonNull<TypedCommand> {
let grid = *unsafe { Box::from_raw(grid.as_ptr()) };
let result = servicepoint::Cp437GridCommand {
origin: servicepoint::Origin::new(x, y),
grid,
}
.into();
heap_move_nonnull(result)
}
/// Show UTF-8 encoded text on the screen.
///
/// The passed [CharGrid] gets consumed.
///
/// Returns: a new [servicepoint::CharGridCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_command_char_grid(
x: usize,
y: usize,
grid: NonNull<CharGrid>,
) -> NonNull<TypedCommand> {
let grid = unsafe { *Box::from_raw(grid.as_ptr()) };
let result = servicepoint::CharGridCommand {
origin: servicepoint::Origin::new(x, y),
grid,
}
.into();
heap_move_nonnull(result)
}
/// Sets a window of pixels to the specified values.
///
/// The passed [Bitmap] gets consumed.
///
/// Returns: a new [servicepoint::BitmapCommand] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_command_bitmap(
x: usize,
y: usize,
bitmap: NonNull<Bitmap>,
compression: CompressionCode,
) -> *mut TypedCommand {
let bitmap = unsafe { *Box::from_raw(bitmap.as_ptr()) };
let command = servicepoint::BitmapCommand {
origin: servicepoint::Origin::new(x, y),
bitmap,
compression,
}
.into();
heap_move(command)
}
/// Deallocates a [TypedCommand].
///
/// # Examples
///
/// ```C
/// TypedCommand c = sp_command_clear();
/// sp_command_free(c);
/// ```
#[no_mangle]
pub unsafe extern "C" fn sp_command_free(command: NonNull<TypedCommand>) {
unsafe { heap_drop(command) }
}

View file

@ -1,17 +1,22 @@
use crate::{heap_drop, heap_move, heap_remove}; use crate::{
use servicepoint::{Header, Packet, TypedCommand, UdpSocketExt}; commands::{CommandTag, SPCommand},
use std::ffi::{c_char, CStr}; mem::{heap_drop, heap_move_ok, heap_remove},
use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket}; };
use std::ptr::NonNull; use servicepoint::{Header, Packet, UdpSocketExt};
use std::{
ffi::{c_char, CStr},
net::{Ipv4Addr, SocketAddrV4, UdpSocket},
ptr::NonNull,
};
/// Creates a new instance of [UdpConnection]. /// Creates a new instance of [UdpSocket].
/// ///
/// returns: NULL if connection fails, or connected instance /// returns: NULL if connection fails, or connected instance
/// ///
/// # Examples /// # Examples
/// ///
/// ```C /// ```C
/// UdpConnection connection = sp_udp_open("172.23.42.29:2342"); /// UdpSocket connection = sp_udp_open("172.23.42.29:2342");
/// if (connection != NULL) /// if (connection != NULL)
/// sp_udp_send_command(connection, sp_command_clear()); /// sp_udp_send_command(connection, sp_command_clear());
/// ``` /// ```
@ -20,22 +25,18 @@ pub unsafe extern "C" fn sp_udp_open(host: NonNull<c_char>) -> *mut UdpSocket {
let host = unsafe { CStr::from_ptr(host.as_ptr()) } let host = unsafe { CStr::from_ptr(host.as_ptr()) }
.to_str() .to_str()
.expect("Bad encoding"); .expect("Bad encoding");
let connection = match UdpSocket::bind_connect(host) {
Err(_) => return std::ptr::null_mut(),
Ok(value) => value,
};
heap_move(connection) heap_move_ok(UdpSocket::bind_connect(host))
} }
/// Creates a new instance of [UdpConnection]. /// Creates a new instance of [UdpSocket].
/// ///
/// returns: NULL if connection fails, or connected instance /// returns: NULL if connection fails, or connected instance
/// ///
/// # Examples /// # Examples
/// ///
/// ```C /// ```C
/// UdpConnection connection = sp_udp_open_ipv4(172, 23, 42, 29, 2342); /// UdpSocket connection = sp_udp_open_ipv4(172, 23, 42, 29, 2342);
/// if (connection != NULL) /// if (connection != NULL)
/// sp_udp_send_command(connection, sp_command_clear()); /// sp_udp_send_command(connection, sp_command_clear());
/// ``` /// ```
@ -48,14 +49,10 @@ pub unsafe extern "C" fn sp_udp_open_ipv4(
port: u16, port: u16,
) -> *mut UdpSocket { ) -> *mut UdpSocket {
let addr = SocketAddrV4::new(Ipv4Addr::from([ip1, ip2, ip3, ip4]), port); let addr = SocketAddrV4::new(Ipv4Addr::from([ip1, ip2, ip3, ip4]), port);
let connection = match UdpSocket::bind_connect(addr) { heap_move_ok(UdpSocket::bind_connect(addr))
Err(_) => return std::ptr::null_mut(),
Ok(value) => value,
};
heap_move(connection)
} }
/// Sends a [Packet] to the display using the [UdpConnection]. /// Sends a [Packet] to the display using the [UdpSocket].
/// ///
/// The passed `packet` gets consumed. /// The passed `packet` gets consumed.
/// ///
@ -69,7 +66,7 @@ pub unsafe extern "C" fn sp_udp_send_packet(
unsafe { connection.as_ref().send(&Vec::from(packet)) }.is_ok() unsafe { connection.as_ref().send(&Vec::from(packet)) }.is_ok()
} }
/// Sends a [TypedCommand] to the display using the [UdpConnection]. /// Sends a [SPCommand] to the display using the [UdpSocket].
/// ///
/// The passed `command` gets consumed. /// The passed `command` gets consumed.
/// ///
@ -83,13 +80,47 @@ pub unsafe extern "C" fn sp_udp_send_packet(
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_udp_send_command( pub unsafe extern "C" fn sp_udp_send_command(
connection: NonNull<UdpSocket>, connection: NonNull<UdpSocket>,
command: NonNull<TypedCommand>, command: SPCommand,
) -> bool { ) -> bool {
let command = unsafe { heap_remove(command) }; unsafe {
unsafe { connection.as_ref().send_command(command) }.is_some() match command.tag {
CommandTag::Invalid => return false,
CommandTag::Bitmap => connection
.as_ref()
.send_command(heap_remove(command.data.bitmap)),
CommandTag::BitVec => connection
.as_ref()
.send_command(heap_remove(command.data.bitvec)),
CommandTag::BrightnessGrid => connection
.as_ref()
.send_command(heap_remove(command.data.brightness_grid)),
CommandTag::CharGrid => connection
.as_ref()
.send_command(heap_remove(command.data.char_grid)),
CommandTag::Cp437Grid => connection
.as_ref()
.send_command(heap_remove(command.data.cp437_grid)),
CommandTag::GlobalBrightness => connection
.as_ref()
.send_command(heap_remove(command.data.global_brightness)),
CommandTag::Clear => connection
.as_ref()
.send_command(heap_remove(command.data.clear)),
CommandTag::HardReset => connection
.as_ref()
.send_command(heap_remove(command.data.hard_reset)),
CommandTag::FadeOut => connection
.as_ref()
.send_command(heap_remove(command.data.fade_out)),
CommandTag::BitmapLegacy => connection
.as_ref()
.send_command(heap_remove(command.data.bitmap_legacy)),
}
}
.is_some()
} }
/// Sends a [Header] to the display using the [UdpConnection]. /// Sends a [Header] to the display using the [UdpSocket].
/// ///
/// returns: true in case of success /// returns: true in case of success
/// ///
@ -112,7 +143,7 @@ pub unsafe extern "C" fn sp_udp_send_header(
.is_ok() .is_ok()
} }
/// Closes and deallocates a [UdpConnection]. /// Closes and deallocates a [UdpSocket].
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_udp_free(connection: NonNull<UdpSocket>) { pub unsafe extern "C" fn sp_udp_free(connection: NonNull<UdpSocket>) {
unsafe { heap_drop(connection) } unsafe { heap_drop(connection) }