Compare commits

..

17 commits

Author SHA1 Message Date
Vinzenz Schroeter 82696b2d1a add slice modifier
Some checks failed
Rust / build-gnu-apt (pull_request) Successful in 2m7s
Rust / build-size-gnu-unstable (pull_request) Failing after 2m48s
2025-06-26 19:26:41 +02:00
Vinzenz Schroeter 39c7c27c86 implement return modifiers 2025-06-26 18:59:46 +02:00
Vinzenz Schroeter 0968605d0b cleanups, add semicolon everywhere 2025-06-26 17:29:03 +02:00
Vinzenz Schroeter e8f11c08ea add parameter modifiers 2025-06-23 23:28:30 +02:00
Vinzenz Schroeter 664625402f move where the modifier is 2025-06-23 21:36:01 +02:00
Vinzenz Schroeter 5a849a87c7 fix missing renames 2025-06-23 21:16:22 +02:00
Vinzenz Schroeter 323ba6128e add move fn to dsl, rename SPCommand to GenericCommand, remove DisplayBitVec command 2025-06-23 20:26:22 +02:00
Vinzenz Schroeter e434130784 unifiy special handling of params and return 2025-06-23 19:43:52 +02:00
Vinzenz Schroeter 92ce27af68 simplify property exports 2025-06-23 19:43:23 +02:00
Vinzenz Schroeter 7a836783e1 rename function to ...try to indicate possible null return 2025-06-22 13:00:32 +02:00
Vinzenz Schroeter b4730ffdf3 container macro code dedup 2025-06-22 12:52:53 +02:00
Vinzenz Schroeter 5ecb84ed16 derive try_into_packet automatically 2025-06-22 12:28:37 +02:00
Vinzenz Schroeter 8116375fd0 more type name based naming 2025-06-22 12:28:37 +02:00
Vinzenz Schroeter 8f13ba61f0 remove _ from type names in function names 2025-06-22 00:14:06 +02:00
Vinzenz Schroeter 500cbbc872 add prefix centrally 2025-06-21 23:51:10 +02:00
Vinzenz Schroeter 1eb59d986a wrap_command macro 2025-06-21 23:47:42 +02:00
Vinzenz Schroeter 18f0be072a fix docs, misc tweaks 2025-06-19 18:32:07 +02:00
30 changed files with 1958 additions and 1910 deletions

View file

@ -96,7 +96,7 @@ endif
# ADD NEW EXAMPLES HERE # ADD NEW EXAMPLES HERE
_c_src := src/announce.c src/brightness_tester.c src/header_logger.c \ _c_src := src/announce.c src/brightness_tester.c src/header_logger.c \
src/moving_line.c src/random_stuff.c src/wiping_clear.c src/moving_line.c src/random_stuff.c src/wiping_clear.c src/undefined.c
_programs := $(basename $(notdir $(_c_src))) _programs := $(basename $(notdir $(_c_src)))
_bins := $(_programs) _bins := $(_programs)
_unstripped_bins := $(addsuffix _unstripped, $(_bins)) _unstripped_bins := $(addsuffix _unstripped, $(_bins))

View file

@ -3,27 +3,27 @@
int main(void) { int main(void) {
sock_init(); sock_init();
sp_udp_send_header(sock, (Header) {.command_code = COMMAND_CODE_CLEAR}); sp_udpsocket_send_header(sock, (Header) {.command_code = COMMAND_CODE_CLEAR});
CharGrid *grid = sp_char_grid_new(5, 2); CharGrid *grid = sp_chargrid_new(5, 2);
if (grid == NULL) if (grid == NULL)
return 1; return 1;
sp_char_grid_set(grid, 0, 0, 'H'); sp_chargrid_set(grid, 0, 0, 'H');
sp_char_grid_set(grid, 1, 0, 'e'); sp_chargrid_set(grid, 1, 0, 'e');
sp_char_grid_set(grid, 2, 0, 'l'); sp_chargrid_set(grid, 2, 0, 'l');
sp_char_grid_set(grid, 3, 0, 'l'); sp_chargrid_set(grid, 3, 0, 'l');
sp_char_grid_set(grid, 4, 0, 'o'); sp_chargrid_set(grid, 4, 0, 'o');
sp_char_grid_set(grid, 0, 1, 'W'); sp_chargrid_set(grid, 0, 1, 'W');
sp_char_grid_set(grid, 1, 1, 'o'); sp_chargrid_set(grid, 1, 1, 'o');
sp_char_grid_set(grid, 2, 1, 'r'); sp_chargrid_set(grid, 2, 1, 'r');
sp_char_grid_set(grid, 3, 1, 'l'); sp_chargrid_set(grid, 3, 1, 'l');
sp_char_grid_set(grid, 4, 1, 'd'); sp_chargrid_set(grid, 4, 1, 'd');
Packet *packet = sp_char_grid_into_packet(grid, 0, 0); Packet *packet = sp_chargrid_try_into_packet(grid, 0, 0);
if (packet == NULL) if (packet == NULL)
return 1; return 1;
sp_udp_send_packet(sock, packet); sp_udpsocket_send_packet(sock, packet);
return 0; return 0;
} }

View file

@ -5,14 +5,14 @@ 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);
BitmapCommand *bitmapCommand = sp_cmd_bitmap_from_bitmap(all_on); BitmapCommand *bitmapCommand = sp_bitmapcommand_from_bitmap(all_on);
Packet *packet = sp_cmd_bitmap_try_into_packet(bitmapCommand); Packet *packet = sp_bitmapcommand_try_into_packet(bitmapCommand);
if (packet != NULL) if (packet != NULL)
sp_udp_send_packet(sock, packet); sp_udpsocket_send_packet(sock, packet);
} }
void make_brightness_pattern(BrightnessGrid *grid) { void make_brightness_pattern(BrightnessGrid *grid) {
ByteSlice slice = sp_brightness_grid_data_ref_mut(grid); ByteSlice slice = sp_brightnessgrid_data_ref_mut(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));
} }
@ -23,13 +23,13 @@ int main(void) {
enable_all_pixels(); enable_all_pixels();
BrightnessGrid *grid = sp_brightness_grid_new(TILE_WIDTH, TILE_HEIGHT); BrightnessGrid *grid = sp_brightnessgrid_new(TILE_WIDTH, TILE_HEIGHT);
make_brightness_pattern(grid); make_brightness_pattern(grid);
Packet *packet = sp_cmd_brightness_grid_into_packet(sp_cmd_brightness_grid_from_grid(grid)); Packet *packet = sp_brightnessgridcommand_try_into_packet(sp_brightnessgridcommand_from_grid(grid));
if (packet == NULL) if (packet == NULL)
return -2; return -2;
sp_udp_send_packet(sock, packet); sp_udpsocket_send_packet(sock, packet);
return 0; return 0;
} }

View file

@ -15,8 +15,8 @@ void handle_error(const char *msg) {
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
bool log_command(struct Command command) { bool log_command(struct GenericCommand *command) {
switch (command.tag) { switch (command->tag) {
case COMMAND_TAG_INVALID: { case COMMAND_TAG_INVALID: {
printf("-> this is an invalid command\n"); printf("-> this is an invalid command\n");
break; break;
@ -26,14 +26,14 @@ bool log_command(struct Command command) {
return true; return true;
} }
case COMMAND_TAG_BITMAP: { case COMMAND_TAG_BITMAP: {
BitmapCommand *bitmapCommand = command.data.bitmap; BitmapCommand *bitmapCommand = command->data.bitmap;
CompressionCode compression = sp_cmd_bitmap_get_compression(bitmapCommand); CompressionCode compression = sp_bitmapcommand_get_compression(bitmapCommand);
size_t x, y; size_t x, y;
sp_cmd_bitmap_get_origin(bitmapCommand, &x, &y); sp_bitmapcommand_get_origin(bitmapCommand, &x, &y);
Bitmap *bitmap = sp_cmd_bitmap_get(bitmapCommand); Bitmap *bitmap = sp_bitmapcommand_get_bitmap_mut(bitmapCommand);
size_t w = sp_bitmap_width(bitmap); size_t w = sp_bitmap_width(bitmap);
size_t h = sp_bitmap_height(bitmap); size_t h = sp_bitmap_height(bitmap);
@ -42,54 +42,54 @@ bool log_command(struct Command command) {
break; break;
} }
case COMMAND_TAG_BRIGHTNESS_GRID: { case COMMAND_TAG_BRIGHTNESS_GRID: {
BrightnessGridCommand *gridCommand = command.data.brightness_grid; BrightnessGridCommand *gridCommand = command->data.brightness_grid;
size_t x, y; size_t x, y;
sp_cmd_brightness_grid_get_origin(gridCommand, &x, &y); sp_brightnessgridcommand_get_origin(gridCommand, &x, &y);
BrightnessGrid *grid = sp_cmd_brightness_grid_get(gridCommand); BrightnessGrid *grid = sp_brightnessgridcommand_get_grid_mut(gridCommand);
size_t w = sp_brightness_grid_width(grid); size_t w = sp_brightnessgrid_width(grid);
size_t h = sp_brightness_grid_height(grid); size_t h = sp_brightnessgrid_height(grid);
printf("-> BrightnessGridCommand with params: x=%zu, y=%zu, w=%zu, h=%zu\n", printf("-> BrightnessGridCommand with params: x=%zu, y=%zu, w=%zu, h=%zu\n",
x, y, w, h); x, y, w, h);
break; break;
} }
case COMMAND_TAG_CHAR_GRID: { case COMMAND_TAG_CHAR_GRID: {
CharGridCommand *gridCommand = command.data.char_grid; CharGridCommand *gridCommand = command->data.char_grid;
size_t x, y; size_t x, y;
sp_cmd_char_grid_get_origin(gridCommand, &x, &y); sp_chargridcommand_get_origin(gridCommand, &x, &y);
CharGrid *grid = sp_cmd_char_grid_get(gridCommand); CharGrid *grid = sp_chargridcommand_get_grid_mut(gridCommand);
size_t w = sp_char_grid_width(grid); size_t w = sp_chargrid_width(grid);
size_t h = sp_char_grid_height(grid); size_t h = sp_chargrid_height(grid);
printf("-> CharGridCommand with params: x=%zu, y=%zu, w=%zu, h=%zu\n", printf("-> CharGridCommand with params: x=%zu, y=%zu, w=%zu, h=%zu\n",
x, y, w, h); x, y, w, h);
break; break;
} }
case COMMAND_TAG_CP437_GRID: { case COMMAND_TAG_CP437_GRID: {
Cp437GridCommand *gridCommand = command.data.cp437_grid; Cp437GridCommand *gridCommand = command->data.cp437_grid;
size_t x, y; size_t x, y;
sp_cmd_cp437_grid_get_origin(gridCommand, &x, &y); sp_cp437gridcommand_get_origin(gridCommand, &x, &y);
Cp437Grid *grid = sp_cmd_cp437_grid_get(gridCommand); Cp437Grid *grid = sp_cp437gridcommand_get_grid_mut(gridCommand);
size_t w = sp_cp437_grid_width(grid); size_t w = sp_cp437grid_width(grid);
size_t h = sp_cp437_grid_height(grid); size_t h = sp_cp437grid_height(grid);
printf("-> Cp437GridCommand with params: x=%zu, y=%zu, w=%zu, h=%zu\n", printf("-> Cp437GridCommand with params: x=%zu, y=%zu, w=%zu, h=%zu\n",
x, y, w, h); x, y, w, h);
break; break;
} }
case COMMAND_TAG_BIT_VEC: { case COMMAND_TAG_BIT_VEC: {
BitVecCommand *bitvecCommand = command.data.bitvec; BitVecCommand *bitvecCommand = command->data.bit_vec;
size_t offset = sp_cmd_bitvec_get_offset(bitvecCommand); size_t offset = sp_bitveccommand_get_offset(bitvecCommand);
CompressionCode compression = sp_cmd_bitvec_get_compression(bitvecCommand); CompressionCode compression = sp_bitveccommand_get_compression(bitvecCommand);
BinaryOperation operation = sp_cmd_bitvec_get_operation(bitvecCommand); BinaryOperation operation = sp_bitveccommand_get_operation(bitvecCommand);
char *operationText; char *operationText;
switch (operation) { switch (operation) {
case BINARY_OPERATION_AND: case BINARY_OPERATION_AND:
@ -109,8 +109,8 @@ bool log_command(struct Command command) {
break; break;
} }
BitVec *bitvec = sp_cmd_bitvec_get(bitvecCommand); DisplayBitVec *bitvec = sp_bitveccommand_get_bitvec_mut(bitvecCommand);
size_t len = sp_bitvec_len(bitvec); size_t len = sp_displaybitvec_len(bitvec);
printf("-> BitVecCommand with params: offset=%zu, length=%zu, compression=%hu, operation=%s\n", printf("-> BitVecCommand with params: offset=%zu, length=%zu, compression=%hu, operation=%s\n",
offset, len, compression, operationText); offset, len, compression, operationText);
@ -129,12 +129,12 @@ bool log_command(struct Command command) {
break; break;
} }
case COMMAND_TAG_GLOBAL_BRIGHTNESS: { case COMMAND_TAG_GLOBAL_BRIGHTNESS: {
Brightness brightness = sp_cmd_brightness_global_get_brightness(command.data.global_brightness); Brightness brightness = sp_globalbrightnesscommand_get_brightness(command->data.global_brightness);
printf("-> GlobalBrightnessCommand with params: brightness=%hu\n", brightness); printf("-> GlobalBrightnessCommand with params: brightness=%hu\n", brightness);
break; break;
} }
default: { default: {
printf("-> unknown command tag %d\n", command.tag); printf("-> unknown command tag %d\n", command->tag);
break; break;
} }
} }
@ -198,10 +198,10 @@ int main(int argc, char **argv) {
header->command_code, header->a, header->b, header->c, header->d, header->command_code, header->a, header->b, header->c, header->d,
payload.start, payload.length); payload.start, payload.length);
struct Command command = sp_cmd_generic_try_from_packet(packet); struct GenericCommand *command = sp_genericcommand_try_from_packet(packet);
done = log_command(command); done = log_command(command);
sp_cmd_generic_free(command); sp_genericcommand_free(command);
} }
close(udp_socket); close(udp_socket);

View file

@ -10,12 +10,12 @@
static UdpSocket *sock = NULL; static UdpSocket *sock = NULL;
void sock_free() { void sock_free() {
sp_udp_free(sock); sp_udpsocket_free(sock);
} }
void sock_init() { void sock_init() {
//sock = sp_udp_open_ipv4(127, 0, 0, 1, 2342); sock = sp_udpsocket_open_ipv4(127, 0, 0, 1, 2342);
sock = sp_udp_open_ipv4(172, 23, 42, 29, 2342); //sock = sp_udp_open_ipv4(172, 23, 42, 29, 2342);
if (sock == NULL) if (sock == NULL)
exit(-1); exit(-1);
atexit(sock_free); atexit(sock_free);

View file

@ -13,14 +13,14 @@ int main(void) {
sp_bitmap_set(bitmap, (y + x) % PIXEL_WIDTH, y, true); sp_bitmap_set(bitmap, (y + x) % PIXEL_WIDTH, y, true);
} }
BitmapCommand *command = sp_cmd_bitmap_from_bitmap(sp_bitmap_clone(bitmap)); BitmapCommand *command = sp_bitmapcommand_from_bitmap(sp_bitmap_clone(bitmap));
Packet *packet = sp_cmd_bitmap_try_into_packet(command); Packet *packet = sp_bitmapcommand_try_into_packet(command);
if (packet == NULL) { if (packet == NULL) {
result = -2; result = -2;
goto exit; goto exit;
} }
if (!sp_udp_send_packet(sock, packet)) { if (!sp_udpsocket_send_packet(sock, packet)) {
result = -3; result = -3;
goto exit; goto exit;
} }

View file

@ -11,13 +11,13 @@ int main(void) {
sp_bitmap_fill(pixels, true); sp_bitmap_fill(pixels, true);
Packet *packet = sp_bitmap_into_packet(pixels, 0, 0, COMPRESSION_CODE_UNCOMPRESSED); Packet *packet = sp_bitmap_try_into_packet(pixels, 0, 0, COMPRESSION_CODE_UNCOMPRESSED);
if (packet == NULL) if (packet == NULL)
return 1; return 1;
Header *header = sp_packet_get_header_mut(packet); Header *header = sp_packet_get_header_mut(packet);
printf("[%d, %d, %d, %d, %d]\n", header->command_code, header->a, header->b, header->c, header->d); printf("[%d, %d, %d, %d, %d]\n", header->command_code, header->a, header->b, header->c, header->d);
sp_udp_send_packet(sock, packet); sp_udpsocket_send_packet(sock, packet);
return 0; return 0;
} }

22
example/src/undefined.c Normal file
View file

@ -0,0 +1,22 @@
#include <stdio.h>
#include "servicepoint.h"
#include "helpers.h"
/// DO NOT DO ANY OF THIS!
int main(void) {
BitmapCommand *bmcmd = sp_bitmapcommand_new(sp_bitmap_new_max_sized(), 0, 0, COMPRESSION_CODE_UNCOMPRESSED);
BitVecCommand *bvcmd = (BitVecCommand *) bmcmd;
sp_bitveccommand_free(bvcmd);
uint8_t *data = calloc(1024, 1);
struct GenericCommand generic = {
.tag = COMMAND_TAG_BRIGHTNESS_GRID,
.data = {.null = data},
};
sock_init();
sp_udpsocket_send_command(sock, &generic);
return 0;
}

View file

@ -13,14 +13,14 @@ int main() {
sp_bitmap_set(enabled_pixels, x, y, false); sp_bitmap_set(enabled_pixels, x, y, false);
} }
BitVec *bitvec = sp_bitmap_into_bitvec(sp_bitmap_clone(enabled_pixels)); DisplayBitVec *bitvec = sp_bitmap_into_bitvec(sp_bitmap_clone(enabled_pixels));
BitVecCommand *command = sp_cmd_bitvec_new(bitvec, 0, BINARY_OPERATION_AND, COMPRESSION_CODE_LZMA); BitVecCommand *command = sp_bitveccommand_new(bitvec, 0, BINARY_OPERATION_AND, COMPRESSION_CODE_LZMA);
Packet *packet = sp_cmd_bitvec_try_into_packet(command); Packet *packet = sp_bitveccommand_try_into_packet(command);
if (packet == NULL) { if (packet == NULL) {
result = -2; result = -2;
goto exit; goto exit;
} }
if (!sp_udp_send_packet(sock, packet)) { if (!sp_udpsocket_send_packet(sock, packet)) {
result = -3; result = -3;
goto exit; goto exit;
} }

File diff suppressed because it is too large Load diff

View file

@ -1,56 +1,43 @@
use crate::{ use crate::{
commands::wrap_origin_accessors, commands::{wrap_command, wrap_origin_accessors},
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions}, macros::{wrap_fields, wrap_functions},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
}; };
use servicepoint::{Bitmap, BitmapCommand, CompressionCode, Origin, Packet}; use servicepoint::{Bitmap, BitmapCommand, CompressionCode, Origin};
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_clone!(sp_cmd_bitmap::BitmapCommand); wrap_command!(Bitmap);
wrap_free!(sp_cmd_bitmap::BitmapCommand);
wrap_fields!(sp_cmd_bitmap::BitmapCommand; wrap_fields!(BitmapCommand;
prop bitmap: Bitmap { mut get(); move set(value); }; prop bitmap: Bitmap { get mut; set move; };
prop compression: CompressionCode { get(); set(value); }; prop compression: CompressionCode { get; set; };
); );
wrap_origin_accessors!(sp_cmd_bitmap::BitmapCommand); wrap_origin_accessors!(BitmapCommand);
wrap_functions!(sp_cmd_bitmap; wrap_functions!(associate BitmapCommand;
/// Sets a window of pixels to the specified values. /// Sets a window of pixels to the specified values.
/// ///
/// The passed [Bitmap] gets consumed. /// The passed [Bitmap] gets consumed.
/// ///
/// Returns: a new [BitmapCommand] instance. /// Returns: a new [BitmapCommand] instance.
fn new( fn new(
bitmap: NonNull<Bitmap>, bitmap: move NonNull<Bitmap>,
origin_x: usize, origin_x: val usize,
origin_y: usize, origin_y: val usize,
compression: CompressionCode, compression: val CompressionCode,
) -> NonNull<BitmapCommand> { ) -> move NonNull<BitmapCommand> {
heap_move_nonnull(BitmapCommand { BitmapCommand {
bitmap: unsafe { heap_remove(bitmap) }, bitmap,
origin: Origin::new(origin_x, origin_y), origin: Origin::new(origin_x, origin_y),
compression, compression,
}) }
} };
/// Move the provided [Bitmap] into a new [BitmapCommand], /// Move the provided [Bitmap] into a new [BitmapCommand],
/// leaving other fields as their default values. /// leaving other fields as their default values.
/// ///
/// Rust equivalent: `BitmapCommand::from(bitmap)` /// Rust equivalent: `BitmapCommand::from(bitmap)`
fn from_bitmap( fn from_bitmap(bitmap: move NonNull<Bitmap>) -> move NonNull<BitmapCommand> {
bitmap: NonNull<Bitmap>, bitmap.into()
) -> 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.
fn try_into_packet(
command: NonNull<BitmapCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
); );

View file

@ -1,25 +1,22 @@
use crate::{ use crate::{
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions}, commands::wrap_command,
mem::{heap_move_nonnull, heap_move_ok, heap_remove}, macros::{wrap_fields, wrap_functions},
}; };
use servicepoint::{ use servicepoint::{
BinaryOperation, BitVecCommand, CompressionCode, DisplayBitVec, Offset, BinaryOperation, BitVecCommand, CompressionCode, DisplayBitVec, Offset,
Packet,
}; };
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_clone!(sp_cmd_bitvec::BitVecCommand); wrap_command!(BitVec);
wrap_free!(sp_cmd_bitvec::BitVecCommand);
wrap_fields!(sp_cmd_bitvec::BitVecCommand; wrap_fields!(BitVecCommand;
prop bitvec: DisplayBitVec { mut get(); move set(value); }; prop bitvec: DisplayBitVec { get mut; set move; };
prop offset: Offset { get(); set(value); }; prop offset: Offset { get; set; };
prop operation: BinaryOperation { get(); set(value); }; prop operation: BinaryOperation { get; set; };
prop compression: CompressionCode { get(); set(value); }; prop compression: CompressionCode { get; set; };
); );
wrap_functions!(sp_cmd_bitvec; wrap_functions!(associate BitVecCommand;
/// Set pixel data starting at the pixel offset on screen. /// Set pixel data starting at the pixel offset on screen.
/// ///
/// The screen will continuously overwrite more pixel data without regarding the offset, meaning /// The screen will continuously overwrite more pixel data without regarding the offset, meaning
@ -33,26 +30,16 @@ wrap_functions!(sp_cmd_bitvec;
/// ///
/// The contained [`DisplayBitVec`] is always uncompressed. /// The contained [`DisplayBitVec`] is always uncompressed.
fn new( fn new(
bitvec: NonNull<DisplayBitVec>, bitvec: move NonNull<DisplayBitVec>,
offset: usize, offset: val usize,
operation: BinaryOperation, operation: val BinaryOperation,
compression: CompressionCode, compression: val CompressionCode,
) -> NonNull<BitVecCommand> { ) -> move NonNull<BitVecCommand> {
heap_move_nonnull(BitVecCommand { BitVecCommand {
bitvec: unsafe { heap_remove(bitvec) }, bitvec,
offset, offset,
operation, operation,
compression, compression,
}) }
} };
/// Tries to turn a [BitVecCommand] into a [Packet].
///
/// Returns: NULL or a [Packet] containing the command.
fn try_into_packet(
command: NonNull<BitVecCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
); );

View file

@ -1,53 +1,38 @@
use crate::{ use crate::{
commands::wrap_origin_accessors, commands::{wrap_command, wrap_origin_accessors},
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions}, macros::{wrap_fields, wrap_functions},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
}; };
use servicepoint::{BrightnessGrid, BrightnessGridCommand, Origin, Packet}; use servicepoint::{BrightnessGrid, BrightnessGridCommand, Origin};
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_clone!(sp_cmd_brightness_grid::BrightnessGridCommand); wrap_command!(BrightnessGrid);
wrap_free!(sp_cmd_brightness_grid::BrightnessGridCommand);
wrap_fields!(sp_cmd_brightness_grid::BrightnessGridCommand; wrap_fields!(BrightnessGridCommand;
prop grid: BrightnessGrid { mut get(); move set(grid); }; prop grid: BrightnessGrid { get mut; set move; };
); );
wrap_origin_accessors!(sp_cmd_brightness_grid::BrightnessGridCommand); wrap_origin_accessors!(BrightnessGridCommand);
wrap_functions!(sp_cmd_brightness_grid;
wrap_functions!(associate BrightnessGridCommand;
/// Set the brightness of individual tiles in a rectangular area of the display. /// Set the brightness of individual tiles in a rectangular area of the display.
/// ///
/// The passed [BrightnessGrid] gets consumed. /// The passed [BrightnessGrid] gets consumed.
/// ///
/// Returns: a new [BrightnessGridCommand] instance. /// Returns: a new [BrightnessGridCommand] instance.
fn new( fn new(
grid: NonNull<BrightnessGrid>, grid: move NonNull<BrightnessGrid>,
origin_x: usize, origin_x: val usize,
origin_y: usize, origin_y: val usize
) -> NonNull<BrightnessGridCommand> { ) -> move NonNull<BrightnessGridCommand> {
heap_move_nonnull(BrightnessGridCommand { BrightnessGridCommand {
grid: unsafe { heap_remove(grid) }, grid,
origin: Origin::new(origin_x, origin_y), origin: Origin::new(origin_x, origin_y),
}) }
} };
/// Moves the provided [BrightnessGrid] into a new [BrightnessGridCommand], /// Moves the provided [BrightnessGrid] into a new [BrightnessGridCommand],
/// leaving other fields as their default values. /// leaving other fields as their default values.
fn from_grid( fn from_grid(grid: move NonNull<BrightnessGrid>) -> move NonNull<BrightnessGridCommand> {
grid: NonNull<BrightnessGrid>, grid.into()
) -> 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.
fn into_packet(
command: NonNull<BrightnessGridCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
); );

View file

@ -1,37 +1,38 @@
use crate::{ use crate::{commands::wrap_command, macros::wrap_functions};
macros::{wrap_free, wrap_functions},
mem::heap_move_nonnull,
};
use servicepoint::{ClearCommand, FadeOutCommand, HardResetCommand}; use servicepoint::{ClearCommand, FadeOutCommand, HardResetCommand};
use std::ptr::NonNull;
macro_rules! wrap_cc_only { macro_rules! wrap_cc_only {
($prefix:ident :: $typ:ident ; $(#[$meta:meta])*) => { ($(#[$meta:meta])* $command:ident) => {
wrap_functions!($prefix; ::paste::paste!{
$(#[$meta])* wrap_command!($command);
///
#[doc = concat!(" Returns: a new [`",stringify!($typ),"`] instance.")]
fn new() -> NonNull<$typ> {
heap_move_nonnull($typ)
}
);
wrap_free!($prefix :: $typ); wrap_functions!(associate [< $command Command >];
$(#[$meta])*
///
#[doc = " Returns: a new [`" [< $command Command >] "`] instance."]
fn new() -> move ::core::ptr::NonNull<[< $command Command >]> {
[< $command Command >]
};
);
}
}; };
} }
wrap_cc_only!(sp_cmd_clear::ClearCommand; wrap_cc_only!(
/// Set all pixels to the off state. /// Set all pixels to the off state.
/// ///
/// Does not affect brightness. /// Does not affect brightness.
Clear
); );
wrap_cc_only!(sp_cmd_hard_reset::HardResetCommand; wrap_cc_only!(
/// Kills the udp daemon on the display, which usually results in a restart. /// Kills the udp daemon on the display, which usually results in a restart.
/// ///
/// Please do not send this in your normal program flow. /// Please do not send this in your normal program flow.
HardReset
); );
wrap_cc_only!(sp_cmd_fade_out::FadeOutCommand; wrap_cc_only!(
/// A yet-to-be-tested command. /// A yet-to-be-tested command.
FadeOut
); );

View file

@ -1,53 +1,38 @@
use crate::{ use crate::{
commands::wrap_origin_accessors, commands::{wrap_command, wrap_origin_accessors},
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions}, macros::{wrap_fields, wrap_functions},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
}; };
use servicepoint::{CharGrid, CharGridCommand, Origin, Packet}; use servicepoint::{CharGrid, CharGridCommand, Origin};
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_clone!(sp_cmd_char_grid::CharGridCommand); wrap_command!(CharGrid);
wrap_free!(sp_cmd_char_grid::CharGridCommand);
wrap_fields!(sp_cmd_char_grid::CharGridCommand; wrap_fields!(CharGridCommand;
prop grid: CharGrid { mut get(); move set(grid); }; prop grid: CharGrid { get mut; set move; };
); );
wrap_origin_accessors!(sp_cmd_char_grid::CharGridCommand); wrap_origin_accessors!(CharGridCommand);
wrap_functions!(sp_cmd_char_grid;
wrap_functions!(associate CharGridCommand;
/// Show UTF-8 encoded text on the screen. /// Show UTF-8 encoded text on the screen.
/// ///
/// The passed [CharGrid] gets consumed. /// The passed [CharGrid] gets consumed.
/// ///
/// Returns: a new [CharGridCommand] instance. /// Returns: a new [CharGridCommand] instance.
fn new( fn new(
grid: NonNull<CharGrid>, grid: move NonNull<CharGrid>,
origin_x: usize, origin_x: val usize,
origin_y: usize, origin_y: val usize,
) -> NonNull<CharGridCommand> { ) -> move NonNull<CharGridCommand> {
heap_move_nonnull(CharGridCommand { CharGridCommand {
grid: unsafe { heap_remove(grid) }, grid,
origin: Origin::new(origin_x, origin_y), origin: Origin::new(origin_x, origin_y),
}) }
} };
/// Moves the provided [CharGrid] into a new [CharGridCommand], /// Moves the provided [CharGrid] into a new [CharGridCommand],
/// leaving other fields as their default values. /// leaving other fields as their default values.
fn from_grid( fn from_grid(grid: move NonNull<CharGrid>) -> move NonNull<CharGridCommand> {
grid: NonNull<CharGrid>, grid.into()
) -> 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.
fn try_into_packet(
command: NonNull<CharGridCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
); );

View file

@ -1,53 +1,38 @@
use crate::{ use crate::{
commands::wrap_origin_accessors, commands::{wrap_command, wrap_origin_accessors},
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions}, macros::{wrap_fields, wrap_functions},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
}; };
use servicepoint::{Cp437Grid, Cp437GridCommand, Origin, Packet}; use servicepoint::{Cp437Grid, Cp437GridCommand, Origin};
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_clone!(sp_cmd_cp437_grid::Cp437GridCommand); wrap_command!(Cp437Grid);
wrap_free!(sp_cmd_cp437_grid::Cp437GridCommand);
wrap_fields!(sp_cmd_cp437_grid::Cp437GridCommand; wrap_fields!(Cp437GridCommand;
prop grid: Cp437Grid { mut get(); move set(grid); }; prop grid: Cp437Grid { get mut; set move; };
); );
wrap_origin_accessors!(sp_cmd_cp437_grid::Cp437GridCommand); wrap_origin_accessors!(Cp437GridCommand);
wrap_functions!(sp_cmd_cp437_grid;
wrap_functions!(associate Cp437GridCommand;
/// Show text on the screen. /// Show text on the screen.
/// ///
/// The text is sent in the form of a 2D grid of [CP-437] encoded characters. /// 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. /// The origin is relative to the top-left of the display.
fn new( fn new(
grid: NonNull<Cp437Grid>, grid: move NonNull<Cp437Grid>,
origin_x: usize, origin_x: val usize,
origin_y: usize, origin_y: val usize,
) -> NonNull<Cp437GridCommand> { ) -> move NonNull<Cp437GridCommand> {
heap_move_nonnull(Cp437GridCommand { Cp437GridCommand {
grid: unsafe { heap_remove(grid) }, grid,
origin: Origin::new(origin_x, origin_y), origin: Origin::new(origin_x, origin_y),
}) }
} };
/// Moves the provided [Cp437Grid] into a new [Cp437GridCommand], /// Moves the provided [Cp437Grid] into a new [Cp437GridCommand],
/// leaving other fields as their default values. /// leaving other fields as their default values.
fn from_grid( fn from_grid(grid: move NonNull<Cp437Grid>) -> move NonNull<Cp437GridCommand> {
grid: NonNull<Cp437Grid>, grid.into()
) -> 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.
fn try_into_packet(
command: NonNull<Cp437GridCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
); );

View file

@ -1,5 +1,5 @@
use crate::{ use crate::{
macros::wrap_functions, macros::{derive_clone, derive_free, wrap_functions, wrap_methods},
mem::{ mem::{
heap_clone, heap_drop, heap_move, heap_move_nonnull, heap_move_ok, heap_clone, heap_drop, heap_move, heap_move_nonnull, heap_move_ok,
heap_remove, heap_remove,
@ -18,7 +18,7 @@ use std::ptr::{null_mut, NonNull};
pub union CommandUnion { pub union CommandUnion {
pub null: *mut u8, pub null: *mut u8,
pub bitmap: NonNull<BitmapCommand>, pub bitmap: NonNull<BitmapCommand>,
pub bitvec: NonNull<BitVecCommand>, pub bit_vec: NonNull<BitVecCommand>,
pub brightness_grid: NonNull<BrightnessGridCommand>, pub brightness_grid: NonNull<BrightnessGridCommand>,
pub char_grid: NonNull<CharGridCommand>, pub char_grid: NonNull<CharGridCommand>,
pub cp437_grid: NonNull<Cp437GridCommand>, pub cp437_grid: NonNull<Cp437GridCommand>,
@ -55,221 +55,214 @@ pub enum CommandTag {
/// ///
/// Rust equivalent: [TypedCommand]. /// Rust equivalent: [TypedCommand].
#[repr(C)] #[repr(C)]
pub struct SPCommand { pub struct GenericCommand {
/// Specifies which kind of command struct is contained in `data` /// Specifies which kind of command struct is contained in `data`
pub tag: CommandTag, pub tag: CommandTag,
/// The pointer to the command struct /// The pointer to the command struct
pub data: CommandUnion, pub data: CommandUnion,
} }
impl SPCommand { impl GenericCommand {
const INVALID: SPCommand = SPCommand { pub(crate) const INVALID: GenericCommand = GenericCommand {
tag: CommandTag::Invalid, tag: CommandTag::Invalid,
data: CommandUnion { null: null_mut() }, data: CommandUnion { null: null_mut() },
}; };
} }
wrap_functions!(sp_cmd_generic; derive_clone!(GenericCommand);
/// Tries to turn a [Packet] into a [SPCommand]. impl Clone for GenericCommand {
fn clone(&self) -> Self {
unsafe {
match self.tag {
CommandTag::Clear => GenericCommand {
tag: CommandTag::Clear,
data: CommandUnion {
clear: heap_clone(self.data.clear),
},
},
CommandTag::CharGrid => GenericCommand {
tag: CommandTag::CharGrid,
data: CommandUnion {
char_grid: heap_clone(self.data.char_grid),
},
},
CommandTag::Cp437Grid => GenericCommand {
tag: CommandTag::Cp437Grid,
data: CommandUnion {
cp437_grid: heap_clone(self.data.cp437_grid),
},
},
CommandTag::Bitmap => GenericCommand {
tag: CommandTag::Bitmap,
data: CommandUnion {
bitmap: heap_clone(self.data.bitmap),
},
},
CommandTag::GlobalBrightness => GenericCommand {
tag: CommandTag::GlobalBrightness,
data: CommandUnion {
global_brightness: heap_clone(
self.data.global_brightness,
),
},
},
CommandTag::BrightnessGrid => GenericCommand {
tag: CommandTag::BrightnessGrid,
data: CommandUnion {
brightness_grid: heap_clone(self.data.brightness_grid),
},
},
CommandTag::BitVec => GenericCommand {
tag: CommandTag::BitVec,
data: CommandUnion {
bit_vec: heap_clone(self.data.bit_vec),
},
},
CommandTag::HardReset => GenericCommand {
tag: CommandTag::HardReset,
data: CommandUnion {
hard_reset: heap_clone(self.data.hard_reset),
},
},
CommandTag::FadeOut => GenericCommand {
tag: CommandTag::FadeOut,
data: CommandUnion {
fade_out: heap_clone(self.data.fade_out),
},
},
#[allow(deprecated)]
CommandTag::BitmapLegacy => GenericCommand {
tag: CommandTag::BitmapLegacy,
data: CommandUnion {
bitmap_legacy: heap_clone(self.data.bitmap_legacy),
},
},
CommandTag::Invalid => GenericCommand::INVALID,
}
}
}
}
derive_free!(GenericCommand);
impl Drop for GenericCommand {
fn drop(&mut self) {
unsafe {
match self.tag {
CommandTag::Invalid => (),
CommandTag::Bitmap => heap_drop(self.data.bitmap),
CommandTag::BitVec => heap_drop(self.data.bit_vec),
CommandTag::BrightnessGrid => {
heap_drop(self.data.brightness_grid)
}
CommandTag::CharGrid => heap_drop(self.data.char_grid),
CommandTag::Cp437Grid => heap_drop(self.data.cp437_grid),
CommandTag::GlobalBrightness => {
heap_drop(self.data.global_brightness)
}
CommandTag::Clear => heap_drop(self.data.clear),
CommandTag::HardReset => heap_drop(self.data.hard_reset),
CommandTag::FadeOut => heap_drop(self.data.fade_out),
CommandTag::BitmapLegacy => heap_drop(self.data.bitmap_legacy),
}
}
*self = Self::INVALID;
}
}
wrap_functions!(associate GenericCommand;
/// Tries to turn a [Packet] into a [GenericCommand].
/// ///
/// The packet is dropped in the process. /// The packet is dropped in the process.
/// ///
/// Returns: pointer to new [SPCommand] instance or NULL if parsing failed. /// Returns: pointer to new [GenericCommand] instance or NULL if parsing failed.
fn try_from_packet( fn try_from_packet(packet: move NonNull<Packet>) -> move NonNull<GenericCommand> {
packet: NonNull<Packet>,
) -> SPCommand {
let packet = *unsafe { Box::from_raw(packet.as_ptr()) };
servicepoint::TypedCommand::try_from(packet) servicepoint::TypedCommand::try_from(packet)
.map(|value| match value { .map(|value| match value {
TypedCommand::Clear(clear) => SPCommand { TypedCommand::Clear(clear) => GenericCommand {
tag: CommandTag::Clear, tag: CommandTag::Clear,
data: CommandUnion { data: CommandUnion {
clear: heap_move_nonnull(clear), clear: heap_move_nonnull(clear),
}, },
}, },
TypedCommand::CharGrid(char_grid) => SPCommand { TypedCommand::CharGrid(char_grid) => GenericCommand {
tag: CommandTag::CharGrid, tag: CommandTag::CharGrid,
data: CommandUnion { data: CommandUnion {
char_grid: heap_move_nonnull(char_grid), char_grid: heap_move_nonnull(char_grid),
}, },
}, },
TypedCommand::Cp437Grid(cp437_grid) => SPCommand { TypedCommand::Cp437Grid(cp437_grid) => GenericCommand {
tag: CommandTag::Cp437Grid, tag: CommandTag::Cp437Grid,
data: CommandUnion { data: CommandUnion {
cp437_grid: heap_move_nonnull(cp437_grid), cp437_grid: heap_move_nonnull(cp437_grid),
}, },
}, },
TypedCommand::Bitmap(bitmap) => SPCommand { TypedCommand::Bitmap(bitmap) => GenericCommand {
tag: CommandTag::Bitmap, tag: CommandTag::Bitmap,
data: CommandUnion { data: CommandUnion {
bitmap: heap_move_nonnull(bitmap), bitmap: heap_move_nonnull(bitmap),
}, },
}, },
TypedCommand::Brightness(global_brightness) => SPCommand { TypedCommand::Brightness(global_brightness) => GenericCommand {
tag: CommandTag::GlobalBrightness, tag: CommandTag::GlobalBrightness,
data: CommandUnion { data: CommandUnion {
global_brightness: heap_move_nonnull(global_brightness), global_brightness: heap_move_nonnull(global_brightness),
}, },
}, },
TypedCommand::BrightnessGrid(brightness_grid) => SPCommand { TypedCommand::BrightnessGrid(brightness_grid) => GenericCommand {
tag: CommandTag::BrightnessGrid, tag: CommandTag::BrightnessGrid,
data: CommandUnion { data: CommandUnion {
brightness_grid: heap_move_nonnull(brightness_grid), brightness_grid: heap_move_nonnull(brightness_grid),
}, },
}, },
TypedCommand::BitVec(bitvec) => SPCommand { TypedCommand::BitVec(bitvec) => GenericCommand {
tag: CommandTag::BitVec, tag: CommandTag::BitVec,
data: CommandUnion { data: CommandUnion {
bitvec: heap_move_nonnull(bitvec), bit_vec: heap_move_nonnull(bitvec),
}, },
}, },
TypedCommand::HardReset(hard_reset) => SPCommand { TypedCommand::HardReset(hard_reset) => GenericCommand {
tag: CommandTag::HardReset, tag: CommandTag::HardReset,
data: CommandUnion { data: CommandUnion {
hard_reset: heap_move_nonnull(hard_reset), hard_reset: heap_move_nonnull(hard_reset),
}, },
}, },
TypedCommand::FadeOut(fade_out) => SPCommand { TypedCommand::FadeOut(fade_out) => GenericCommand {
tag: CommandTag::FadeOut, tag: CommandTag::FadeOut,
data: CommandUnion { data: CommandUnion {
fade_out: heap_move_nonnull(fade_out), fade_out: heap_move_nonnull(fade_out),
}, },
}, },
#[allow(deprecated)] #[allow(deprecated)]
TypedCommand::BitmapLegacy(bitmap_legacy) => SPCommand { TypedCommand::BitmapLegacy(bitmap_legacy) => GenericCommand {
tag: CommandTag::BitmapLegacy, tag: CommandTag::BitmapLegacy,
data: CommandUnion { data: CommandUnion {
bitmap_legacy: heap_move_nonnull(bitmap_legacy), bitmap_legacy: heap_move_nonnull(bitmap_legacy),
}, },
}, },
}) })
.unwrap_or_else(move |_| SPCommand { .unwrap_or_else(move |_| GenericCommand {
tag: CommandTag::Invalid, tag: CommandTag::Invalid,
data: CommandUnion { null: null_mut() }, data: CommandUnion { null: null_mut() },
}) })
} };
);
/// Clones an [SPCommand] instance. wrap_methods! { GenericCommand;
/// /// Tries to turn a [GenericCommand] into a [Packet].
/// returns: a new [SPCommand] instance. /// The [GenericCommand] gets consumed.
fn 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].
///
/// Commands with an invalid `tag` do not have to be freed as the `data` pointer should be null.
///
/// # Examples
///
/// ```C
/// SPCommand c = sp_cmd_clear_into_generic(sp_cmd_clear_new());
/// sp_command_free(c);
/// ```
fn 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. /// Returns tag [CommandTag::Invalid] in case of an error.
fn into_packet( fn try_into_packet(move command) -> val *mut Packet {
command: SPCommand,
) -> *mut Packet {
match command.tag { match command.tag {
CommandTag::Invalid => null_mut(), CommandTag::Invalid => null_mut(),
CommandTag::Bitmap => { CommandTag::Bitmap => {
heap_move_ok(unsafe { heap_remove(command.data.bitmap).try_into() }) heap_move_ok(unsafe { heap_remove(command.data.bitmap).try_into() })
} }
CommandTag::BitVec => { CommandTag::BitVec => {
heap_move_ok(unsafe { heap_remove(command.data.bitvec).try_into() }) heap_move_ok(unsafe { heap_remove(command.data.bit_vec).try_into() })
} }
CommandTag::BrightnessGrid => heap_move_ok(unsafe { CommandTag::BrightnessGrid => heap_move_ok(unsafe {
heap_remove(command.data.brightness_grid).try_into() heap_remove(command.data.brightness_grid).try_into()
@ -296,6 +289,5 @@ wrap_functions!(sp_cmd_generic;
heap_move(unsafe { heap_remove(command.data.bitmap_legacy).into() }) heap_move(unsafe { heap_remove(command.data.bitmap_legacy).into() })
} }
} }
} };
}
);

View file

@ -1,33 +1,21 @@
use crate::{ use crate::{
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions}, commands::wrap_command,
mem::{heap_move_nonnull, heap_remove}, macros::{wrap_fields, wrap_functions},
}; };
use servicepoint::{Brightness, GlobalBrightnessCommand, Packet}; use servicepoint::{Brightness, GlobalBrightnessCommand};
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_functions!(sp_cmd_brightness_global; wrap_functions!(associate GlobalBrightnessCommand;
/// Set the brightness of all tiles to the same value. /// Set the brightness of all tiles to the same value.
/// ///
/// Returns: a new [GlobalBrightnessCommand] instance. /// Returns: a new [GlobalBrightnessCommand] instance.
fn new(brightness: Brightness) -> NonNull<GlobalBrightnessCommand> { fn new(brightness: val Brightness) -> move NonNull<GlobalBrightnessCommand> {
heap_move_nonnull(GlobalBrightnessCommand::from(brightness)) GlobalBrightnessCommand::from(brightness)
}
/// Turns the command into a packet
fn into_packet(command: NonNull<GlobalBrightnessCommand>) -> NonNull<Packet> {
heap_move_nonnull(unsafe { heap_remove(command) }.into())
}
);
wrap_clone!(sp_cmd_brightness_global::GlobalBrightnessCommand);
wrap_free!(sp_cmd_brightness_global::GlobalBrightnessCommand);
wrap_fields!(
sp_cmd_brightness_global::GlobalBrightnessCommand;
prop brightness: Brightness {
get();
set(value);
}; };
); );
wrap_command!(GlobalBrightness);
wrap_fields!(GlobalBrightnessCommand;
prop brightness: Brightness { get; set; };
);

View file

@ -15,33 +15,76 @@ pub use cp437_grid_command::*;
pub use generic_command::*; pub use generic_command::*;
macro_rules! wrap_origin_accessors { macro_rules! wrap_origin_accessors {
( $prefix:ident :: $object_type:ty ) => { ( $object_type:ident ) => {
$crate::macros::wrap_functions!($prefix; ::paste::paste! {
#[doc = concat!(" Reads the origin field of the [`", stringify!($object_type), "`].")] $crate::macros::wrap_methods!($object_type;
fn get_origin( #[doc = " Reads the origin field of the [`" $object_type "`]."]
command: NonNull<$object_type>, fn get_origin(
origin_x: NonNull<usize>, ref command,
origin_y: NonNull<usize>, origin_x: mut ::core::ptr::NonNull<usize>,
) { origin_y: mut ::core::ptr::NonNull<usize>
unsafe { ) {
let origin = &command.as_ref().origin; let origin = command.origin;
*origin_x.as_ptr() = origin.x; *origin_x = origin.x;
*origin_y.as_ptr() = origin.y; *origin_y = origin.y;
} };
}
#[doc = concat!(" Overwrites the origin field of the [`", stringify!($object_type), "`].")] #[doc = " Overwrites the origin field of the [`" $object_type "`]."]
fn set_origin( fn set_origin(mut command, origin_x: val usize, origin_y: val usize) {
command: NonNull<$object_type>, command.origin = ::servicepoint::Origin::new(origin_x, origin_y);
origin_x: usize, };
origin_y: usize, );
) { }
unsafe {
$crate::macros::nonnull_as_mut!(command).origin = ::servicepoint::Origin::new(origin_x, origin_y);
}
}
);
}; };
} }
pub(crate) use wrap_origin_accessors; macro_rules! derive_command_from {
($command:ident) => {
::paste::paste! {
impl From<::servicepoint::[< $command Command >]> for $crate::commands::GenericCommand {
fn from(command: ::servicepoint::[< $command Command >]) -> Self {
Self {
tag: $crate::commands::CommandTag::$command,
data: $crate::commands::CommandUnion {
[< $command:snake >]: $crate::mem::heap_move_nonnull(command)
},
}
}
}
}
};
}
macro_rules! derive_command_into_packet {
($command_type:ident) => {
::paste::paste! {
$crate::macros::wrap_method!($command_type;
#[doc = "Tries to turn a [`" $command_type "`] into a [Packet]."]
///
/// Returns: NULL or a [Packet] containing the command.
fn try_into_packet(move instance) -> move_ok *mut ::servicepoint::Packet {
instance.try_into()
};
);
}
}
}
macro_rules! wrap_command {
($command:ident, $object_type:ident) => {
$crate::macros::derive_clone!($object_type);
$crate::macros::derive_free!($object_type);
$crate::commands::derive_command_from!($command);
$crate::commands::derive_command_into_packet!($object_type);
};
($command:ident) => {
::paste::paste! {
$crate::commands::wrap_command!($command, [< $command Command >]);
}
};
}
pub(crate) use {
derive_command_from, derive_command_into_packet, wrap_command,
wrap_origin_accessors,
};

View file

@ -1,7 +1,6 @@
use crate::{ use crate::{
containers::ByteSlice, containers::{wrap_grid, ByteSlice},
macros::{wrap_clone, wrap_free, wrap_functions, wrap_methods}, macros::{wrap_functions, wrap_methods},
mem::{heap_move_nonnull, heap_move_ok, heap_move_some, heap_remove},
}; };
use servicepoint::{ use servicepoint::{
Bitmap, BitmapCommand, CompressionCode, DataRef, DisplayBitVec, Grid, Bitmap, BitmapCommand, CompressionCode, DataRef, DisplayBitVec, Grid,
@ -9,11 +8,9 @@ use servicepoint::{
}; };
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_clone!(sp_bitmap::Bitmap); wrap_grid!(Bitmap, bool);
wrap_free!(sp_bitmap::Bitmap);
wrap_functions!(sp_bitmap;
wrap_functions!(associate Bitmap;
/// Creates a new [Bitmap] with the specified dimensions. /// Creates a new [Bitmap] with the specified dimensions.
/// ///
/// # Arguments /// # Arguments
@ -37,16 +34,16 @@ wrap_functions!(sp_bitmap;
/// sp_bitmap_set(grid, 0, 0, false); /// sp_bitmap_set(grid, 0, 0, false);
/// sp_bitmap_free(grid); /// sp_bitmap_free(grid);
/// ``` /// ```
fn new(width: usize, height: usize) -> *mut Bitmap { fn new(width: val usize, height: val usize) -> move_some *mut Bitmap {
heap_move_some(Bitmap::new(width, height)) Bitmap::new(width, height)
} };
/// Creates a new [Bitmap] with a size matching the screen. /// Creates a new [Bitmap] with a size matching the screen.
/// ///
/// returns: [Bitmap] initialized to all pixels off. /// returns: [Bitmap] initialized to all pixels off.
fn new_max_sized() -> NonNull<Bitmap> { fn new_max_sized() -> move NonNull<Bitmap> {
heap_move_nonnull(Bitmap::max_sized()) Bitmap::max_sized()
} };
/// Loads a [Bitmap] with the specified dimensions from the provided data. /// Loads a [Bitmap] with the specified dimensions from the provided data.
/// ///
@ -57,13 +54,12 @@ wrap_functions!(sp_bitmap;
/// ///
/// returns: [Bitmap] that contains a copy of the provided data, or NULL in case of an error. /// returns: [Bitmap] that contains a copy of the provided data, or NULL in case of an error.
fn load( fn load(
width: usize, width: val usize,
height: usize, height: val usize,
data: ByteSlice, data: slice ByteSlice,
) -> *mut Bitmap { ) -> move_ok *mut Bitmap {
let data = unsafe { data.as_slice() }; Bitmap::load(width, height, data)
heap_move_ok(Bitmap::load(width, height, data)) };
}
/// Tries to convert the BitVec to a Bitmap. /// Tries to convert the BitVec to a Bitmap.
/// ///
@ -71,84 +67,34 @@ wrap_functions!(sp_bitmap;
/// ///
/// Returns NULL in case of error. /// Returns NULL in case of error.
fn from_bitvec( fn from_bitvec(
width: usize, width: val usize,
bitvec: NonNull<DisplayBitVec>, bitvec: move NonNull<DisplayBitVec>,
) -> *mut Bitmap { ) -> move_ok *mut Bitmap {
let bitvec = unsafe { heap_remove(bitvec) }; Bitmap::from_bitvec(width, bitvec)
heap_move_ok(Bitmap::from_bitvec(width, bitvec)) };
} );
wrap_methods!(Bitmap;
/// Consumes the Bitmap and returns the contained BitVec. /// Consumes the Bitmap and returns the contained BitVec.
fn into_bitvec( fn into_bitvec(move bitmap) -> move NonNull<DisplayBitVec> {
bitmap: NonNull<Bitmap> bitmap.into()
) -> NonNull<DisplayBitVec> { };
let bitmap = unsafe { heap_remove(bitmap) };
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].
/// ///
/// The provided [Bitmap] gets consumed. /// The provided [Bitmap] gets consumed.
/// ///
/// Returns NULL in case of an error. /// Returns NULL in case of an error.
fn into_packet( fn try_into_packet(move bitmap, x: val usize, y: val usize, compression: val CompressionCode) -> move_ok *mut Packet {
bitmap: NonNull<Bitmap>, Packet::try_from(BitmapCommand {
x: usize,
y: usize,
compression: CompressionCode,
) -> *mut Packet {
let bitmap = unsafe { heap_remove(bitmap) };
heap_move_ok(Packet::try_from(BitmapCommand {
bitmap, bitmap,
origin: Origin::new(x, y), origin: Origin::new(x, y),
compression, compression,
})) })
} };
);
wrap_methods!(
sp_bitmap::Bitmap;
/// 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) -> bool;
/// Sets the value of the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
mut fn set(x: usize, y: usize, value: bool);
/// Sets the state of all pixels in the [Bitmap].
///
/// # Arguments
///
/// - `value`: the value to set all pixels to
mut fn fill(value: bool);
/// Gets the width in pixels.
ref fn width() -> usize;
/// Gets the height in pixels.
ref fn height() -> usize;
/// Gets an unsafe reference to the data of the [Bitmap] instance. /// Gets an unsafe reference to the data of the [Bitmap] instance.
/// ///
/// The returned memory is valid for the lifetime of the bitmap. /// The returned memory is valid for the lifetime of the bitmap.
mut fn data_ref_mut() -> ByteSlice { fn data_ref_mut(mut instance) -> slice ByteSlice;
return(slice) { unsafe { ByteSlice::from_slice(slice) } };
};
); );

View file

@ -1,15 +1,15 @@
use crate::{ use crate::{
containers::ByteSlice, containers::{wrap_container, ByteSlice},
macros::{wrap_clone, wrap_free, wrap_functions, wrap_methods}, macros::{wrap_functions, wrap_methods},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
}; };
use servicepoint::{ use servicepoint::{
BinaryOperation, BitVecCommand, CompressionCode, DisplayBitVec, Packet, BinaryOperation, BitVecCommand, CompressionCode, DisplayBitVec, Packet,
}; };
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_functions!(sp_bitvec; wrap_container!(DisplayBitVec);
wrap_functions!(associate DisplayBitVec;
/// Creates a new [DisplayBitVec] instance. /// Creates a new [DisplayBitVec] instance.
/// ///
/// # Arguments /// # Arguments
@ -21,45 +21,37 @@ wrap_functions!(sp_bitvec;
/// # Panics /// # Panics
/// ///
/// - when `size` is not divisible by 8. /// - when `size` is not divisible by 8.
fn new(size: usize) -> NonNull<DisplayBitVec> { fn new(size: val usize) -> move NonNull<DisplayBitVec> {
heap_move_nonnull(DisplayBitVec::repeat(false, size)) DisplayBitVec::repeat(false, size)
} };
/// Interpret the data as a series of bits and load then into a new [DisplayBitVec] instance. /// Interpret the data as a series of bits and load then into a new [DisplayBitVec] instance.
/// ///
/// returns: [DisplayBitVec] instance containing data. /// returns: [DisplayBitVec] instance containing data.
fn load(data: ByteSlice) -> NonNull<DisplayBitVec> { fn load(data: slice ByteSlice) -> move NonNull<DisplayBitVec> {
let data = unsafe { data.as_slice() }; DisplayBitVec::from_slice(data)
heap_move_nonnull(DisplayBitVec::from_slice(data)) };
} );
wrap_methods!(DisplayBitVec;
/// Creates a [BitVecCommand] and immediately turns that into a [Packet]. /// Creates a [BitVecCommand] and immediately turns that into a [Packet].
/// ///
/// The provided [DisplayBitVec] gets consumed. /// The provided [DisplayBitVec] gets consumed.
/// ///
/// Returns NULL in case of an error. /// Returns NULL in case of an error.
fn into_packet( fn try_into_packet(
bitvec: NonNull<DisplayBitVec>, move bitvec,
offset: usize, offset: val usize,
operation: BinaryOperation, operation: val BinaryOperation,
compression: CompressionCode, compression: val CompressionCode
) -> *mut Packet { ) -> move_ok *mut Packet {
let bitvec = unsafe { heap_remove(bitvec) }; Packet::try_from(BitVecCommand {
heap_move_ok(Packet::try_from(BitVecCommand {
bitvec, bitvec,
offset, offset,
operation, operation,
compression, compression,
})) })
} };
);
wrap_clone!(sp_bitvec::DisplayBitVec);
wrap_free!(sp_bitvec::DisplayBitVec);
wrap_methods!(
sp_bitvec::DisplayBitVec;
/// Gets the value of a bit. /// Gets the value of a bit.
/// ///
@ -73,11 +65,10 @@ wrap_methods!(
/// # Panics /// # Panics
/// ///
/// - when accessing `index` out of bounds /// - when accessing `index` out of bounds
ref fn get(index: usize) -> bool { fn get(ref instance, index: val usize) -> val bool {
return(result) { result.map(|x| *x).unwrap_or(false) }; instance.get(index).map(|x| *x).unwrap_or(false)
}; };
/// Sets the value of a bit. /// Sets the value of a bit.
/// ///
/// # Arguments /// # Arguments
@ -88,25 +79,23 @@ wrap_methods!(
/// # Panics /// # Panics
/// ///
/// - when accessing `index` out of bounds /// - when accessing `index` out of bounds
mut fn set(index: usize, value: bool); fn set(mut instance, index: val usize, value: val bool);
/// Sets the value of all bits. /// Sets the value of all bits.
/// ///
/// # Arguments /// # Arguments
/// ///
/// - `value`: the value to set all bits to /// - `value`: the value to set all bits to
mut fn fill(value: bool); fn fill(mut instance, value: val bool);
/// Gets the length in bits. /// Gets the length in bits.
ref fn len() -> usize; fn len(ref instance) -> val usize;
/// Returns true if length is 0. /// Returns true if length is 0.
ref fn is_empty() -> bool; fn is_empty(ref instance) -> val bool;
/// Gets an unsafe reference to the data of the [DisplayBitVec] instance. /// Gets an unsafe reference to the data of the [DisplayBitVec] instance.
/// ///
/// The returned memory is valid for the lifetime of the bitvec. /// The returned memory is valid for the lifetime of the bitvec.
mut fn as_raw_mut_slice() -> ByteSlice { fn as_raw_mut_slice(mut instance) -> slice ByteSlice;
return(slice) { unsafe { ByteSlice::from_slice(slice) } };
};
); );

View file

@ -1,8 +1,6 @@
use crate::macros::wrap_functions;
use crate::{ use crate::{
containers::ByteSlice, containers::{wrap_grid, ByteSlice},
macros::{wrap_clone, wrap_free, wrap_methods}, macros::{wrap_functions, wrap_methods},
mem::{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,
@ -10,8 +8,9 @@ use servicepoint::{
}; };
use std::{mem::transmute, ptr::NonNull}; use std::{mem::transmute, ptr::NonNull};
wrap_functions!(sp_brightness_grid; wrap_grid!(BrightnessGrid, Brightness);
wrap_functions!(associate BrightnessGrid;
/// Creates a new [BrightnessGrid] with the specified dimensions. /// Creates a new [BrightnessGrid] with the specified dimensions.
/// ///
/// returns: [BrightnessGrid] initialized to 0. /// returns: [BrightnessGrid] initialized to 0.
@ -29,12 +28,9 @@ wrap_functions!(sp_brightness_grid;
/// TypedCommand *command = sp_command_char_brightness(grid); /// TypedCommand *command = sp_command_char_brightness(grid);
/// sp_udp_free(connection); /// sp_udp_free(connection);
/// ``` /// ```
fn new( fn new(width: val usize, height: val usize) -> move NonNull<BrightnessGrid> {
width: usize, BrightnessGrid::new(width, height)
height: usize, };
) -> NonNull<BrightnessGrid> {
heap_move_nonnull(BrightnessGrid::new(width, height))
}
/// Loads a [BrightnessGrid] with the specified dimensions from the provided data. /// Loads a [BrightnessGrid] with the specified dimensions from the provided data.
/// ///
@ -42,90 +38,38 @@ wrap_functions!(sp_brightness_grid;
/// ///
/// returns: new [BrightnessGrid] instance, or NULL in case of an error. /// returns: new [BrightnessGrid] instance, or NULL in case of an error.
fn load( fn load(
width: usize, width: val usize,
height: usize, height: val usize,
data: ByteSlice, data: slice ByteSlice,
) -> *mut BrightnessGrid { ) -> move_some *mut BrightnessGrid {
let data = unsafe { data.as_slice() }; ByteGrid::load(width, height, data)
heap_move_some( .map(move |grid| grid.map(Brightness::saturating_from))
ByteGrid::load(width, height, data) };
.map(move |grid| grid.map(Brightness::saturating_from)), );
)
}
wrap_methods!(BrightnessGrid;
/// Creates a [BrightnessGridCommand] and immediately turns that into a [Packet]. /// Creates a [BrightnessGridCommand] and immediately turns that into a [Packet].
/// ///
/// The provided [BrightnessGrid] gets consumed. /// The provided [BrightnessGrid] gets consumed.
/// ///
/// Returns NULL in case of an error. /// Returns NULL in case of an error.
fn into_packet( fn try_into_packet(move grid, x: val usize, y: val usize) -> move_ok *mut Packet {
grid: NonNull<BrightnessGrid>, Packet::try_from(BrightnessGridCommand {
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
heap_move_ok(Packet::try_from(BrightnessGridCommand {
grid, grid,
origin: Origin::new(x, y), origin: Origin::new(x, y),
})) })
} };
);
wrap_clone!(sp_brightness_grid::BrightnessGrid);
wrap_free!(sp_brightness_grid::BrightnessGrid);
wrap_methods!(
sp_brightness_grid::BrightnessGrid;
/// Gets the current value at the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell to read
///
/// returns: value at position
///
/// # Panics
/// - When accessing `x` or `y` out of bounds.
ref fn get(x: usize, y: usize) -> Brightness;
/// Sets the value of 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: Brightness);
/// Sets the value of all cells.
///
/// # Arguments
///
/// - `value`: the value to set all cells to
mut fn fill(value: Brightness);
/// 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 instance. /// Gets an unsafe reference to the data of the instance.
/// ///
/// The returned memory is valid for the lifetime of the grid. /// The returned memory is valid for the lifetime of the grid.
mut fn data_ref_mut() -> ByteSlice { fn data_ref_mut(mut instance) -> slice ByteSlice {
return(br_slice) { unsafe { //noinspection RsAssertEqual
//noinspection RsAssertEqual const _: () = assert!(size_of::<Brightness>() == 1);
const _: () = assert!(size_of::<Brightness>() == 1);
ByteSlice::from_slice(transmute::<&mut [Brightness], &mut [u8]>(br_slice)) let br_slice = instance.data_ref_mut();
}}; unsafe {
transmute::<&mut [Brightness], &mut [u8]>(br_slice)
}
}; };
); );

View file

@ -26,15 +26,21 @@ pub struct ByteSlice {
} }
impl ByteSlice { impl ByteSlice {
pub(crate) const INVALID: ByteSlice = ByteSlice { /// Represents an invalid [ByteSlice] instance.
pub const INVALID: ByteSlice = ByteSlice {
start: std::ptr::null_mut(), start: std::ptr::null_mut(),
length: 0, length: 0,
}; };
pub(crate) unsafe fn as_slice(&self) -> &[u8] { pub(crate) unsafe fn as_slice(&self) -> &[u8] {
assert!(!self.start.is_null());
unsafe { std::slice::from_raw_parts(self.start, self.length) } unsafe { std::slice::from_raw_parts(self.start, self.length) }
} }
#[allow(
clippy::mut_from_ref,
reason = "This is used to get a pointer from the C side."
)]
pub(crate) unsafe fn as_slice_mut(&self) -> &mut [u8] { pub(crate) unsafe fn as_slice_mut(&self) -> &mut [u8] {
unsafe { std::slice::from_raw_parts_mut(self.start, self.length) } unsafe { std::slice::from_raw_parts_mut(self.start, self.length) }
} }

View file

@ -1,13 +1,14 @@
use crate::{ use crate::{
containers::ByteSlice, containers::{derive_get_width_height, wrap_container, ByteSlice},
macros::{wrap_clone, wrap_free, wrap_functions, wrap_methods}, macros::{wrap_functions, wrap_methods},
mem::{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;
wrap_functions!(sp_char_grid; wrap_container!(CharGrid);
derive_get_width_height!(CharGrid);
wrap_functions!(associate CharGrid;
/// Creates a new [CharGrid] with the specified dimensions. /// Creates a new [CharGrid] with the specified dimensions.
/// ///
/// returns: [CharGrid] initialized to 0. /// returns: [CharGrid] initialized to 0.
@ -20,49 +21,19 @@ wrap_functions!(sp_char_grid;
/// sp_char_grid_set(grid, 0, 0, '!'); /// sp_char_grid_set(grid, 0, 0, '!');
/// sp_char_grid_free(grid); /// sp_char_grid_free(grid);
/// ``` /// ```
fn new( fn new(width: val usize, height: val usize) -> move NonNull<CharGrid> {
width: usize, CharGrid::new(width, height)
height: usize, };
) -> NonNull<CharGrid> {
heap_move_nonnull(CharGrid::new(width, height))
}
/// Loads a [CharGrid] with the specified dimensions from the provided data. /// Loads a [CharGrid] with the specified dimensions from the provided data.
/// ///
/// returns: new CharGrid or NULL in case of an error /// returns: new CharGrid or NULL in case of an error
fn load( fn load(width: val usize, height: val usize, data: slice ByteSlice) -> move_ok *mut CharGrid {
width: usize, CharGrid::load_utf8(width, height, data.to_vec())
height: usize, };
data: ByteSlice,
) -> *mut CharGrid {
let data = unsafe { data.as_slice() };
heap_move_ok(CharGrid::load_utf8(width, height, data.to_vec()))
}
/// Creates a [CharGridCommand] and immediately turns that into a [Packet].
///
/// The provided [CharGrid] gets consumed.
///
/// Returns NULL in case of an error.
fn into_packet(
grid: NonNull<CharGrid>,
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
heap_move_ok(Packet::try_from(CharGridCommand {
grid,
origin: Origin::new(x, y),
}))
}
); );
wrap_clone!(sp_char_grid::CharGrid); wrap_methods!(CharGrid;
wrap_free!(sp_char_grid::CharGrid);
wrap_methods!(
sp_char_grid::CharGrid;
/// Returns the current value at the specified position. /// Returns the current value at the specified position.
/// ///
@ -73,8 +44,8 @@ wrap_methods!(
/// # Panics /// # Panics
/// ///
/// - when accessing `x` or `y` out of bounds /// - when accessing `x` or `y` out of bounds
ref fn get(x: usize, y: usize) -> u32 { fn get(ref instance, x: val usize, y: val usize) -> val u32 {
return(char) { char as u32 }; instance.get(x, y) as u32
}; };
/// Sets the value of the specified position in the grid. /// Sets the value of the specified position in the grid.
@ -90,8 +61,8 @@ wrap_methods!(
/// ///
/// - when accessing `x` or `y` out of bounds /// - when accessing `x` or `y` out of bounds
/// - when providing values that cannot be converted to Rust's `char`. /// - when providing values that cannot be converted to Rust's `char`.
mut fn set(x: usize, y: usize, value: u32) { fn set(mut instance, x: val usize, y: val usize, value: val u32) {
prepare(value) { char::from_u32(value).unwrap() }; instance.set(x, y, char::from_u32(value).unwrap())
}; };
/// Sets the value of all cells in the grid. /// Sets the value of all cells in the grid.
@ -100,13 +71,19 @@ wrap_methods!(
/// ///
/// - `value`: the value to set all cells to /// - `value`: the value to set all cells to
/// - when providing values that cannot be converted to Rust's `char`. /// - when providing values that cannot be converted to Rust's `char`.
mut fn fill(value: u32) { fn fill(mut instance, value: val u32) {
prepare(value) { char::from_u32(value).unwrap() }; instance.fill(char::from_u32(value).unwrap())
}; };
/// Gets the width of the grid. /// Creates a [CharGridCommand] and immediately turns that into a [Packet].
ref fn width() -> usize; ///
/// The provided [CharGrid] gets consumed.
/// Gets the height of the grid. ///
ref fn height() -> usize; /// Returns NULL in case of an error.
fn try_into_packet(move grid, x: val usize, y: val usize) -> move_ok *mut Packet {
Packet::try_from(CharGridCommand {
grid,
origin: Origin::new(x, y),
})
};
); );

View file

@ -1,103 +1,43 @@
use crate::macros::wrap_functions;
use crate::{ use crate::{
containers::ByteSlice, containers::{wrap_grid, ByteSlice},
macros::{wrap_clone, wrap_free, wrap_methods}, macros::{wrap_functions, wrap_methods},
mem::{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,
}; };
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_functions!(sp_cp437_grid; wrap_grid!(Cp437Grid, u8);
wrap_functions!(associate Cp437Grid;
/// Creates a new [Cp437Grid] with the specified dimensions. /// Creates a new [Cp437Grid] with the specified dimensions.
/// ///
/// returns: [Cp437Grid] initialized to 0. /// returns: [Cp437Grid] initialized to 0.
fn new( fn new(width: val usize, height: val usize) -> move NonNull<Cp437Grid> {
width: usize, Cp437Grid::new(width, height)
height: usize, };
) -> NonNull<Cp437Grid> {
heap_move_nonnull(Cp437Grid::new(width, height))
}
/// Loads a [Cp437Grid] with the specified dimensions from the provided data. /// Loads a [Cp437Grid] with the specified dimensions from the provided data.
fn load( fn load(width: val usize, height: val usize, data: slice ByteSlice) -> move_some *mut Cp437Grid {
width: usize, Cp437Grid::load(width, height, data)
height: usize, };
data: ByteSlice, );
) -> *mut Cp437Grid {
let data = unsafe { data.as_slice() };
heap_move_some(Cp437Grid::load(width, height, data))
}
wrap_methods!(Cp437Grid;
/// Creates a [Cp437GridCommand] and immediately turns that into a [Packet]. /// Creates a [Cp437GridCommand] and immediately turns that into a [Packet].
/// ///
/// The provided [Cp437Grid] gets consumed. /// The provided [Cp437Grid] gets consumed.
/// ///
/// Returns NULL in case of an error. /// Returns NULL in case of an error.
fn into_packet( fn try_into_packet(move grid, x: val usize, y: val usize) -> move_ok *mut Packet {
grid: NonNull<Cp437Grid>, Packet::try_from(Cp437GridCommand {
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
heap_move_ok(Packet::try_from(Cp437GridCommand {
grid, grid,
origin: Origin::new(x, y), 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. /// Gets an unsafe reference to the data of the grid.
/// ///
/// The returned memory is valid for the lifetime of the instance. /// The returned memory is valid for the lifetime of the instance.
mut fn data_ref_mut() -> ByteSlice { fn data_ref_mut(mut instance) -> slice ByteSlice;
return(slice) { unsafe { ByteSlice::from_slice(slice) } };
};
); );

View file

@ -11,3 +11,68 @@ pub use brightness_grid::*;
pub use byte_slice::*; pub use byte_slice::*;
pub use char_grid::*; pub use char_grid::*;
pub use cp437_grid::*; pub use cp437_grid::*;
macro_rules! wrap_container {
($object_type:ident) => {
$crate::macros::derive_clone!($object_type);
$crate::macros::derive_free!($object_type);
};
}
macro_rules! derive_get_width_height {
($object_type:ident) => {
$crate::macros::wrap_methods! {$object_type;
/// Gets the width.
fn width(ref instance) -> val usize;
/// Gets the height.
fn height(ref instance) -> val usize;
}
};
}
macro_rules! wrap_grid {
($object_type:ident, $value_type:ident) => {
$crate::containers::wrap_container!($object_type);
$crate::containers::derive_get_width_height!($object_type);
$crate::macros::wrap_methods! {$object_type;
/// 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
fn get(ref instance, x: val usize, y: val usize) -> val $value_type;
/// Sets the value of the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
fn set(mut instance, x: val usize, y: val usize, value: val $value_type);
/// Sets the state of all cells in the grid.
///
/// # Arguments
///
/// - `value`: the value to set all cells to
fn fill(mut instance, value: val $value_type);
}
};
}
pub(crate) use {derive_get_width_height, wrap_container, wrap_grid};
mod _hidden {
/// This is a type only used by cbindgen to have a type for pointers.
#[allow(unused)]
pub struct DisplayBitVec;
}

View file

@ -2,8 +2,6 @@
//! //!
//! # Examples //! # Examples
//! //!
//! Make sure to check out [this GitHub repo](https://github.com/arfst23/ServicePoint) as well!
//!
//! ```C //! ```C
//! #include <stdio.h> //! #include <stdio.h>
//! #include "servicepoint.h" //! #include "servicepoint.h"
@ -24,36 +22,32 @@
//! return 0; //! return 0;
//! } //! }
//! ``` //! ```
//!
//! There are more examples in the source repository.
/// Functions related to commands. /// Functions related to commands.
pub mod commands; pub mod commands;
/// Functions related to [servicepoint::Bitmap], [servicepoint::CharGrid] and friends. /// Functions related to [servicepoint::Bitmap], [servicepoint::CharGrid] and friends.
pub mod containers; pub mod containers;
mod macros; pub(crate) mod macros;
pub(crate) mod mem; pub(crate) mod mem;
/// Functions related to [Packet]. /// Functions related to [servicepoint::Packet].
pub mod packet; pub mod packet;
/// Functions related to [UdpSocket]. /// Functions related to [servicepoint::UdpSocketExt].
pub mod udp; pub mod udp;
/// 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 = 30; pub const SP_FRAME_PACING_MS: u128 = 30;
/// This is a type only used by cbindgen to have a type for pointers.
pub struct UdpSocket;
/// This is a type only used by cbindgen to have a type for pointers.
pub struct DisplayBitVec;
#[cfg(feature = "env_logger")] #[cfg(feature = "env_logger")]
mod feature_env_logger { mod feature_env_logger {
use crate::macros::wrap_functions; use crate::macros::wrap_functions;
wrap_functions!(sp_envlogger; wrap_functions!(envlogger;
/// Call this function at the beginning of main to enable rust logging controlled by the /// Call this function at the beginning of main to enable rust logging controlled by the
/// `RUST_LOG` environment variable. See [env_logger](https://docs.rs/env_logger/latest/env_logger/). /// `RUST_LOG` environment variable. See [env_logger](https://docs.rs/env_logger/latest/env_logger/).
fn init() { fn init() {
env_logger::init(); env_logger::init();
} };
); );
} }

View file

@ -1,239 +1,270 @@
macro_rules! wrap_free { macro_rules! derive_free {
($prefix:ident :: $typ:ty) => { ($typ:ident) => {
$crate::macros::wrap_functions!($prefix; ::paste::paste! {
#[doc = concat!("Deallocates a [`", stringify!($typ), "`] instance.")] $crate::macros::wrap_method!($typ;
fn free(instance: NonNull<$typ>) { #[doc = "Deallocates a [`" $typ "`] instance."]
unsafe { $crate::mem::heap_drop(instance) } #[allow(dropping_copy_types)]
} fn free(move instance) {
); ::std::mem::drop(instance)
};
);
}
}; };
} }
macro_rules! wrap_clone { macro_rules! derive_clone {
($prefix:ident :: $typ:ty) => { ($object_type:ident) => {
$crate::macros::wrap_functions!($prefix; ::paste::paste! {
#[doc = concat!("Clones a [`", stringify!($typ), "`] instance.")] $crate::macros::wrap_method!($object_type;
fn clone(instance: NonNull<$typ>) -> NonNull<$typ> { #[doc = "Clones a [`" $object_type "`] instance."]
unsafe { $crate::mem::heap_clone(instance) } fn clone(ref instance) -> move ::core::ptr::NonNull<$object_type> {
} instance.clone()
); };
);
}
}; };
} }
macro_rules! nonnull_as_ref { macro_rules! wrap_method {
($ident:ident) => { (
$ident.as_ref() $object_type:ident;
$(#[$meta:meta])+
fn $function:ident($ref_or_mut:ident $instance:ident $(, $($param_name:ident: $param_modifier:ident $param_type:ty),*)?)
$(-> $return_modifier:ident $return_type:ty)?;
) => {
::paste::paste!{
$crate::macros::wrap_method!(
$object_type;
$(#[$meta])+
fn $function($ref_or_mut $instance $(, $($param_name: $param_modifier $param_type),*)?)
$(-> $return_modifier $return_type)? {
$instance.$function($($($param_name),*)?)
};
);
}
};
($object_type:ident;
$(#[$meta:meta])+
fn $function:ident($ref_or_mut:ident $instance:ident $(, $($param_name:ident: $param_modifier:ident $param_type:ty),*)?)
$(-> $return_modifier:ident $return_type:ty)?
$impl:block;
) => {
paste::paste! {
$crate::macros::wrap_functions!([< $object_type:lower >];
#[doc = " Calls method [`servicepoint::" $object_type "::" $function "`]."]
///
$(#[$meta])*
fn $function(
$instance: $ref_or_mut ::core::ptr::NonNull<$object_type>
$(,$($param_name: $param_modifier $param_type),*)?
) $(-> $return_modifier $return_type)?
$impl;
);
}
}; };
} }
macro_rules! nonnull_as_mut {
($ident:ident) => {
(&mut *$ident.as_ptr())
};
}
// meta required on purpose, because otherwise the added documentation would suppress warnings
macro_rules! wrap_methods { macro_rules! wrap_methods {
( (
$prefix:ident :: $object_type:ty; $object_type:ident;
$( $(
$(#[$meta:meta])+ $(#[$meta:meta])+
$ref_or_mut:ident fn $function:ident($($param_name:ident: $param_type:ty),*) fn $function:ident($ref_or_mut:ident $instance:ident $(, $($param_name:ident: $param_modifier:ident $param_type:ty),*)?)
$(-> $return_type:ty)? $(-> $return_modifier:ident $return_type:ty)?
$({ $($impl:block)?;
$($(prepare($param_let_name:ident) $param_let_expr:block);+;)?
$(return($it:ident) $return_expr:block;)?
})?
;
)+ )+
) => { ) => {
paste::paste! { paste::paste! {
$crate::macros::wrap_functions!($prefix; $(
$( $crate::macros::wrap_method!($object_type;
#[doc = concat!(" Calls [`servicepoint::", stringify!($object_type),
"::", stringify!($function), "`].")]
#[doc = ""]
$(#[$meta])* $(#[$meta])*
fn $function( fn $function($ref_or_mut $instance $(, $($param_name: $param_modifier $param_type),*)?)
instance: NonNull<$object_type>, $(-> $return_modifier $return_type)?
$($param_name: $param_type),* $($impl)?;
) $(-> $return_type)? {
let instance = unsafe { $crate::macros:: [< nonnull_as_ $ref_or_mut >] !(instance) };
$($(
$(let $param_let_name = $param_let_expr;)*
)?)?
#[allow(
unused_variables,
reason = "This variable may not be used depending on macro variables" )]
let result = instance.$function($($param_name),*);
$(
$(
let $it = result;
let result = $return_expr;
)?
)?
return result;
}
)+
); );
)+
}
};
}
macro_rules! wrap_fields_accessor {
(get; $object_type:ident :: $prop_name:ident : $prop_type:ty) => {
paste::paste! {
$crate::macros::wrap_method! {$object_type;
#[doc = " Gets the value of field `" $prop_name
"` of the [`servicepoint::" $object_type "`]."]
fn [<get _ $prop_name>](ref instance) -> val $prop_type {
instance.$prop_name
};
}
}
};
(mut get; $object_type:ident :: $prop_name:ident : $prop_type:ty) => {
paste::paste! {
$crate::macros::wrap_method! {$object_type;
#[doc = " Gets a reference to the field `" $prop_name
"` of the [`servicepoint::" $object_type "`]."]
///
/// - The returned reference inherits the lifetime of object 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.
fn [<get _ $prop_name _mut>](mut instance) -> val ::core::ptr::NonNull<$prop_type> {
::core::ptr::NonNull::from(&mut instance.$prop_name)
};
}
}
};
(set; $object_type:ident :: $prop_name:ident : $prop_type:ty) => {
paste::paste! {
$crate::macros::wrap_method! {$object_type;
#[doc = " Sets the value of field `" $prop_name
"` of the [`servicepoint::" $object_type "`]."]
fn [<set _ $prop_name>](mut instance, value: val $prop_type) {
instance.$prop_name = value;
};
}
}
};
(move set; $object_type:ident :: $prop_name:ident : $prop_type:ty) => {
paste::paste! {
$crate::macros::wrap_method! {$object_type;
#[doc = " Sets the value of field `" $prop_name
"` of the [`servicepoint::" $object_type "`]."]
/// The provided value is moved into the instance, potentially invalidating previously taken references.
fn [<set _ $prop_name>](mut instance, value: move ::core::ptr::NonNull<$prop_type>) {
instance.$prop_name = value;
};
}
} }
}; };
} }
macro_rules! wrap_fields { macro_rules! wrap_fields {
( (
$prefix:ident :: $object_type:ty; $object_type:ident;
$( $(
prop $prop_name:ident : $prop_type:ty { prop $prop_name:ident : $prop_type:ty { $($accessor:ident $($modifier:ident)?;)+ };
$(
get() $({
$(#[$get_meta:meta])*
$(return $get_expr:expr;)?
})?;
)?
$(
mut get() $({
$(#[$get_mut_meta:meta])*
$(return $get_mut_expr:expr;)?
})?;
)?
$(
set($value:ident)
$({
$(#[$set_meta:meta])*
$(return $set_expr:expr;)?
})?;
)?
$(
move set( $set_move_value:ident)
$({
$(#[$set_move_meta:meta])*
$(return $set_move_expr:expr;)?
})?;
)?
};
)+ )+
) => { ) => {
paste::paste! { $($(
$crate::macros::wrap_functions!($prefix; ::paste::paste!{
$( $crate::macros::wrap_fields_accessor! {
$( $($modifier)? $accessor;
#[doc = concat!(" Gets the value of field `", stringify!($prop_name), $object_type :: $prop_name: $prop_type
"` of the [`servicepoint::", stringify!($object_type),"`].")] }
$($( }
#[doc = ""] )+)+
#[$get_meta] };
)*)? }
fn [<get _ $prop_name>](
instance: ::core::ptr::NonNull<$object_type>
) -> $prop_type {
let $prop_name = unsafe { $crate::macros::nonnull_as_ref!(instance).$prop_name };
$($(
let $prop_name = $get_expr;
)?)?
return $prop_name;
}
)?
$( macro_rules! apply_param_modifier {
#[doc = concat!(" Gets a reference to the field `", stringify!($prop_name), (move, $param_name:ident) => {
"` of the [`servicepoint::",stringify!($object_type),"`].")] unsafe { $crate::mem::heap_remove($param_name) }
$($( };
#[doc = ""] (val, $param_name:ident) => {
#[$get_mut_meta] $param_name
)*)? };
#[doc = ""] (mut, $param_name:ident) => {
#[doc = " - The returned reference inherits the lifetime of object in which it is contained."] unsafe { (&mut *$param_name.as_ptr()) }
#[doc = " - The returned pointer may not be used in a function that consumes the instance, e.g. to create a command."] };
fn [<get _ $prop_name _mut>]( (ref, $param_name:ident) => {
instance: ::core::ptr::NonNull<$object_type> unsafe { $param_name.as_ref() }
) -> ::core::ptr::NonNull<$prop_type> { };
let $prop_name = unsafe { &mut $crate::macros::nonnull_as_mut!(instance).$prop_name }; (slice, $param_name:ident) => {
$($( unsafe { $param_name.as_slice() }
let $prop_name = $get_mut_expr; };
)?)? }
return ::core::ptr::NonNull::from($prop_name);
}
)?
$( macro_rules! apply_return_modifier {
#[doc = concat!(" Sets the value of field `", stringify!($prop_name), (val, $result:ident) => {
"` of the [`servicepoint::",stringify!($object_type),"`].")] $result
$($( };
#[doc = ""] (move, $result:ident) => {
#[$set_meta] $crate::mem::heap_move_nonnull($result)
)*)? };
fn [<set _ $prop_name>]( (move_ok, $result:ident) => {
instance: ::core::ptr::NonNull<$object_type>, $crate::mem::heap_move_ok($result)
value: $prop_type, };
) { (move_some, $result:ident) => {
let instance = unsafe { $crate::macros::nonnull_as_mut!(instance) }; $crate::mem::heap_move_some($result)
$($( };
let $value = value; (slice, $result:ident) => {
let value = $set_expr; unsafe { ByteSlice::from_slice($result) }
)?)? };
instance.$prop_name = value; }
}
)?
macro_rules! wrap_function {
(
$module:ident;
$(#[$meta:meta])+
fn $function:ident($($param_name:ident: $param_modifier:ident $param_type:ty),*$(,)?)
$(-> $return_modifier:ident $return_type:ty)?
$block:block;
) => {
::paste::paste! {
$(#[$meta])+
#[doc = ""]
#[doc = " This function is part of the `" $module "` module."]
#[no_mangle]
pub unsafe extern "C" fn [< sp_ $module _ $function >](
$($param_name: $param_type),*
) $(-> $return_type)?
{
$( $(
#[doc = concat!(" Sets the value of field `", stringify!($prop_name), let $param_name = $crate::macros::apply_param_modifier!($param_modifier, $param_name);
"` of the [`servicepoint::",stringify!($object_type),"`].")] )*
#[doc = concat!(" The provided value is moved into the instance, ", let result = $block;
"potentially invalidating previously taken references.")] $(
$($( let result = $crate::macros::apply_return_modifier!($return_modifier, result);
#[doc = ""]
#[$set_move_meta]
)*)?
fn [<set _ $prop_name>](
instance: ::core::ptr::NonNull<$object_type>,
value: NonNull<$prop_type>,
) {
let instance = unsafe { $crate::macros::nonnull_as_mut!(instance) };
let value = unsafe { $crate::mem::heap_remove(value) };
$($(
let $set_move_value = value;
let value = $set_move_expr;
)?)?
instance.$prop_name = value;
}
)? )?
)+ result
); }
} }
}; };
} }
macro_rules! wrap_functions { macro_rules! wrap_functions {
( (
$prefix:ident; $module:ident;
$( $(
$(#[$meta:meta])+ $(#[$meta:meta])+
fn $function:ident($($param_name:ident: $param_type:ty),*$(,)?) fn $function:ident($($param_name:ident: $param_modifier:ident $param_type:ty),*$(,)?)
$(-> $return_type:ty)? $(-> $return_modifier:ident $return_type:ty)?
$block:block $block:block;
)+ )+
) => { ) => {
::paste::paste! { ::paste::paste! {
$( $(
$(#[$meta])* $crate::macros::wrap_function!($module;
#[doc = ""] $(#[$meta])+
#[doc = concat!(" This function is part of the ", stringify!($prefix), " module.")] fn $function($($param_name: $param_modifier $param_type),*) $(-> $return_modifier $return_type)?
#[no_mangle] $block;
pub unsafe extern "C" fn [<$prefix _ $function>]( );
$($param_name: $param_type),*
) $(-> $return_type)?
$block
)+ )+
} }
}; };
(
associate $object_type:ident;
$(
$(#[$meta:meta])+
fn $function:ident($($param_name:ident: $param_modifier:ident $param_type:ty),*$(,)?)
$(-> $return_modifier:ident $return_type:ty)?
$block:block;
)+
) => {
::paste::paste! {
$crate::macros::wrap_functions!{[< $object_type:lower >];
$(
$(#[$meta])+
fn $function($($param_name: $param_modifier $param_type),*) $(-> $return_modifier $return_type)?
$block;
)+
}
}
};
} }
pub(crate) use { pub(crate) use {
nonnull_as_mut, nonnull_as_ref, wrap_clone, wrap_fields, wrap_free, apply_param_modifier, apply_return_modifier, derive_clone, derive_free,
wrap_functions, wrap_methods, wrap_fields, wrap_fields_accessor, wrap_function, wrap_functions,
wrap_method, wrap_methods,
}; };

View file

@ -1,103 +1,89 @@
use crate::{ use crate::{
containers::ByteSlice, containers::ByteSlice,
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions}, macros::{
mem::{heap_move_nonnull, heap_move_ok}, derive_clone, derive_free, wrap_fields, wrap_functions, wrap_methods,
},
}; };
use servicepoint::{CommandCode, Header, Packet}; use servicepoint::{CommandCode, Header, Packet};
use std::ptr::NonNull; use std::ptr::NonNull;
wrap_functions!(sp_packet; wrap_functions!(associate Packet;
/// 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
fn try_load(data: ByteSlice) -> *mut Packet { fn try_load(data: slice ByteSlice) -> move_ok *mut Packet {
let data = unsafe { data.as_slice() }; servicepoint::Packet::try_from(data)
heap_move_ok(servicepoint::Packet::try_from(data)) };
}
/// Creates a raw [Packet] from parts. /// Creates a raw [Packet] from parts.
/// ///
/// returns: new instance. Will never return null. /// returns: new instance. Will never return null.
fn from_parts(header: Header, payload: ByteSlice) -> NonNull<Packet> { fn from_parts(header: val Header, payload: val ByteSlice) -> move NonNull<Packet> {
let payload = if payload == ByteSlice::INVALID { let payload = if payload == ByteSlice::INVALID {
None None
} else { } else {
Some(Vec::from(unsafe { payload.as_slice() })) Some(Vec::from(unsafe { payload.as_slice() }))
}; };
heap_move_nonnull(Packet { header, payload }) Packet { header, payload }
} };
);
derive_clone!(Packet);
derive_free!(Packet);
wrap_fields!(Packet;
prop header: Header { get; get mut; set; };
);
wrap_methods! { Packet;
/// Returns a pointer to the current payload of the provided packet. /// Returns a pointer to the current payload of the provided packet.
/// ///
/// Returns an [ByteSlice::INVALID] instance in case the packet does not have any payload. /// Returns an [ByteSlice::INVALID] instance in case the packet does not have any payload.
/// ///
/// The returned memory can be changed and will be valid until a new payload is set. /// The returned memory can be changed and will be valid until a new payload is set.
fn get_payload(packet: NonNull<Packet>) -> ByteSlice { fn get_payload(mut packet) -> val ByteSlice {
unsafe { match &mut packet.payload {
match &mut (*packet.as_ptr()).payload { None => ByteSlice::INVALID,
None => ByteSlice::INVALID, Some(payload) => unsafe { ByteSlice::from_slice(payload) },
Some(payload) => ByteSlice::from_slice(payload),
}
} }
} };
/// Sets the payload of the provided packet to the provided data. /// Sets the payload of the provided packet to the provided data.
/// ///
/// This makes previous payload pointers invalid. /// This makes previous payload pointers invalid.
fn set_payload(packet: NonNull<Packet>, data: ByteSlice) { fn set_payload(mut packet, data: val ByteSlice) {
unsafe { packet.payload = if data == ByteSlice::INVALID {
(*packet.as_ptr()).payload = if data == ByteSlice::INVALID { None
None } else {
} else { Some(unsafe { data.as_slice().to_vec() })
Some(data.as_slice().to_vec())
}
} }
} };
/// Serialize the packet into the provided buffer. /// Serialize the packet into the provided buffer.
/// ///
/// # Panics /// # Panics
/// ///
/// - if the buffer is not big enough to hold header+payload. /// - if the buffer is not big enough to hold header+payload.
fn serialize_to(packet: NonNull<Packet>, buffer: ByteSlice) -> usize { fn serialize_to(mut packet, buffer: val ByteSlice) -> val usize {
unsafe { unsafe {
packet.as_ref().serialize_to(buffer.as_slice_mut()).unwrap_or(0) packet.serialize_to(buffer.as_slice_mut()).unwrap_or(0)
} }
}
);
wrap_clone!(sp_packet::Packet);
wrap_free!(sp_packet::Packet);
wrap_fields!(
sp_packet::Packet;
prop header: Header {
get();
mut get();
set(value);
}; };
); }
wrap_functions!(sp; wrap_functions!(sp;
/// Converts u16 into [CommandCode]. /// Converts u16 into [CommandCode].
/// ///
/// If the provided value is not valid, false is returned and result is not changed. /// If the provided value is not valid, false is returned and result is not changed.
fn u16_to_command_code( fn u16_to_command_code(code: val u16, result: mut NonNull<CommandCode>) -> val bool {
code: u16,
result: *mut CommandCode,
) -> bool {
match CommandCode::try_from(code) { match CommandCode::try_from(code) {
Ok(code) => { Ok(code) => {
unsafe { *result = code;
*result = code;
}
true true
} }
Err(_) => false, Err(_) => false,
} }
} };
); );

View file

@ -1,7 +1,7 @@
use crate::{ use crate::{
commands::{CommandTag, SPCommand}, commands::{CommandTag, GenericCommand},
macros::{wrap_free, wrap_functions}, macros::{derive_free, wrap_functions, wrap_methods},
mem::{heap_move_ok, heap_remove}, mem::heap_remove,
}; };
use servicepoint::{Header, Packet, UdpSocketExt}; use servicepoint::{Header, Packet, UdpSocketExt};
use std::{ use std::{
@ -10,10 +10,9 @@ use std::{
ptr::NonNull, ptr::NonNull,
}; };
wrap_free!(sp_udp::UdpSocket); derive_free!(UdpSocket);
wrap_functions!(sp_udp;
wrap_functions!(associate UdpSocket;
/// Creates a new instance of [UdpSocket]. /// Creates a new instance of [UdpSocket].
/// ///
/// returns: NULL if connection fails, or connected instance /// returns: NULL if connection fails, or connected instance
@ -25,13 +24,12 @@ wrap_functions!(sp_udp;
/// if (connection != NULL) /// if (connection != NULL)
/// sp_udp_send_command(connection, sp_command_clear()); /// sp_udp_send_command(connection, sp_command_clear());
/// ``` /// ```
fn open(host: NonNull<c_char>) -> *mut UdpSocket { fn open(host: val NonNull<c_char>) -> move_ok *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");
UdpSocket::bind_connect(host)
heap_move_ok(UdpSocket::bind_connect(host)) };
}
/// Creates a new instance of [UdpSocket]. /// Creates a new instance of [UdpSocket].
/// ///
@ -44,22 +42,23 @@ wrap_functions!(sp_udp;
/// if (connection != NULL) /// if (connection != NULL)
/// sp_udp_send_command(connection, sp_command_clear()); /// sp_udp_send_command(connection, sp_command_clear());
/// ``` /// ```
fn open_ipv4(ip1: u8, ip2: u8, ip3: u8, ip4: u8, port: u16) -> *mut UdpSocket { fn open_ipv4(ip1: val u8, ip2: val u8, ip3: val u8, ip4: val u8, port: val u16) -> move_ok *mut UdpSocket {
let addr = SocketAddrV4::new(Ipv4Addr::from([ip1, ip2, ip3, ip4]), port); let addr = SocketAddrV4::new(Ipv4Addr::from([ip1, ip2, ip3, ip4]), port);
heap_move_ok(UdpSocket::bind_connect(addr)) UdpSocket::bind_connect(addr)
} };
);
wrap_methods! {UdpSocket;
/// Sends a [Packet] to the display using the [UdpSocket]. /// Sends a [Packet] to the display using the [UdpSocket].
/// ///
/// The passed `packet` gets consumed. /// The passed `packet` gets consumed.
/// ///
/// returns: true in case of success /// returns: true in case of success
fn send_packet(connection: NonNull<UdpSocket>, packet: NonNull<Packet>) -> bool { fn send_packet(ref connection, packet: move NonNull<Packet>) -> val bool {
let packet = unsafe { heap_remove(packet) }; connection.send(&Vec::from(packet)).is_ok()
unsafe { connection.as_ref().send(&Vec::from(packet)) }.is_ok() };
}
/// Sends a [SPCommand] to the display using the [UdpSocket]. /// Sends a [GenericCommand] to the display using the [UdpSocket].
/// ///
/// The passed `command` gets consumed. /// The passed `command` gets consumed.
/// ///
@ -70,44 +69,25 @@ wrap_functions!(sp_udp;
/// ```C /// ```C
/// sp_udp_send_command(connection, sp_command_brightness(5)); /// sp_udp_send_command(connection, sp_command_brightness(5));
/// ``` /// ```
fn send_command(connection: NonNull<UdpSocket>, command: SPCommand) -> bool { fn send_command(ref connection, command: mut NonNull<GenericCommand>) -> val bool {
unsafe { unsafe {
match command.tag { let result = match command.tag {
CommandTag::Invalid => return false, CommandTag::Invalid => return false,
CommandTag::Bitmap => connection CommandTag::Bitmap => connection.send_command(heap_remove(command.data.bitmap)),
.as_ref() CommandTag::BitVec => connection.send_command(heap_remove(command.data.bit_vec)),
.send_command(heap_remove(command.data.bitmap)), CommandTag::BrightnessGrid => connection.send_command(heap_remove(command.data.brightness_grid)),
CommandTag::BitVec => connection CommandTag::CharGrid => connection.send_command(heap_remove(command.data.char_grid)),
.as_ref() CommandTag::Cp437Grid => connection.send_command(heap_remove(command.data.cp437_grid)),
.send_command(heap_remove(command.data.bitvec)), CommandTag::GlobalBrightness => connection.send_command(heap_remove(command.data.global_brightness)),
CommandTag::BrightnessGrid => connection CommandTag::Clear => connection.send_command(heap_remove(command.data.clear)),
.as_ref() CommandTag::HardReset => connection.send_command(heap_remove(command.data.hard_reset)),
.send_command(heap_remove(command.data.brightness_grid)), CommandTag::FadeOut => connection.send_command(heap_remove(command.data.fade_out)),
CommandTag::CharGrid => connection CommandTag::BitmapLegacy => connection.send_command(heap_remove(command.data.bitmap_legacy)),
.as_ref() }.is_some();
.send_command(heap_remove(command.data.char_grid)), *command = GenericCommand::INVALID;
CommandTag::Cp437Grid => connection result
.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 [UdpSocket]. /// Sends a [Header] to the display using the [UdpSocket].
/// ///
@ -118,14 +98,19 @@ wrap_functions!(sp_udp;
/// ```C /// ```C
/// sp_udp_send_header(connection, sp_command_brightness(5)); /// sp_udp_send_header(connection, sp_command_brightness(5));
/// ``` /// ```
fn send_header(udp_connection: NonNull<UdpSocket>, header: Header) -> bool { fn send_header(ref udp_connection, header: val Header) -> val bool {
let packet = Packet { let packet = Packet {
header, header,
payload: None, payload: None,
}; };
unsafe { udp_connection.as_ref() } udp_connection.send(&Vec::from(packet)).is_ok()
.send(&Vec::from(packet)) };
.is_ok() }
}
); mod _hidden {
/// This is a type only used by cbindgen to have a type for pointers.
///
/// See [servicepoint::UdpSocketExt].
#[allow(unused)]
pub struct UdpSocket;
}