Compare commits

..

No commits in common. "6dcd26d1c1ddf4b87d687209efbb491cc1d26074" and "8fe4038a436f6a52712a392514765a5c0237937b" have entirely different histories.

18 changed files with 758 additions and 765 deletions

4
Cargo.lock generated
View file

@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 3
[[package]] [[package]]
name = "adler2" name = "adler2"
@ -408,7 +408,7 @@ dependencies = [
[[package]] [[package]]
name = "servicepoint" name = "servicepoint"
version = "0.13.2" version = "0.13.2"
source = "git+https://git.berlin.ccc.de/servicepoint/servicepoint/?branch=next#971bee5065139f220022e8108cfaa9c263b8a8a0" source = "git+https://git.berlin.ccc.de/servicepoint/servicepoint/?branch=next#fe67160974d9fed542eb37e5e9a202eaf6fe00dc"
dependencies = [ dependencies = [
"bitvec", "bitvec",
"bzip2", "bzip2",

View file

@ -6,30 +6,28 @@
use std::{env, fs::copy}; use std::{env, fs::copy};
use cbindgen::{generate_with_config, Config};
fn main() { fn main() {
let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
println!("cargo::rerun-if-changed={crate_dir}"); println!("cargo::rerun-if-changed={crate_dir}");
let config = let config =
cbindgen::Config::from_file(crate_dir.clone() + "/cbindgen.toml") Config::from_file(crate_dir.clone() + "/cbindgen.toml").unwrap();
.unwrap();
let output_dir = env::var("OUT_DIR").unwrap(); let output_dir = env::var("OUT_DIR").unwrap();
let header_file = output_dir.clone() + "/servicepoint.h"; let header_file = output_dir.clone() + "/servicepoint.h";
if let Ok(bindings) = cbindgen::generate_with_config(crate_dir, config) { generate_with_config(crate_dir, config)
bindings.write_to_file(&header_file); .unwrap()
.write_to_file(&header_file);
println!("cargo:include={output_dir}");
println!("cargo:include={output_dir}"); println!("cargo::rerun-if-env-changed=SERVICEPOINT_HEADER_OUT");
if let Ok(header_out) = env::var("SERVICEPOINT_HEADER_OUT") {
println!("cargo::rerun-if-env-changed=SERVICEPOINT_HEADER_OUT"); let header_copy = header_out + "/servicepoint.h";
if let Ok(header_out) = env::var("SERVICEPOINT_HEADER_OUT") { println!("cargo:warning=Copying header to {header_copy}");
let header_copy = header_out + "/servicepoint.h"; copy(header_file, &header_copy).unwrap();
println!("cargo:warning=Copying header to {header_copy}"); println!("cargo::rerun-if-changed={header_copy}");
copy(header_file, &header_copy).unwrap();
println!("cargo::rerun-if-changed={header_copy}");
}
} else {
eprintln!("cargo:warning=Servicepoint header could not be generated");
} }
} }

View file

@ -19,13 +19,11 @@ line_endings = "LF"
style = "type" style = "type"
usize_is_size_t = true usize_is_size_t = true
# this is needed because otherwise the order in the C bindings is different on different machines # this is needed because otherwise the order in the C# bindings is different on different machines
sort_by = "Name" sort_by = "Name"
[parse] [parse]
parse_deps = true parse_deps = false
include = ["servicepoint"]
extra_bindings = ["servicepoint"]
[parse.expand] [parse.expand]
features = ["full"] features = ["full"]
@ -34,11 +32,5 @@ features = ["full"]
include = [] include = []
exclude = [] exclude = []
[export.rename]
"TypedCommand" = "Command"
[enum] [enum]
rename_variants = "QualifiedScreamingSnakeCase" rename_variants = "QualifiedScreamingSnakeCase"
[ptr]
non_null_attribute = "/*notnull*/"

View file

@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 3
[[package]] [[package]]
name = "adler2" name = "adler2"
@ -423,7 +423,7 @@ dependencies = [
[[package]] [[package]]
name = "servicepoint" name = "servicepoint"
version = "0.13.2" version = "0.13.2"
source = "git+https://git.berlin.ccc.de/servicepoint/servicepoint/?branch=next#971bee5065139f220022e8108cfaa9c263b8a8a0" source = "git+https://git.berlin.ccc.de/servicepoint/servicepoint/?branch=next#75d24f658764dea251e28c7067446f3ccfbb89b0"
dependencies = [ dependencies = [
"bitvec", "bitvec",
"bzip2", "bzip2",

View file

@ -36,7 +36,7 @@ CCFLAGS := -static -Os \
-fvisibility=hidden \ -fvisibility=hidden \
-Bsymbolic \ -Bsymbolic \
-Wl,--exclude-libs,ALL \ -Wl,--exclude-libs,ALL \
-fno-ident -fno-ident \
#-fuse-ld=gold \ #-fuse-ld=gold \
-fno-exceptions -fno-exceptions
#-Wl,--icf=all \ #-Wl,--icf=all \

File diff suppressed because it is too large Load diff

View file

@ -2,26 +2,21 @@
#include "servicepoint.h" #include "servicepoint.h"
int main(void) { int main(void) {
UdpConnection *connection = sp_connection_open("localhost:2342"); SPConnection *connection = sp_connection_open("localhost:2342");
if (connection == NULL) if (connection == NULL)
return 1; return 1;
Bitmap *pixels = sp_bitmap_new(PIXEL_WIDTH, PIXEL_HEIGHT); SPBitmap *pixels = sp_bitmap_new(SP_PIXEL_WIDTH, SP_PIXEL_HEIGHT);
if (pixels == NULL) if (pixels == NULL)
return 1; return 1;
sp_bitmap_fill(pixels, true); sp_bitmap_fill(pixels, true);
Command *command = sp_command_bitmap_linear_win(0, 0, pixels, COMPRESSION_CODE_UNCOMPRESSED); SPCommand *command = sp_command_bitmap_linear_win(0, 0, pixels, SP_COMPRESSION_CODE_UNCOMPRESSED);
if (command == NULL) if (command == NULL)
return 1; return 1;
Packet *packet = sp_packet_from_command(command); sp_connection_send_command(connection, command);
Header *header = sp_packet_get_header(packet);
printf("[%d, %d, %d, %d, %d]\n", header->command_code, header->a, header->b, header->c, header->d);
sp_connection_send_packet(connection, packet);
sp_connection_free(connection); sp_connection_free(connection);
return 0; return 0;

View file

@ -1,23 +1,24 @@
//! C functions for interacting with [SPBitmap]s //! C functions for interacting with [SPBitmap]s
//! //!
//! prefix `sp_bitmap_` //! prefix `sp_bitmap_`
//!
//! A grid of pixels.
//!
//! # Examples
//!
//! ```C
//! Cp437Grid grid = sp_bitmap_new(8, 3);
//! sp_bitmap_fill(grid, true);
//! sp_bitmap_set(grid, 0, 0, false);
//! sp_bitmap_free(grid);
//! ```
use servicepoint::{Bitmap, DataRef, Grid}; use servicepoint::{DataRef, Grid};
use std::ptr::NonNull; use std::ptr::NonNull;
use crate::byte_slice::SPByteSlice; use crate::byte_slice::SPByteSlice;
/// A grid of pixels.
///
/// # Examples
///
/// ```C
/// Cp437Grid grid = sp_bitmap_new(8, 3);
/// sp_bitmap_fill(grid, true);
/// sp_bitmap_set(grid, 0, 0, false);
/// sp_bitmap_free(grid);
/// ```
pub struct SPBitmap(pub(crate) servicepoint::Bitmap);
/// Creates a new [SPBitmap] with the specified dimensions. /// Creates a new [SPBitmap] with the specified dimensions.
/// ///
/// # Arguments /// # Arguments
@ -43,9 +44,9 @@ use crate::byte_slice::SPByteSlice;
pub unsafe extern "C" fn sp_bitmap_new( pub unsafe extern "C" fn sp_bitmap_new(
width: usize, width: usize,
height: usize, height: usize,
) -> *mut Bitmap { ) -> *mut SPBitmap {
if let Some(bitmap) = Bitmap::new(width, height) { if let Some(bitmap) = servicepoint::Bitmap::new(width, height) {
Box::leak(Box::new(bitmap)) Box::leak(Box::new(SPBitmap(bitmap)))
} else { } else {
std::ptr::null_mut() std::ptr::null_mut()
} }
@ -62,8 +63,8 @@ pub unsafe extern "C" fn sp_bitmap_new(
/// - the returned instance is freed in some way, either by using a consuming function or /// - the returned instance is freed in some way, either by using a consuming function or
/// by explicitly calling [sp_bitmap_free]. /// by explicitly calling [sp_bitmap_free].
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_new_screen_sized() -> NonNull<Bitmap> { pub unsafe extern "C" fn sp_bitmap_new_screen_sized() -> NonNull<SPBitmap> {
let result = Box::new(Bitmap::max_sized()); let result = Box::new(SPBitmap(servicepoint::Bitmap::max_sized()));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -98,11 +99,13 @@ pub unsafe extern "C" fn sp_bitmap_new_screen_sized() -> NonNull<Bitmap> {
pub unsafe extern "C" fn sp_bitmap_load( pub unsafe extern "C" fn sp_bitmap_load(
width: usize, width: usize,
height: usize, height: usize,
data: SPByteSlice, data: *const u8,
) -> *mut Bitmap { data_length: usize,
let data = unsafe { data.as_slice() }; ) -> *mut SPBitmap {
if let Ok(bitmap) = Bitmap::load(width, height, data) { assert!(!data.is_null());
Box::leak(Box::new(bitmap)) let data = unsafe { std::slice::from_raw_parts(data, data_length) };
if let Ok(bitmap) = servicepoint::Bitmap::load(width, height, data) {
Box::leak(Box::new(SPBitmap(bitmap)))
} else { } else {
std::ptr::null_mut() std::ptr::null_mut()
} }
@ -126,9 +129,10 @@ pub unsafe extern "C" fn sp_bitmap_load(
/// by explicitly calling `sp_bitmap_free`. /// by explicitly calling `sp_bitmap_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_clone( pub unsafe extern "C" fn sp_bitmap_clone(
bitmap: NonNull<Bitmap>, bitmap: *const SPBitmap,
) -> NonNull<Bitmap> { ) -> NonNull<SPBitmap> {
let result = Box::new(unsafe { bitmap.as_ref().clone() }); assert!(!bitmap.is_null());
let result = Box::new(SPBitmap(unsafe { (*bitmap).0.clone() }));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -143,11 +147,14 @@ pub unsafe extern "C" fn sp_bitmap_clone(
/// The caller has to make sure that: /// The caller has to make sure that:
/// ///
/// - `bitmap` points to a valid [SPBitmap] /// - `bitmap` points to a valid [SPBitmap]
/// - `bitmap` is not used concurrently or after bitmap call
/// - `bitmap` was not passed to another consuming function, e.g. to create a [SPCommand]
/// ///
/// [SPCommand]: [crate::SPCommand] /// [SPCommand]: [crate::SPCommand]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_free(bitmap: NonNull<Bitmap>) { pub unsafe extern "C" fn sp_bitmap_free(bitmap: *mut SPBitmap) {
_ = unsafe { Box::from_raw(bitmap.as_ptr()) }; assert!(!bitmap.is_null());
_ = unsafe { Box::from_raw(bitmap) };
} }
/// Gets the current value at the specified position in the [SPBitmap]. /// Gets the current value at the specified position in the [SPBitmap].
@ -170,11 +177,12 @@ pub unsafe extern "C" fn sp_bitmap_free(bitmap: NonNull<Bitmap>) {
/// - `bitmap` is not written to concurrently /// - `bitmap` is not written to concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_get( pub unsafe extern "C" fn sp_bitmap_get(
bitmap: NonNull<Bitmap>, bitmap: *const SPBitmap,
x: usize, x: usize,
y: usize, y: usize,
) -> bool { ) -> bool {
unsafe { bitmap.as_ref().get(x, y) } assert!(!bitmap.is_null());
unsafe { (*bitmap).0.get(x, y) }
} }
/// Sets the value of the specified position in the [SPBitmap]. /// Sets the value of the specified position in the [SPBitmap].
@ -200,12 +208,13 @@ pub unsafe extern "C" fn sp_bitmap_get(
/// - `bitmap` is not written to or read from concurrently /// - `bitmap` is not written to or read from concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_set( pub unsafe extern "C" fn sp_bitmap_set(
bitmap: NonNull<Bitmap>, bitmap: *mut SPBitmap,
x: usize, x: usize,
y: usize, y: usize,
value: bool, value: bool,
) { ) {
unsafe { (*bitmap.as_ptr()).set(x, y, value) }; assert!(!bitmap.is_null());
unsafe { (*bitmap).0.set(x, y, value) };
} }
/// Sets the state of all pixels in the [SPBitmap]. /// Sets the state of all pixels in the [SPBitmap].
@ -226,8 +235,9 @@ pub unsafe extern "C" fn sp_bitmap_set(
/// - `bitmap` points to a valid [SPBitmap] /// - `bitmap` points to a valid [SPBitmap]
/// - `bitmap` is not written to or read from concurrently /// - `bitmap` is not written to or read from concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_fill(bitmap: NonNull<Bitmap>, value: bool) { pub unsafe extern "C" fn sp_bitmap_fill(bitmap: *mut SPBitmap, value: bool) {
unsafe { (*bitmap.as_ptr()).fill(value) }; assert!(!bitmap.is_null());
unsafe { (*bitmap).0.fill(value) };
} }
/// Gets the width in pixels of the [SPBitmap] instance. /// Gets the width in pixels of the [SPBitmap] instance.
@ -246,8 +256,9 @@ pub unsafe extern "C" fn sp_bitmap_fill(bitmap: NonNull<Bitmap>, value: bool) {
/// ///
/// - `bitmap` points to a valid [SPBitmap] /// - `bitmap` points to a valid [SPBitmap]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_width(bitmap: NonNull<Bitmap>) -> usize { pub unsafe extern "C" fn sp_bitmap_width(bitmap: *const SPBitmap) -> usize {
unsafe { bitmap.as_ref().width() } assert!(!bitmap.is_null());
unsafe { (*bitmap).0.width() }
} }
/// Gets the height in pixels of the [SPBitmap] instance. /// Gets the height in pixels of the [SPBitmap] instance.
@ -266,8 +277,9 @@ pub unsafe extern "C" fn sp_bitmap_width(bitmap: NonNull<Bitmap>) -> usize {
/// ///
/// - `bitmap` points to a valid [SPBitmap] /// - `bitmap` points to a valid [SPBitmap]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_height(bitmap: NonNull<Bitmap>) -> usize { pub unsafe extern "C" fn sp_bitmap_height(bitmap: *const SPBitmap) -> usize {
unsafe { bitmap.as_ref().height() } assert!(!bitmap.is_null());
unsafe { (*bitmap).0.height() }
} }
/// Gets an unsafe reference to the data of the [SPBitmap] instance. /// Gets an unsafe reference to the data of the [SPBitmap] instance.
@ -285,7 +297,12 @@ pub unsafe extern "C" fn sp_bitmap_height(bitmap: NonNull<Bitmap>) -> usize {
/// - the returned memory range is never accessed concurrently, either via the [SPBitmap] or directly /// - the returned memory range is never accessed concurrently, either via the [SPBitmap] or directly
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitmap_unsafe_data_ref( pub unsafe extern "C" fn sp_bitmap_unsafe_data_ref(
mut bitmap: NonNull<Bitmap>, bitmap: *mut SPBitmap,
) -> SPByteSlice { ) -> SPByteSlice {
unsafe { SPByteSlice::from_slice(bitmap.as_mut().data_ref_mut()) } assert!(!bitmap.is_null());
let data = unsafe { (*bitmap).0.data_ref_mut() };
SPByteSlice {
start: NonNull::new(data.as_mut_ptr_range().start).unwrap(),
length: data.len(),
}
} }

View file

@ -13,7 +13,19 @@ use std::ptr::NonNull;
/// sp_bitvec_set(vec, 5, true); /// sp_bitvec_set(vec, 5, true);
/// sp_bitvec_free(vec); /// sp_bitvec_free(vec);
/// ``` /// ```
pub struct SPBitVec(pub(crate) servicepoint::BitVecU8Msb0); pub struct SPBitVec(servicepoint::BitVec);
impl From<servicepoint::BitVec> for SPBitVec {
fn from(actual: servicepoint::BitVec) -> Self {
Self(actual)
}
}
impl From<SPBitVec> for servicepoint::BitVec {
fn from(value: SPBitVec) -> Self {
value.0
}
}
impl Clone for SPBitVec { impl Clone for SPBitVec {
fn clone(&self) -> Self { fn clone(&self) -> Self {
@ -41,8 +53,7 @@ impl Clone for SPBitVec {
/// by explicitly calling `sp_bitvec_free`. /// by explicitly calling `sp_bitvec_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_new(size: usize) -> NonNull<SPBitVec> { pub unsafe extern "C" fn sp_bitvec_new(size: usize) -> NonNull<SPBitVec> {
let result = let result = Box::new(SPBitVec(servicepoint::BitVec::repeat(false, size)));
Box::new(SPBitVec(servicepoint::BitVecU8Msb0::repeat(false, size)));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -64,11 +75,12 @@ pub unsafe extern "C" fn sp_bitvec_new(size: usize) -> NonNull<SPBitVec> {
/// by explicitly calling `sp_bitvec_free`. /// by explicitly calling `sp_bitvec_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_load( pub unsafe extern "C" fn sp_bitvec_load(
data: SPByteSlice, data: *const u8,
data_length: usize,
) -> NonNull<SPBitVec> { ) -> NonNull<SPBitVec> {
let data = unsafe { data.as_slice() }; assert!(!data.is_null());
let result = let data = unsafe { std::slice::from_raw_parts(data, data_length) };
Box::new(SPBitVec(servicepoint::BitVecU8Msb0::from_slice(data))); let result = Box::new(SPBitVec(servicepoint::BitVec::from_slice(data)));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -90,9 +102,10 @@ pub unsafe extern "C" fn sp_bitvec_load(
/// by explicitly calling `sp_bitvec_free`. /// by explicitly calling `sp_bitvec_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_clone( pub unsafe extern "C" fn sp_bitvec_clone(
bit_vec: NonNull<SPBitVec>, bit_vec: *const SPBitVec,
) -> NonNull<SPBitVec> { ) -> NonNull<SPBitVec> {
let result = Box::new(unsafe { bit_vec.as_ref().clone() }); assert!(!bit_vec.is_null());
let result = Box::new(unsafe { (*bit_vec).clone() });
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -112,8 +125,9 @@ pub unsafe extern "C" fn sp_bitvec_clone(
/// ///
/// [SPCommand]: [crate::SPCommand] /// [SPCommand]: [crate::SPCommand]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_free(bit_vec: NonNull<SPBitVec>) { pub unsafe extern "C" fn sp_bitvec_free(bit_vec: *mut SPBitVec) {
_ = unsafe { Box::from_raw(bit_vec.as_ptr()) }; assert!(!bit_vec.is_null());
_ = unsafe { Box::from_raw(bit_vec) };
} }
/// Gets the value of a bit from the [SPBitVec]. /// Gets the value of a bit from the [SPBitVec].
@ -138,10 +152,11 @@ pub unsafe extern "C" fn sp_bitvec_free(bit_vec: NonNull<SPBitVec>) {
/// - `bit_vec` is not written to concurrently /// - `bit_vec` is not written to concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_get( pub unsafe extern "C" fn sp_bitvec_get(
bit_vec: NonNull<SPBitVec>, bit_vec: *const SPBitVec,
index: usize, index: usize,
) -> bool { ) -> bool {
unsafe { *bit_vec.as_ref().0.get(index).unwrap() } assert!(!bit_vec.is_null());
unsafe { *(*bit_vec).0.get(index).unwrap() }
} }
/// Sets the value of a bit in the [SPBitVec]. /// Sets the value of a bit in the [SPBitVec].
@ -165,11 +180,12 @@ pub unsafe extern "C" fn sp_bitvec_get(
/// - `bit_vec` is not written to or read from concurrently /// - `bit_vec` is not written to or read from concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_set( pub unsafe extern "C" fn sp_bitvec_set(
bit_vec: NonNull<SPBitVec>, bit_vec: *mut SPBitVec,
index: usize, index: usize,
value: bool, value: bool,
) { ) {
unsafe { (*bit_vec.as_ptr()).0.set(index, value) } assert!(!bit_vec.is_null());
unsafe { (*bit_vec).0.set(index, value) }
} }
/// Sets the value of all bits in the [SPBitVec]. /// Sets the value of all bits in the [SPBitVec].
@ -190,11 +206,9 @@ pub unsafe extern "C" fn sp_bitvec_set(
/// - `bit_vec` points to a valid [SPBitVec] /// - `bit_vec` points to a valid [SPBitVec]
/// - `bit_vec` is not written to or read from concurrently /// - `bit_vec` is not written to or read from concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_fill( pub unsafe extern "C" fn sp_bitvec_fill(bit_vec: *mut SPBitVec, value: bool) {
bit_vec: NonNull<SPBitVec>, assert!(!bit_vec.is_null());
value: bool, unsafe { (*bit_vec).0.fill(value) }
) {
unsafe { (*bit_vec.as_ptr()).0.fill(value) }
} }
/// Gets the length of the [SPBitVec] in bits. /// Gets the length of the [SPBitVec] in bits.
@ -213,8 +227,9 @@ pub unsafe extern "C" fn sp_bitvec_fill(
/// ///
/// - `bit_vec` points to a valid [SPBitVec] /// - `bit_vec` points to a valid [SPBitVec]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_len(bit_vec: NonNull<SPBitVec>) -> usize { pub unsafe extern "C" fn sp_bitvec_len(bit_vec: *const SPBitVec) -> usize {
unsafe { bit_vec.as_ref().0.len() } assert!(!bit_vec.is_null());
unsafe { (*bit_vec).0.len() }
} }
/// Returns true if length is 0. /// Returns true if length is 0.
@ -233,10 +248,9 @@ pub unsafe extern "C" fn sp_bitvec_len(bit_vec: NonNull<SPBitVec>) -> usize {
/// ///
/// - `bit_vec` points to a valid [SPBitVec] /// - `bit_vec` points to a valid [SPBitVec]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_is_empty( pub unsafe extern "C" fn sp_bitvec_is_empty(bit_vec: *const SPBitVec) -> bool {
bit_vec: NonNull<SPBitVec>, assert!(!bit_vec.is_null());
) -> bool { unsafe { (*bit_vec).0.is_empty() }
unsafe { bit_vec.as_ref().0.is_empty() }
} }
/// Gets an unsafe reference to the data of the [SPBitVec] instance. /// Gets an unsafe reference to the data of the [SPBitVec] instance.
@ -258,7 +272,12 @@ pub unsafe extern "C" fn sp_bitvec_is_empty(
/// - the returned memory range is never accessed concurrently, either via the [SPBitVec] or directly /// - the returned memory range is never accessed concurrently, either via the [SPBitVec] or directly
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_bitvec_unsafe_data_ref( pub unsafe extern "C" fn sp_bitvec_unsafe_data_ref(
bit_vec: NonNull<SPBitVec>, bit_vec: *mut SPBitVec,
) -> SPByteSlice { ) -> SPByteSlice {
unsafe { SPByteSlice::from_slice((*bit_vec.as_ptr()).0.as_raw_mut_slice()) } assert!(!bit_vec.is_null());
let data = unsafe { (*bit_vec).0.as_raw_mut_slice() };
SPByteSlice {
start: NonNull::new(data.as_mut_ptr_range().start).unwrap(),
length: data.len(),
}
} }

View file

@ -1,26 +1,9 @@
//! C functions for interacting with [SPBrightnessGrid]s //! C functions for interacting with [SPBrightnessGrid]s
//! //!
//! prefix `sp_brightness_grid_` //! prefix `sp_brightness_grid_`
//!
//!
//! A grid containing brightness values.
//!
//! # Examples
//! ```C
//! SPConnection connection = sp_connection_open("127.0.0.1:2342");
//! if (connection == NULL)
//! return 1;
//!
//! SPBrightnessGrid grid = sp_brightness_grid_new(2, 2);
//! sp_brightness_grid_set(grid, 0, 0, 0);
//! sp_brightness_grid_set(grid, 1, 1, 10);
//!
//! SPCommand command = sp_command_char_brightness(grid);
//! sp_connection_free(connection);
//! ```
use crate::SPByteSlice; use crate::SPByteSlice;
use servicepoint::{BrightnessGrid, DataRef, Grid}; use servicepoint::{DataRef, Grid};
use std::convert::Into; use std::convert::Into;
use std::mem::transmute; use std::mem::transmute;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -32,6 +15,24 @@ pub const SP_BRIGHTNESS_MAX: u8 = 11;
/// Count of possible brightness values /// Count of possible brightness values
pub const SP_BRIGHTNESS_LEVELS: u8 = 12; pub const SP_BRIGHTNESS_LEVELS: u8 = 12;
/// A grid containing brightness values.
///
/// # Examples
/// ```C
/// SPConnection connection = sp_connection_open("127.0.0.1:2342");
/// if (connection == NULL)
/// return 1;
///
/// SPBrightnessGrid grid = sp_brightness_grid_new(2, 2);
/// sp_brightness_grid_set(grid, 0, 0, 0);
/// sp_brightness_grid_set(grid, 1, 1, 10);
///
/// SPCommand command = sp_command_char_brightness(grid);
/// sp_connection_free(connection);
/// ```
#[derive(Clone)]
pub struct SPBrightnessGrid(pub(crate) servicepoint::BrightnessGrid);
/// Creates a new [SPBrightnessGrid] with the specified dimensions. /// Creates a new [SPBrightnessGrid] with the specified dimensions.
/// ///
/// returns: [SPBrightnessGrid] initialized to 0. Will never return NULL. /// returns: [SPBrightnessGrid] initialized to 0. Will never return NULL.
@ -46,8 +47,10 @@ pub const SP_BRIGHTNESS_LEVELS: u8 = 12;
pub unsafe extern "C" fn sp_brightness_grid_new( pub unsafe extern "C" fn sp_brightness_grid_new(
width: usize, width: usize,
height: usize, height: usize,
) -> NonNull<BrightnessGrid> { ) -> NonNull<SPBrightnessGrid> {
let result = Box::new(BrightnessGrid::new(width, height)); let result = Box::new(SPBrightnessGrid(servicepoint::BrightnessGrid::new(
width, height,
)));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -72,15 +75,17 @@ pub unsafe extern "C" fn sp_brightness_grid_new(
pub unsafe extern "C" fn sp_brightness_grid_load( pub unsafe extern "C" fn sp_brightness_grid_load(
width: usize, width: usize,
height: usize, height: usize,
data: SPByteSlice, data: *const u8,
) -> *mut BrightnessGrid { data_length: usize,
let data = unsafe { data.as_slice() }; ) -> *mut SPBrightnessGrid {
assert!(!data.is_null());
let data = unsafe { std::slice::from_raw_parts(data, data_length) };
let grid = match servicepoint::ByteGrid::load(width, height, data) { let grid = match servicepoint::ByteGrid::load(width, height, data) {
None => return std::ptr::null_mut(), None => return std::ptr::null_mut(),
Some(grid) => grid, Some(grid) => grid,
}; };
if let Ok(grid) = BrightnessGrid::try_from(grid) { if let Ok(grid) = servicepoint::BrightnessGrid::try_from(grid) {
Box::leak(Box::new(grid)) Box::leak(Box::new(SPBrightnessGrid(grid)))
} else { } else {
std::ptr::null_mut() std::ptr::null_mut()
} }
@ -108,9 +113,10 @@ pub unsafe extern "C" fn sp_brightness_grid_load(
/// by explicitly calling `sp_brightness_grid_free`. /// by explicitly calling `sp_brightness_grid_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_clone( pub unsafe extern "C" fn sp_brightness_grid_clone(
brightness_grid: NonNull<BrightnessGrid>, brightness_grid: *const SPBrightnessGrid,
) -> NonNull<BrightnessGrid> { ) -> NonNull<SPBrightnessGrid> {
let result = Box::new(unsafe { brightness_grid.as_ref().clone() }); assert!(!brightness_grid.is_null());
let result = Box::new(unsafe { (*brightness_grid).clone() });
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -135,9 +141,10 @@ pub unsafe extern "C" fn sp_brightness_grid_clone(
/// [SPCommand]: [crate::SPCommand] /// [SPCommand]: [crate::SPCommand]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_free( pub unsafe extern "C" fn sp_brightness_grid_free(
brightness_grid: NonNull<BrightnessGrid>, brightness_grid: *mut SPBrightnessGrid,
) { ) {
_ = unsafe { Box::from_raw(brightness_grid.as_ptr()) }; assert!(!brightness_grid.is_null());
_ = unsafe { Box::from_raw(brightness_grid) };
} }
/// Gets the current value at the specified position. /// Gets the current value at the specified position.
@ -162,11 +169,12 @@ pub unsafe extern "C" fn sp_brightness_grid_free(
/// - `brightness_grid` is not written to concurrently /// - `brightness_grid` is not written to concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_get( pub unsafe extern "C" fn sp_brightness_grid_get(
brightness_grid: NonNull<BrightnessGrid>, brightness_grid: *const SPBrightnessGrid,
x: usize, x: usize,
y: usize, y: usize,
) -> u8 { ) -> u8 {
unsafe { brightness_grid.as_ref().get(x, y) }.into() assert!(!brightness_grid.is_null());
unsafe { (*brightness_grid).0.get(x, y) }.into()
} }
/// Sets the value of the specified position in the [SPBrightnessGrid]. /// Sets the value of the specified position in the [SPBrightnessGrid].
@ -193,14 +201,15 @@ pub unsafe extern "C" fn sp_brightness_grid_get(
/// - `brightness_grid` is not written to or read from concurrently /// - `brightness_grid` is not written to or read from concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_set( pub unsafe extern "C" fn sp_brightness_grid_set(
brightness_grid: NonNull<BrightnessGrid>, brightness_grid: *mut SPBrightnessGrid,
x: usize, x: usize,
y: usize, y: usize,
value: u8, value: u8,
) { ) {
assert!(!brightness_grid.is_null());
let brightness = servicepoint::Brightness::try_from(value) let brightness = servicepoint::Brightness::try_from(value)
.expect("invalid brightness value"); .expect("invalid brightness value");
unsafe { (*brightness_grid.as_ptr()).set(x, y, brightness) }; unsafe { (*brightness_grid).0.set(x, y, brightness) };
} }
/// Sets the value of all cells in the [SPBrightnessGrid]. /// Sets the value of all cells in the [SPBrightnessGrid].
@ -223,12 +232,13 @@ pub unsafe extern "C" fn sp_brightness_grid_set(
/// - `brightness_grid` is not written to or read from concurrently /// - `brightness_grid` is not written to or read from concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_fill( pub unsafe extern "C" fn sp_brightness_grid_fill(
brightness_grid: NonNull<BrightnessGrid>, brightness_grid: *mut SPBrightnessGrid,
value: u8, value: u8,
) { ) {
assert!(!brightness_grid.is_null());
let brightness = servicepoint::Brightness::try_from(value) let brightness = servicepoint::Brightness::try_from(value)
.expect("invalid brightness value"); .expect("invalid brightness value");
unsafe { (*brightness_grid.as_ptr()).fill(brightness) }; unsafe { (*brightness_grid).0.fill(brightness) };
} }
/// Gets the width of the [SPBrightnessGrid] instance. /// Gets the width of the [SPBrightnessGrid] instance.
@ -250,9 +260,10 @@ pub unsafe extern "C" fn sp_brightness_grid_fill(
/// - `brightness_grid` points to a valid [SPBrightnessGrid] /// - `brightness_grid` points to a valid [SPBrightnessGrid]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_width( pub unsafe extern "C" fn sp_brightness_grid_width(
brightness_grid: NonNull<BrightnessGrid>, brightness_grid: *const SPBrightnessGrid,
) -> usize { ) -> usize {
unsafe { brightness_grid.as_ref().width() } assert!(!brightness_grid.is_null());
unsafe { (*brightness_grid).0.width() }
} }
/// Gets the height of the [SPBrightnessGrid] instance. /// Gets the height of the [SPBrightnessGrid] instance.
@ -274,9 +285,10 @@ pub unsafe extern "C" fn sp_brightness_grid_width(
/// - `brightness_grid` points to a valid [SPBrightnessGrid] /// - `brightness_grid` points to a valid [SPBrightnessGrid]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_height( pub unsafe extern "C" fn sp_brightness_grid_height(
brightness_grid: NonNull<BrightnessGrid>, brightness_grid: *const SPBrightnessGrid,
) -> usize { ) -> usize {
unsafe { brightness_grid.as_ref().height() } assert!(!brightness_grid.is_null());
unsafe { (*brightness_grid).0.height() }
} }
/// Gets an unsafe reference to the data of the [SPBrightnessGrid] instance. /// Gets an unsafe reference to the data of the [SPBrightnessGrid] instance.
@ -300,10 +312,15 @@ pub unsafe extern "C" fn sp_brightness_grid_height(
/// - the returned memory range is never accessed concurrently, either via the [SPBrightnessGrid] or directly /// - the returned memory range is never accessed concurrently, either via the [SPBrightnessGrid] or directly
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_unsafe_data_ref( pub unsafe extern "C" fn sp_brightness_grid_unsafe_data_ref(
brightness_grid: NonNull<BrightnessGrid>, brightness_grid: *mut SPBrightnessGrid,
) -> SPByteSlice { ) -> SPByteSlice {
assert_eq!(size_of::<servicepoint::Brightness>(), 1); assert!(!brightness_grid.is_null());
let data = unsafe { (*brightness_grid.as_ptr()).data_ref_mut() }; assert_eq!(core::mem::size_of::<servicepoint::Brightness>(), 1);
let data = unsafe { (*brightness_grid).0.data_ref_mut() };
// this assumes more about the memory layout than rust guarantees. yikes! // this assumes more about the memory layout than rust guarantees. yikes!
unsafe { SPByteSlice::from_slice(transmute(data)) } let data: &mut [u8] = unsafe { transmute(data) };
SPByteSlice {
start: NonNull::new(data.as_mut_ptr_range().start).unwrap(),
length: data.len(),
}
} }

View file

@ -2,6 +2,7 @@
use std::ptr::NonNull; use std::ptr::NonNull;
#[repr(C)]
/// Represents a span of memory (`&mut [u8]` ) as a struct usable by C code. /// Represents a span of memory (`&mut [u8]` ) as a struct usable by C code.
/// ///
/// You should not create an instance of this type in your C code. /// You should not create an instance of this type in your C code.
@ -15,29 +16,9 @@ use std::ptr::NonNull;
/// the function returning this type. /// the function returning this type.
/// - an instance of this created from C is never passed to a consuming function, as the rust code /// - an instance of this created from C is never passed to a consuming function, as the rust code
/// will try to free the memory of a potentially separate allocator. /// will try to free the memory of a potentially separate allocator.
#[repr(C)]
pub struct SPByteSlice { pub struct SPByteSlice {
/// The start address of the memory /// The start address of the memory
pub start: NonNull<u8>, pub start: NonNull<u8>,
/// The amount of memory in bytes /// The amount of memory in bytes
pub length: usize, pub length: usize,
} }
impl SPByteSlice {
pub(crate) unsafe fn as_slice(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.start.as_ptr(), self.length) }
}
pub(crate) unsafe fn as_slice_mut(&self) -> &mut [u8] {
unsafe {
std::slice::from_raw_parts_mut(self.start.as_ptr(), self.length)
}
}
pub(crate) unsafe fn from_slice(slice: &mut [u8]) -> Self {
Self {
start: NonNull::new(slice.as_mut_ptr()).unwrap(),
length: slice.len(),
}
}
}

View file

@ -1,27 +1,33 @@
//! C functions for interacting with [SPCharGrid]s //! C functions for interacting with [SPCharGrid]s
//! //!
//! prefix `sp_char_grid_` //! prefix `sp_char_grid_`
//!
//! A C-wrapper for grid containing UTF-8 characters.
//!
//! As the rust [char] type is not FFI-safe, characters are passed in their UTF-32 form as 32bit unsigned integers.
//!
//! The encoding is enforced in most cases by the rust standard library
//! and will panic when provided with illegal characters.
//!
//! # Examples
//!
//! ```C
//! CharGrid grid = sp_char_grid_new(4, 3);
//! sp_char_grid_fill(grid, '?');
//! sp_char_grid_set(grid, 0, 0, '!');
//! sp_char_grid_free(grid);
//! ```
use crate::SPByteSlice; use servicepoint::Grid;
use servicepoint::{CharGrid, Grid};
use std::ptr::NonNull; use std::ptr::NonNull;
/// A C-wrapper for grid containing UTF-8 characters.
///
/// As the rust [char] type is not FFI-safe, characters are passed in their UTF-32 form as 32bit unsigned integers.
///
/// The encoding is enforced in most cases by the rust standard library
/// and will panic when provided with illegal characters.
///
/// # Examples
///
/// ```C
/// CharGrid grid = sp_char_grid_new(4, 3);
/// sp_char_grid_fill(grid, '?');
/// sp_char_grid_set(grid, 0, 0, '!');
/// sp_char_grid_free(grid);
/// ```
pub struct SPCharGrid(pub(crate) servicepoint::CharGrid);
impl Clone for SPCharGrid {
fn clone(&self) -> Self {
SPCharGrid(self.0.clone())
}
}
/// Creates a new [SPCharGrid] with the specified dimensions. /// Creates a new [SPCharGrid] with the specified dimensions.
/// ///
/// returns: [SPCharGrid] initialized to 0. Will never return NULL. /// returns: [SPCharGrid] initialized to 0. Will never return NULL.
@ -36,8 +42,9 @@ use std::ptr::NonNull;
pub unsafe extern "C" fn sp_char_grid_new( pub unsafe extern "C" fn sp_char_grid_new(
width: usize, width: usize,
height: usize, height: usize,
) -> NonNull<CharGrid> { ) -> NonNull<SPCharGrid> {
let result = Box::new(CharGrid::new(width, height)); let result =
Box::new(SPCharGrid(servicepoint::CharGrid::new(width, height)));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -63,12 +70,15 @@ pub unsafe extern "C" fn sp_char_grid_new(
pub unsafe extern "C" fn sp_char_grid_load( pub unsafe extern "C" fn sp_char_grid_load(
width: usize, width: usize,
height: usize, height: usize,
data: SPByteSlice, data: *const u8,
) -> NonNull<CharGrid> { data_length: usize,
let data = unsafe { data.as_slice() }; ) -> NonNull<SPCharGrid> {
// TODO remove unwrap assert!(data.is_null());
let result = let data = unsafe { std::slice::from_raw_parts(data, data_length) };
Box::new(CharGrid::load_utf8(width, height, data.to_vec()).unwrap()); let result = Box::new(SPCharGrid(
servicepoint::CharGrid::load_utf8(width, height, data.to_vec())
.unwrap(),
));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -90,9 +100,10 @@ pub unsafe extern "C" fn sp_char_grid_load(
/// by explicitly calling `sp_char_grid_free`. /// by explicitly calling `sp_char_grid_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_char_grid_clone( pub unsafe extern "C" fn sp_char_grid_clone(
char_grid: NonNull<CharGrid>, char_grid: *const SPCharGrid,
) -> NonNull<CharGrid> { ) -> NonNull<SPCharGrid> {
let result = Box::new(unsafe { char_grid.as_ref().clone() }); assert!(!char_grid.is_null());
let result = Box::new(unsafe { (*char_grid).clone() });
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -112,8 +123,9 @@ pub unsafe extern "C" fn sp_char_grid_clone(
/// ///
/// [SPCommand]: [crate::SPCommand] /// [SPCommand]: [crate::SPCommand]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_char_grid_free(char_grid: NonNull<CharGrid>) { pub unsafe extern "C" fn sp_char_grid_free(char_grid: *mut SPCharGrid) {
_ = unsafe { Box::from_raw(char_grid.as_ptr()) }; assert!(!char_grid.is_null());
_ = unsafe { Box::from_raw(char_grid) };
} }
/// Gets the current value at the specified position. /// Gets the current value at the specified position.
@ -136,11 +148,12 @@ pub unsafe extern "C" fn sp_char_grid_free(char_grid: NonNull<CharGrid>) {
/// - `char_grid` is not written to concurrently /// - `char_grid` is not written to concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_char_grid_get( pub unsafe extern "C" fn sp_char_grid_get(
char_grid: NonNull<CharGrid>, char_grid: *const SPCharGrid,
x: usize, x: usize,
y: usize, y: usize,
) -> u32 { ) -> u32 {
unsafe { char_grid.as_ref().get(x, y) as u32 } assert!(!char_grid.is_null());
unsafe { (*char_grid).0.get(x, y) as u32 }
} }
/// Sets the value of the specified position in the [SPCharGrid]. /// Sets the value of the specified position in the [SPCharGrid].
@ -168,12 +181,13 @@ pub unsafe extern "C" fn sp_char_grid_get(
/// [SPBitVec]: [crate::SPBitVec] /// [SPBitVec]: [crate::SPBitVec]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_char_grid_set( pub unsafe extern "C" fn sp_char_grid_set(
char_grid: NonNull<CharGrid>, char_grid: *mut SPCharGrid,
x: usize, x: usize,
y: usize, y: usize,
value: u32, value: u32,
) { ) {
unsafe { (*char_grid.as_ptr()).set(x, y, char::from_u32(value).unwrap()) }; assert!(!char_grid.is_null());
unsafe { (*char_grid).0.set(x, y, char::from_u32(value).unwrap()) };
} }
/// Sets the value of all cells in the [SPCharGrid]. /// Sets the value of all cells in the [SPCharGrid].
@ -195,10 +209,11 @@ pub unsafe extern "C" fn sp_char_grid_set(
/// - `char_grid` is not written to or read from concurrently /// - `char_grid` is not written to or read from concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_char_grid_fill( pub unsafe extern "C" fn sp_char_grid_fill(
char_grid: NonNull<CharGrid>, char_grid: *mut SPCharGrid,
value: u32, value: u32,
) { ) {
unsafe { (*char_grid.as_ptr()).fill(char::from_u32(value).unwrap()) }; assert!(!char_grid.is_null());
unsafe { (*char_grid).0.fill(char::from_u32(value).unwrap()) };
} }
/// Gets the width of the [SPCharGrid] instance. /// Gets the width of the [SPCharGrid] instance.
@ -218,9 +233,10 @@ pub unsafe extern "C" fn sp_char_grid_fill(
/// - `char_grid` points to a valid [SPCharGrid] /// - `char_grid` points to a valid [SPCharGrid]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_char_grid_width( pub unsafe extern "C" fn sp_char_grid_width(
char_grid: NonNull<CharGrid>, char_grid: *const SPCharGrid,
) -> usize { ) -> usize {
unsafe { char_grid.as_ref().width() } assert!(!char_grid.is_null());
unsafe { (*char_grid).0.width() }
} }
/// Gets the height of the [SPCharGrid] instance. /// Gets the height of the [SPCharGrid] instance.
@ -240,7 +256,8 @@ pub unsafe extern "C" fn sp_char_grid_width(
/// - `char_grid` points to a valid [SPCharGrid] /// - `char_grid` points to a valid [SPCharGrid]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_char_grid_height( pub unsafe extern "C" fn sp_char_grid_height(
char_grid: NonNull<CharGrid>, char_grid: *const SPCharGrid,
) -> usize { ) -> usize {
unsafe { char_grid.as_ref().height() } assert!(!char_grid.is_null());
unsafe { (*char_grid).0.height() }
} }

View file

@ -2,11 +2,11 @@
//! //!
//! prefix `sp_command_` //! prefix `sp_command_`
use crate::SPBitVec; use crate::{
use servicepoint::{ SPBitVec, SPBitmap, SPBrightnessGrid, SPCharGrid, SPCompressionCode,
BinaryOperation, Bitmap, BrightnessGrid, CharGrid, CompressionCode, SPCp437Grid, SPPacket,
Cp437Grid, GlobalBrightnessCommand, Packet, TypedCommand,
}; };
use servicepoint::{BinaryOperation, GlobalBrightnessCommand};
use std::ptr::NonNull; use std::ptr::NonNull;
/// A low-level display command. /// A low-level display command.
@ -23,6 +23,13 @@ use std::ptr::NonNull;
/// ``` /// ```
/// ///
/// [SPConnection]: [crate::SPConnection] /// [SPConnection]: [crate::SPConnection]
pub struct SPCommand(pub(crate) servicepoint::TypedCommand);
impl Clone for SPCommand {
fn clone(&self) -> Self {
SPCommand(self.0.clone())
}
}
/// Tries to turn a [SPPacket] into a [SPCommand]. /// Tries to turn a [SPPacket] into a [SPCommand].
/// ///
@ -45,12 +52,12 @@ use std::ptr::NonNull;
/// by explicitly calling `sp_command_free`. /// by explicitly calling `sp_command_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_try_from_packet( pub unsafe extern "C" fn sp_command_try_from_packet(
packet: NonNull<Packet>, packet: *mut SPPacket,
) -> *mut TypedCommand { ) -> *mut SPCommand {
let packet = *unsafe { Box::from_raw(packet.as_ptr()) }; let packet = *unsafe { Box::from_raw(packet) };
match servicepoint::TypedCommand::try_from(packet) { match servicepoint::TypedCommand::try_from(packet.0) {
Err(_) => std::ptr::null_mut(), Err(_) => std::ptr::null_mut(),
Ok(command) => Box::into_raw(Box::new(command)), Ok(command) => Box::into_raw(Box::new(SPCommand(command))),
} }
} }
@ -72,9 +79,10 @@ pub unsafe extern "C" fn sp_command_try_from_packet(
/// by explicitly calling `sp_command_free`. /// by explicitly calling `sp_command_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_clone( pub unsafe extern "C" fn sp_command_clone(
command: NonNull<TypedCommand>, command: *const SPCommand,
) -> NonNull<TypedCommand> { ) -> NonNull<SPCommand> {
let result = Box::new(unsafe { command.as_ref().clone() }); assert!(!command.is_null());
let result = Box::new(unsafe { (*command).clone() });
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -97,8 +105,8 @@ pub unsafe extern "C" fn sp_command_clone(
/// - the returned [SPCommand] instance is freed in some way, either by using a consuming function or /// - the returned [SPCommand] instance is freed in some way, either by using a consuming function or
/// by explicitly calling `sp_command_free`. /// by explicitly calling `sp_command_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_clear() -> NonNull<TypedCommand> { pub unsafe extern "C" fn sp_command_clear() -> NonNull<SPCommand> {
let result = Box::new(servicepoint::ClearCommand.into()); let result = Box::new(SPCommand(servicepoint::ClearCommand.into()));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -115,8 +123,8 @@ pub unsafe extern "C" fn sp_command_clear() -> NonNull<TypedCommand> {
/// - the returned [SPCommand] instance is freed in some way, either by using a consuming function or /// - the returned [SPCommand] instance is freed in some way, either by using a consuming function or
/// by explicitly calling `sp_command_free`. /// by explicitly calling `sp_command_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_hard_reset() -> NonNull<TypedCommand> { pub unsafe extern "C" fn sp_command_hard_reset() -> NonNull<SPCommand> {
let result = Box::new(servicepoint::HardResetCommand.into()); let result = Box::new(SPCommand(servicepoint::HardResetCommand.into()));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -131,8 +139,8 @@ pub unsafe extern "C" fn sp_command_hard_reset() -> NonNull<TypedCommand> {
/// - the returned [SPCommand] instance is freed in some way, either by using a consuming function or /// - the returned [SPCommand] instance is freed in some way, either by using a consuming function or
/// by explicitly calling `sp_command_free`. /// by explicitly calling `sp_command_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_fade_out() -> NonNull<TypedCommand> { pub unsafe extern "C" fn sp_command_fade_out() -> NonNull<SPCommand> {
let result = Box::new(servicepoint::FadeOutCommand.into()); let result = Box::new(SPCommand(servicepoint::FadeOutCommand.into()));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -153,10 +161,11 @@ pub unsafe extern "C" fn sp_command_fade_out() -> NonNull<TypedCommand> {
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_brightness( pub unsafe extern "C" fn sp_command_brightness(
brightness: u8, brightness: u8,
) -> NonNull<TypedCommand> { ) -> NonNull<SPCommand> {
let brightness = servicepoint::Brightness::try_from(brightness) let brightness = servicepoint::Brightness::try_from(brightness)
.expect("invalid brightness"); .expect("invalid brightness");
let result = Box::new(GlobalBrightnessCommand::from(brightness).into()); let result =
Box::new(SPCommand(GlobalBrightnessCommand::from(brightness).into()));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -182,16 +191,17 @@ pub unsafe extern "C" fn sp_command_brightness(
pub unsafe extern "C" fn sp_command_char_brightness( pub unsafe extern "C" fn sp_command_char_brightness(
x: usize, x: usize,
y: usize, y: usize,
grid: NonNull<BrightnessGrid>, grid: *mut SPBrightnessGrid,
) -> NonNull<TypedCommand> { ) -> NonNull<SPCommand> {
let grid = unsafe { *Box::from_raw(grid.as_ptr()) }; assert!(!grid.is_null());
let result = Box::new( let byte_grid = unsafe { *Box::from_raw(grid) };
let result = Box::new(SPCommand(
servicepoint::BrightnessGridCommand { servicepoint::BrightnessGridCommand {
origin: servicepoint::Origin::new(x, y), origin: servicepoint::Origin::new(x, y),
grid, grid: byte_grid.0,
} }
.into(), .into(),
); ));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -223,9 +233,9 @@ pub unsafe extern "C" fn sp_command_char_brightness(
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_bitmap_linear( pub unsafe extern "C" fn sp_command_bitmap_linear(
offset: usize, offset: usize,
bit_vec: NonNull<SPBitVec>, bit_vec: *mut SPBitVec,
compression: CompressionCode, compression: SPCompressionCode,
) -> *mut TypedCommand { ) -> *mut SPCommand {
unsafe { unsafe {
sp_command_bitmap_linear_internal( sp_command_bitmap_linear_internal(
offset, offset,
@ -264,9 +274,9 @@ pub unsafe extern "C" fn sp_command_bitmap_linear(
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_bitmap_linear_and( pub unsafe extern "C" fn sp_command_bitmap_linear_and(
offset: usize, offset: usize,
bit_vec: NonNull<SPBitVec>, bit_vec: *mut SPBitVec,
compression: CompressionCode, compression: SPCompressionCode,
) -> *mut TypedCommand { ) -> *mut SPCommand {
unsafe { unsafe {
sp_command_bitmap_linear_internal( sp_command_bitmap_linear_internal(
offset, offset,
@ -305,9 +315,9 @@ pub unsafe extern "C" fn sp_command_bitmap_linear_and(
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_bitmap_linear_or( pub unsafe extern "C" fn sp_command_bitmap_linear_or(
offset: usize, offset: usize,
bit_vec: NonNull<SPBitVec>, bit_vec: *mut SPBitVec,
compression: CompressionCode, compression: SPCompressionCode,
) -> *mut TypedCommand { ) -> *mut SPCommand {
unsafe { unsafe {
sp_command_bitmap_linear_internal( sp_command_bitmap_linear_internal(
offset, offset,
@ -346,9 +356,9 @@ pub unsafe extern "C" fn sp_command_bitmap_linear_or(
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_bitmap_linear_xor( pub unsafe extern "C" fn sp_command_bitmap_linear_xor(
offset: usize, offset: usize,
bit_vec: NonNull<SPBitVec>, bit_vec: *mut SPBitVec,
compression: CompressionCode, compression: SPCompressionCode,
) -> *mut TypedCommand { ) -> *mut SPCommand {
unsafe { unsafe {
sp_command_bitmap_linear_internal( sp_command_bitmap_linear_internal(
offset, offset,
@ -362,22 +372,25 @@ pub unsafe extern "C" fn sp_command_bitmap_linear_xor(
#[inline] #[inline]
unsafe fn sp_command_bitmap_linear_internal( unsafe fn sp_command_bitmap_linear_internal(
offset: usize, offset: usize,
bit_vec: NonNull<SPBitVec>, bit_vec: *mut SPBitVec,
compression: CompressionCode, compression: SPCompressionCode,
operation: BinaryOperation, operation: BinaryOperation,
) -> *mut TypedCommand { ) -> *mut SPCommand {
let bit_vec = unsafe { *Box::from_raw(bit_vec.as_ptr()) }; assert!(!bit_vec.is_null());
let bit_vec = unsafe { *Box::from_raw(bit_vec) };
let compression = match compression.try_into() { let compression = match compression.try_into() {
Ok(compression) => compression, Ok(compression) => compression,
Err(_) => return std::ptr::null_mut(), Err(_) => return std::ptr::null_mut(),
}; };
let command = servicepoint::BitVecCommand { let command = SPCommand(
offset, servicepoint::BitVecCommand {
operation, offset,
bitvec: bit_vec.0, operation,
compression, bitvec: bit_vec.into(),
} compression,
.into(); }
.into(),
);
Box::leak(Box::new(command)) Box::leak(Box::new(command))
} }
@ -403,16 +416,17 @@ unsafe fn sp_command_bitmap_linear_internal(
pub unsafe extern "C" fn sp_command_cp437_data( pub unsafe extern "C" fn sp_command_cp437_data(
x: usize, x: usize,
y: usize, y: usize,
grid: NonNull<Cp437Grid>, grid: *mut SPCp437Grid,
) -> NonNull<TypedCommand> { ) -> NonNull<SPCommand> {
let grid = *unsafe { Box::from_raw(grid.as_ptr()) }; assert!(!grid.is_null());
let result = Box::new( let grid = *unsafe { Box::from_raw(grid) };
let result = Box::new(SPCommand(
servicepoint::Cp437GridCommand { servicepoint::Cp437GridCommand {
origin: servicepoint::Origin::new(x, y), origin: servicepoint::Origin::new(x, y),
grid, grid: grid.0,
} }
.into(), .into(),
); ));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -438,16 +452,17 @@ pub unsafe extern "C" fn sp_command_cp437_data(
pub unsafe extern "C" fn sp_command_utf8_data( pub unsafe extern "C" fn sp_command_utf8_data(
x: usize, x: usize,
y: usize, y: usize,
grid: NonNull<CharGrid>, grid: *mut SPCharGrid,
) -> NonNull<TypedCommand> { ) -> NonNull<SPCommand> {
let grid = unsafe { *Box::from_raw(grid.as_ptr()) }; assert!(!grid.is_null());
let result = Box::new( let grid = unsafe { *Box::from_raw(grid) };
let result = Box::new(SPCommand(
servicepoint::CharGridCommand { servicepoint::CharGridCommand {
origin: servicepoint::Origin::new(x, y), origin: servicepoint::Origin::new(x, y),
grid, grid: grid.0,
} }
.into(), .into(),
); ));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -475,20 +490,23 @@ pub unsafe extern "C" fn sp_command_utf8_data(
pub unsafe extern "C" fn sp_command_bitmap_linear_win( pub unsafe extern "C" fn sp_command_bitmap_linear_win(
x: usize, x: usize,
y: usize, y: usize,
bitmap: NonNull<Bitmap>, bitmap: *mut SPBitmap,
compression: CompressionCode, compression: SPCompressionCode,
) -> *mut TypedCommand { ) -> *mut SPCommand {
let bitmap = unsafe { *Box::from_raw(bitmap.as_ptr()) }; assert!(!bitmap.is_null());
let bitmap = unsafe { *Box::from_raw(bitmap) }.0;
let compression = match compression.try_into() { let compression = match compression.try_into() {
Ok(compression) => compression, Ok(compression) => compression,
Err(_) => return std::ptr::null_mut(), Err(_) => return std::ptr::null_mut(),
}; };
let command = servicepoint::BitmapCommand { let command = SPCommand(
origin: servicepoint::Origin::new(x, y), servicepoint::BitmapCommand {
bitmap, origin: servicepoint::Origin::new(x, y),
compression, bitmap,
} compression,
.into(); }
.into(),
);
Box::leak(Box::new(command)) Box::leak(Box::new(command))
} }
@ -513,6 +531,7 @@ pub unsafe extern "C" fn sp_command_bitmap_linear_win(
/// - `command` is not used concurrently or after this call /// - `command` is not used concurrently or after this call
/// - `command` was not passed to another consuming function, e.g. to create a [SPPacket] /// - `command` was not passed to another consuming function, e.g. to create a [SPPacket]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_command_free(command: NonNull<TypedCommand>) { pub unsafe extern "C" fn sp_command_free(command: *mut SPCommand) {
_ = unsafe { Box::from_raw(command.as_ptr()) }; assert!(!command.is_null());
_ = unsafe { Box::from_raw(command) };
} }

View file

@ -1,20 +1,21 @@
//! C functions for interacting with [SPConnection]s //! C functions for interacting with [SPConnection]s
//! //!
//! prefix `sp_connection_` //! prefix `sp_connection_`
//!
//! A connection to the display.
//!
//! # Examples
//!
//! ```C
//! CConnection connection = sp_connection_open("172.23.42.29:2342");
//! if (connection != NULL)
//! sp_connection_send_command(connection, sp_command_clear());
//! ```
use servicepoint::{Connection, Packet, TypedCommand, UdpConnection}; use crate::{SPCommand, SPPacket};
use servicepoint::Connection;
use std::ffi::{c_char, CStr}; use std::ffi::{c_char, CStr};
use std::ptr::NonNull;
/// A connection to the display.
///
/// # Examples
///
/// ```C
/// CConnection connection = sp_connection_open("172.23.42.29:2342");
/// if (connection != NULL)
/// sp_connection_send_command(connection, sp_command_clear());
/// ```
pub struct SPConnection(pub(crate) servicepoint::UdpConnection);
/// Creates a new instance of [SPConnection]. /// Creates a new instance of [SPConnection].
/// ///
@ -32,31 +33,20 @@ use std::ptr::NonNull;
/// by explicitly calling `sp_connection_free`. /// by explicitly calling `sp_connection_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_connection_open( pub unsafe extern "C" fn sp_connection_open(
host: NonNull<c_char>, host: *const c_char,
) -> *mut UdpConnection { ) -> *mut SPConnection {
let host = unsafe { CStr::from_ptr(host.as_ptr()) } assert!(!host.is_null());
let host = unsafe { CStr::from_ptr(host) }
.to_str() .to_str()
.expect("Bad encoding"); .expect("Bad encoding");
let connection = match UdpConnection::open(host) { let connection = match servicepoint::UdpConnection::open(host) {
Err(_) => return std::ptr::null_mut(), Err(_) => return std::ptr::null_mut(),
Ok(value) => value, Ok(value) => value,
}; };
Box::into_raw(Box::new(connection)) Box::into_raw(Box::new(SPConnection(connection)))
} }
//#[no_mangle]
//pub unsafe extern "C" fn sp_connection_open_ipv4(
// host: SocketAddrV4,
//) -> *mut SPConnection {
// let connection = match servicepoint::UdpConnection::open(host) {
// Err(_) => return std::ptr::null_mut(),
// Ok(value) => value,
// };
//
// Box::into_raw(Box::new(SPConnection(connection)))
//}
// /// Creates a new instance of [SPUdpConnection] for testing that does not actually send anything. // /// Creates a new instance of [SPUdpConnection] for testing that does not actually send anything.
// /// // ///
// /// returns: a new instance. Will never return NULL. // /// returns: a new instance. Will never return NULL.
@ -93,11 +83,13 @@ pub unsafe extern "C" fn sp_connection_open(
/// - `packet` is not used concurrently or after this call /// - `packet` is not used concurrently or after this call
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_connection_send_packet( pub unsafe extern "C" fn sp_connection_send_packet(
connection: NonNull<UdpConnection>, connection: *const SPConnection,
packet: NonNull<Packet>, packet: *mut SPPacket,
) -> bool { ) -> bool {
let packet = unsafe { Box::from_raw(packet.as_ptr()) }; assert!(!connection.is_null());
unsafe { connection.as_ref().send(*packet) }.is_ok() assert!(!packet.is_null());
let packet = unsafe { Box::from_raw(packet) };
unsafe { (*connection).0.send((*packet).0) }.is_ok()
} }
/// Sends a [SPCommand] to the display using the [SPConnection]. /// Sends a [SPCommand] to the display using the [SPConnection].
@ -120,11 +112,13 @@ pub unsafe extern "C" fn sp_connection_send_packet(
/// - `command` is not used concurrently or after this call /// - `command` is not used concurrently or after this call
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_connection_send_command( pub unsafe extern "C" fn sp_connection_send_command(
connection: NonNull<UdpConnection>, connection: *const SPConnection,
command: NonNull<TypedCommand>, command: *mut SPCommand,
) -> bool { ) -> bool {
let command = *unsafe { Box::from_raw(command.as_ptr()) }; assert!(!connection.is_null());
unsafe { connection.as_ref().send(command) }.is_ok() assert!(!command.is_null());
let command = (*unsafe { Box::from_raw(command) }).0;
unsafe { (*connection).0.send(command) }.is_ok()
} }
/// Closes and deallocates a [SPConnection]. /// Closes and deallocates a [SPConnection].
@ -140,8 +134,7 @@ pub unsafe extern "C" fn sp_connection_send_command(
/// - `connection` points to a valid [SPConnection] /// - `connection` points to a valid [SPConnection]
/// - `connection` is not used concurrently or after this call /// - `connection` is not used concurrently or after this call
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_connection_free( pub unsafe extern "C" fn sp_connection_free(connection: *mut SPConnection) {
connection: NonNull<UdpConnection>, assert!(!connection.is_null());
) { _ = unsafe { Box::from_raw(connection) };
_ = unsafe { Box::from_raw(connection.as_ptr()) };
} }

48
src/constants.rs Normal file
View file

@ -0,0 +1,48 @@
//! re-exported constants for use in C
use servicepoint::CompressionCode;
use std::time::Duration;
/// size of a single tile in one dimension
pub const SP_TILE_SIZE: usize = 8;
/// Display tile count in the x-direction
pub const SP_TILE_WIDTH: usize = 56;
/// Display tile count in the y-direction
pub const SP_TILE_HEIGHT: usize = 20;
/// Display width in pixels
pub const SP_PIXEL_WIDTH: usize = SP_TILE_WIDTH * SP_TILE_SIZE;
/// Display height in pixels
pub const SP_PIXEL_HEIGHT: usize = SP_TILE_HEIGHT * SP_TILE_SIZE;
/// pixel count on whole screen
pub const SP_PIXEL_COUNT: usize = SP_PIXEL_WIDTH * SP_PIXEL_HEIGHT;
/// Actual hardware limit is around 28-29ms/frame. Rounded up for less dropped packets.
pub const SP_FRAME_PACING_MS: u128 = Duration::from_millis(30).as_millis();
/// Specifies the kind of compression to use.
#[repr(u16)]
pub enum SPCompressionCode {
/// no compression
Uncompressed = 0x0,
/// compress using flate2 with zlib header
Zlib = 0x677a,
/// compress using bzip2
Bzip2 = 0x627a,
/// compress using lzma
Lzma = 0x6c7a,
/// compress using Zstandard
Zstd = 0x7a73,
}
impl TryFrom<SPCompressionCode> for CompressionCode {
type Error = ();
fn try_from(value: SPCompressionCode) -> Result<Self, Self::Error> {
CompressionCode::try_from(value as u16).map_err(|_| ())
}
}

View file

@ -1,25 +1,31 @@
//! C functions for interacting with [SPCp437Grid]s //! C functions for interacting with [SPCp437Grid]s
//! //!
//! prefix `sp_cp437_grid_` //! prefix `sp_cp437_grid_`
//!
//!
//! A C-wrapper for grid containing codepage 437 characters.
//!
//! The encoding is currently not enforced.
//!
//! # Examples
//!
//! ```C
//! Cp437Grid grid = sp_cp437_grid_new(4, 3);
//! sp_cp437_grid_fill(grid, '?');
//! sp_cp437_grid_set(grid, 0, 0, '!');
//! sp_cp437_grid_free(grid);
//! ```
use crate::SPByteSlice; use crate::SPByteSlice;
use servicepoint::{Cp437Grid, DataRef, Grid}; use servicepoint::{DataRef, Grid};
use std::ptr::NonNull; use std::ptr::NonNull;
/// A C-wrapper for grid containing codepage 437 characters.
///
/// The encoding is currently not enforced.
///
/// # Examples
///
/// ```C
/// Cp437Grid grid = sp_cp437_grid_new(4, 3);
/// sp_cp437_grid_fill(grid, '?');
/// sp_cp437_grid_set(grid, 0, 0, '!');
/// sp_cp437_grid_free(grid);
/// ```
pub struct SPCp437Grid(pub(crate) servicepoint::Cp437Grid);
impl Clone for SPCp437Grid {
fn clone(&self) -> Self {
SPCp437Grid(self.0.clone())
}
}
/// Creates a new [SPCp437Grid] with the specified dimensions. /// Creates a new [SPCp437Grid] with the specified dimensions.
/// ///
/// returns: [SPCp437Grid] initialized to 0. Will never return NULL. /// returns: [SPCp437Grid] initialized to 0. Will never return NULL.
@ -34,8 +40,9 @@ use std::ptr::NonNull;
pub unsafe extern "C" fn sp_cp437_grid_new( pub unsafe extern "C" fn sp_cp437_grid_new(
width: usize, width: usize,
height: usize, height: usize,
) -> NonNull<Cp437Grid> { ) -> NonNull<SPCp437Grid> {
let result = Box::new(Cp437Grid::new(width, height)); let result =
Box::new(SPCp437Grid(servicepoint::Cp437Grid::new(width, height)));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -60,12 +67,14 @@ pub unsafe extern "C" fn sp_cp437_grid_new(
pub unsafe extern "C" fn sp_cp437_grid_load( pub unsafe extern "C" fn sp_cp437_grid_load(
width: usize, width: usize,
height: usize, height: usize,
data: SPByteSlice, data: *const u8,
) -> *mut Cp437Grid { data_length: usize,
let data = unsafe { data.as_slice() }; ) -> *mut SPCp437Grid {
let grid = Cp437Grid::load(width, height, data); assert!(data.is_null());
let data = unsafe { std::slice::from_raw_parts(data, data_length) };
let grid = servicepoint::Cp437Grid::load(width, height, data);
if let Some(grid) = grid { if let Some(grid) = grid {
Box::leak(Box::new(grid)) Box::leak(Box::new(SPCp437Grid(grid)))
} else { } else {
std::ptr::null_mut() std::ptr::null_mut()
} }
@ -89,9 +98,10 @@ pub unsafe extern "C" fn sp_cp437_grid_load(
/// by explicitly calling `sp_cp437_grid_free`. /// by explicitly calling `sp_cp437_grid_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_clone( pub unsafe extern "C" fn sp_cp437_grid_clone(
cp437_grid: NonNull<Cp437Grid>, cp437_grid: *const SPCp437Grid,
) -> NonNull<Cp437Grid> { ) -> NonNull<SPCp437Grid> {
let result = Box::new(unsafe { cp437_grid.as_ref().clone() }); assert!(!cp437_grid.is_null());
let result = Box::new(unsafe { (*cp437_grid).clone() });
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -111,8 +121,9 @@ pub unsafe extern "C" fn sp_cp437_grid_clone(
/// ///
/// [SPCommand]: [crate::SPCommand] /// [SPCommand]: [crate::SPCommand]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_free(cp437_grid: NonNull<Cp437Grid>) { pub unsafe extern "C" fn sp_cp437_grid_free(cp437_grid: *mut SPCp437Grid) {
_ = unsafe { Box::from_raw(cp437_grid.as_ptr()) }; assert!(!cp437_grid.is_null());
_ = unsafe { Box::from_raw(cp437_grid) };
} }
/// Gets the current value at the specified position. /// Gets the current value at the specified position.
@ -135,11 +146,12 @@ pub unsafe extern "C" fn sp_cp437_grid_free(cp437_grid: NonNull<Cp437Grid>) {
/// - `cp437_grid` is not written to concurrently /// - `cp437_grid` is not written to concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_get( pub unsafe extern "C" fn sp_cp437_grid_get(
cp437_grid: NonNull<Cp437Grid>, cp437_grid: *const SPCp437Grid,
x: usize, x: usize,
y: usize, y: usize,
) -> u8 { ) -> u8 {
unsafe { cp437_grid.as_ref().get(x, y) } assert!(!cp437_grid.is_null());
unsafe { (*cp437_grid).0.get(x, y) }
} }
/// Sets the value of the specified position in the [SPCp437Grid]. /// Sets the value of the specified position in the [SPCp437Grid].
@ -167,12 +179,13 @@ pub unsafe extern "C" fn sp_cp437_grid_get(
/// [SPBitVec]: [crate::SPBitVec] /// [SPBitVec]: [crate::SPBitVec]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_set( pub unsafe extern "C" fn sp_cp437_grid_set(
cp437_grid: NonNull<Cp437Grid>, cp437_grid: *mut SPCp437Grid,
x: usize, x: usize,
y: usize, y: usize,
value: u8, value: u8,
) { ) {
unsafe { (*cp437_grid.as_ptr()).set(x, y, value) }; assert!(!cp437_grid.is_null());
unsafe { (*cp437_grid).0.set(x, y, value) };
} }
/// Sets the value of all cells in the [SPCp437Grid]. /// Sets the value of all cells in the [SPCp437Grid].
@ -194,10 +207,11 @@ pub unsafe extern "C" fn sp_cp437_grid_set(
/// - `cp437_grid` is not written to or read from concurrently /// - `cp437_grid` is not written to or read from concurrently
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_fill( pub unsafe extern "C" fn sp_cp437_grid_fill(
cp437_grid: NonNull<Cp437Grid>, cp437_grid: *mut SPCp437Grid,
value: u8, value: u8,
) { ) {
unsafe { (*cp437_grid.as_ptr()).fill(value) }; assert!(!cp437_grid.is_null());
unsafe { (*cp437_grid).0.fill(value) };
} }
/// Gets the width of the [SPCp437Grid] instance. /// Gets the width of the [SPCp437Grid] instance.
@ -217,9 +231,10 @@ pub unsafe extern "C" fn sp_cp437_grid_fill(
/// - `cp437_grid` points to a valid [SPCp437Grid] /// - `cp437_grid` points to a valid [SPCp437Grid]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_width( pub unsafe extern "C" fn sp_cp437_grid_width(
cp437_grid: NonNull<Cp437Grid>, cp437_grid: *const SPCp437Grid,
) -> usize { ) -> usize {
unsafe { cp437_grid.as_ref().width() } assert!(!cp437_grid.is_null());
unsafe { (*cp437_grid).0.width() }
} }
/// Gets the height of the [SPCp437Grid] instance. /// Gets the height of the [SPCp437Grid] instance.
@ -239,9 +254,10 @@ pub unsafe extern "C" fn sp_cp437_grid_width(
/// - `cp437_grid` points to a valid [SPCp437Grid] /// - `cp437_grid` points to a valid [SPCp437Grid]
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_height( pub unsafe extern "C" fn sp_cp437_grid_height(
cp437_grid: NonNull<Cp437Grid>, cp437_grid: *const SPCp437Grid,
) -> usize { ) -> usize {
unsafe { cp437_grid.as_ref().height() } assert!(!cp437_grid.is_null());
unsafe { (*cp437_grid).0.height() }
} }
/// Gets an unsafe reference to the data of the [SPCp437Grid] instance. /// Gets an unsafe reference to the data of the [SPCp437Grid] instance.
@ -261,7 +277,11 @@ pub unsafe extern "C" fn sp_cp437_grid_height(
/// - the returned memory range is never accessed concurrently, either via the [SPCp437Grid] or directly /// - the returned memory range is never accessed concurrently, either via the [SPCp437Grid] or directly
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_unsafe_data_ref( pub unsafe extern "C" fn sp_cp437_grid_unsafe_data_ref(
cp437_grid: NonNull<Cp437Grid>, cp437_grid: *mut SPCp437Grid,
) -> SPByteSlice { ) -> SPByteSlice {
unsafe { SPByteSlice::from_slice((*cp437_grid.as_ptr()).data_ref_mut()) } let data = unsafe { (*cp437_grid).0.data_ref_mut() };
SPByteSlice {
start: NonNull::new(data.as_mut_ptr_range().start).unwrap(),
length: data.len(),
}
} }

View file

@ -32,6 +32,7 @@ pub use crate::byte_slice::*;
pub use crate::char_grid::*; pub use crate::char_grid::*;
pub use crate::command::*; pub use crate::command::*;
pub use crate::connection::*; pub use crate::connection::*;
pub use crate::constants::*;
pub use crate::cp437_grid::*; pub use crate::cp437_grid::*;
pub use crate::packet::*; pub use crate::packet::*;
@ -42,10 +43,6 @@ mod byte_slice;
mod char_grid; mod char_grid;
mod command; mod command;
mod connection; mod connection;
mod constants;
mod cp437_grid; mod cp437_grid;
mod packet; mod packet;
use std::time::Duration;
/// Actual hardware limit is around 28-29ms/frame. Rounded up for less dropped packets.
pub const SP_FRAME_PACING_MS: u128 = Duration::from_millis(30).as_millis();

View file

@ -1,14 +1,14 @@
//! C functions for interacting with [SPPacket]s //! C functions for interacting with [SPPacket]s
//! //!
//! prefix `sp_packet_` //! prefix `sp_packet_`
//!
//!
//! The raw packet
use crate::SPByteSlice;
use servicepoint::{Header, Packet, TypedCommand};
use std::ptr::NonNull; use std::ptr::NonNull;
use crate::SPCommand;
/// The raw packet
pub struct SPPacket(pub(crate) servicepoint::Packet);
/// Turns a [SPCommand] into a [SPPacket]. /// Turns a [SPCommand] into a [SPPacket].
/// The [SPCommand] gets consumed. /// The [SPCommand] gets consumed.
/// ///
@ -28,11 +28,12 @@ use std::ptr::NonNull;
/// by explicitly calling `sp_packet_free`. /// by explicitly calling `sp_packet_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_packet_from_command( pub unsafe extern "C" fn sp_packet_from_command(
command: NonNull<TypedCommand>, command: *mut SPCommand,
) -> *mut Packet { ) -> *mut SPPacket {
let command = unsafe { *Box::from_raw(command.as_ptr()) }; assert!(!command.is_null());
if let Ok(packet) = command.try_into() { let command = unsafe { *Box::from_raw(command) };
Box::leak(Box::new(packet)) if let Ok(packet) = command.0.try_into() {
Box::leak(Box::new(SPPacket(packet)))
} else { } else {
std::ptr::null_mut() std::ptr::null_mut()
} }
@ -55,11 +56,15 @@ pub unsafe extern "C" fn sp_packet_from_command(
/// - the returned [SPPacket] instance is freed in some way, either by using a consuming function or /// - the returned [SPPacket] instance is freed in some way, either by using a consuming function or
/// by explicitly calling `sp_packet_free`. /// by explicitly calling `sp_packet_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_packet_try_load(data: SPByteSlice) -> *mut Packet { pub unsafe extern "C" fn sp_packet_try_load(
let data = unsafe { data.as_slice() }; data: *const u8,
length: usize,
) -> *mut SPPacket {
assert!(!data.is_null());
let data = unsafe { std::slice::from_raw_parts(data, length) };
match servicepoint::Packet::try_from(data) { match servicepoint::Packet::try_from(data) {
Err(_) => std::ptr::null_mut(), Err(_) => std::ptr::null_mut(),
Ok(packet) => Box::into_raw(Box::new(packet)), Ok(packet) => Box::into_raw(Box::new(SPPacket(packet))),
} }
} }
@ -89,50 +94,36 @@ pub unsafe extern "C" fn sp_packet_try_load(data: SPByteSlice) -> *mut Packet {
/// by explicitly calling [sp_packet_free]. /// by explicitly calling [sp_packet_free].
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_packet_from_parts( pub unsafe extern "C" fn sp_packet_from_parts(
header: Header, command_code: u16,
payload: *const SPByteSlice, a: u16,
) -> NonNull<Packet> { b: u16,
c: u16,
d: u16,
payload: *const u8,
payload_len: usize,
) -> NonNull<SPPacket> {
assert_eq!(payload.is_null(), payload_len == 0);
let payload = if payload.is_null() { let payload = if payload.is_null() {
vec![] vec![]
} else { } else {
let payload = unsafe { (*payload).as_slice() }; let payload =
unsafe { std::slice::from_raw_parts(payload, payload_len) };
Vec::from(payload) Vec::from(payload)
}; };
let packet = Box::new(Packet { header, payload }); let packet = servicepoint::Packet {
NonNull::from(Box::leak(packet)) header: servicepoint::Header {
} command_code,
a,
#[no_mangle] b,
pub unsafe extern "C" fn sp_packet_get_header( c,
packet: NonNull<Packet>, d,
) -> NonNull<Header> { },
NonNull::from(&mut unsafe { (*packet.as_ptr()).header }) payload,
} };
let result = Box::new(SPPacket(packet));
#[no_mangle] NonNull::from(Box::leak(result))
pub unsafe extern "C" fn sp_packet_get_payload(
packet: NonNull<Packet>,
) -> SPByteSlice {
unsafe { SPByteSlice::from_slice(&mut *(*packet.as_ptr()).payload) }
}
#[no_mangle]
pub unsafe extern "C" fn sp_packet_set_payload(
packet: NonNull<Packet>,
data: SPByteSlice,
) {
unsafe { (*packet.as_ptr()).payload = data.as_slice().to_vec() }
}
#[no_mangle]
pub unsafe extern "C" fn sp_packet_write_to(
packet: NonNull<Packet>,
buffer: SPByteSlice,
) {
unsafe {
packet.as_ref().serialize_to(buffer.as_slice_mut());
}
} }
/// Clones a [SPPacket]. /// Clones a [SPPacket].
@ -153,9 +144,10 @@ pub unsafe extern "C" fn sp_packet_write_to(
/// by explicitly calling `sp_packet_free`. /// by explicitly calling `sp_packet_free`.
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_packet_clone( pub unsafe extern "C" fn sp_packet_clone(
packet: NonNull<Packet>, packet: *const SPPacket,
) -> NonNull<Packet> { ) -> NonNull<SPPacket> {
let result = Box::new(unsafe { packet.as_ref().clone() }); assert!(!packet.is_null());
let result = Box::new(SPPacket(unsafe { (*packet).0.clone() }));
NonNull::from(Box::leak(result)) NonNull::from(Box::leak(result))
} }
@ -172,6 +164,7 @@ pub unsafe extern "C" fn sp_packet_clone(
/// - `packet` points to a valid [SPPacket] /// - `packet` points to a valid [SPPacket]
/// - `packet` is not used concurrently or after this call /// - `packet` is not used concurrently or after this call
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn sp_packet_free(packet: NonNull<Packet>) { pub unsafe extern "C" fn sp_packet_free(packet: *mut SPPacket) {
_ = unsafe { Box::from_raw(packet.as_ptr()) } assert!(!packet.is_null());
_ = unsafe { Box::from_raw(packet) }
} }