rename to servicepoint, new dir structure, WIP build.rs

This commit is contained in:
Vinzenz Schroeter 2024-05-25 11:16:37 +02:00
parent e9dc4b59d2
commit f2d98af532
61 changed files with 751 additions and 140 deletions

167
crates/servicepoint/Cargo.lock generated Normal file
View file

@ -0,0 +1,167 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "adler"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "bzip2"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8"
dependencies = [
"bzip2-sys",
"libc",
]
[[package]]
name = "bzip2-sys"
version = "0.1.11+1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "736a955f3fa7875102d57c82b8cac37ec45224a07fd32d58f9f7a186b6cd4cdc"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "cc"
version = "1.0.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "099a5357d84c4c61eb35fc8eafa9a79a902c2f76911e5747ced4e032edd8d9b4"
dependencies = [
"jobserver",
"libc",
"once_cell",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "crc32fast"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3855a8a784b474f333699ef2bbca9db2c4a1f6d9088a90a2d25b1eb53111eaa"
dependencies = [
"cfg-if",
]
[[package]]
name = "flate2"
version = "1.0.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "jobserver"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2b099aaa34a9751c5bf0878add70444e1ed2dd73f347be99003d4577277de6e"
dependencies = [
"libc",
]
[[package]]
name = "libc"
version = "0.2.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346"
[[package]]
name = "log"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
[[package]]
name = "lz4"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e9e2dd86df36ce760a60f6ff6ad526f7ba1f14ba0356f8254fb6905e6494df1"
dependencies = [
"libc",
"lz4-sys",
]
[[package]]
name = "lz4-sys"
version = "1.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57d27b317e207b10f69f5e75494119e391a96f48861ae870d1da6edac98ca900"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "miniz_oxide"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7"
dependencies = [
"adler",
]
[[package]]
name = "once_cell"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "pkg-config"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec"
[[package]]
name = "servicepoint2"
version = "0.2.0"
dependencies = [
"bzip2",
"flate2",
"log",
"lz4",
"zstd",
]
[[package]]
name = "zstd"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d789b1514203a1120ad2429eae43a7bd32b90976a7bb8a05f7ec02fa88cc23a"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "7.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cd99b45c6bc03a018c8b8a86025678c87e55526064e38f9df301989dce7ec0a"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.0.10+zstd.1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa"
dependencies = [
"cc",
"pkg-config",
]

View file

@ -0,0 +1,29 @@
[package]
name = "servicepoint"
version = "0.4.2"
publish = true
edition = "2021"
license = "GPL-3.0-or-later"
description = "A rust library for the CCCB Service Point Display."
homepage = "https://docs.rs/crate/servicepoint"
repository = "https://github.com/cccb/servicepoint"
readme = "../README.md"
[lib]
crate-type = ["staticlib", "rlib", "cdylib"]
[dependencies]
log = "0.4"
flate2 = { version = "1.0", optional = true }
bzip2 = { version = "0.4", optional = true }
zstd = { version = "0.13", optional = true }
rust-lzma = { version = "0.6.0", optional = true }
[features]
default = ["compression_lzma", "c_api"]
compression_zlib = ["dep:flate2"]
compression_bzip2 = ["dep:bzip2"]
compression_lzma = ["dep:rust-lzma"]
compression_zstd = ["dep:zstd"]
all_compressions = ["compression_zlib", "compression_bzip2", "compression_lzma", "compression_zstd"]
c_api = []

View file

@ -0,0 +1,317 @@
use crate::DataRef;
/// A vector of bits
#[derive(Debug, Clone, PartialEq)]
pub struct BitVec {
size: usize,
data: Vec<u8>,
}
impl BitVec {
/// Create a new bit vector.
///
/// # Arguments
///
/// * `size`: size in bits. Must be dividable by 8.
///
/// returns: bit vector with all bits set to false.
///
/// # Panics
///
/// When size is not a multiple of 8.
#[must_use]
pub fn new(size: usize) -> BitVec {
assert_eq!(size % 8, 0);
Self {
size,
data: vec![0; size / 8],
}
}
/// Sets the value of a bit.
///
/// # Arguments
///
/// * `index`: the bit index to edit
/// * `value`: the value to set the bit to
///
/// returns: old value of the bit
pub fn set(&mut self, index: usize, value: bool) -> bool {
let (byte_index, bit_mask) = self.get_indexes(index);
let byte = self.data[byte_index];
let old_value = byte & bit_mask != 0;
self.data[byte_index] = if value {
byte | bit_mask
} else {
byte & (u8::MAX ^ bit_mask)
};
old_value
}
/// Gets the value of a bit.
///
/// # Arguments
///
/// * `index`: the bit index to read
///
/// returns: value of the bit
#[must_use]
pub fn get(&self, index: usize) -> bool {
let (byte_index, bit_mask) = self.get_indexes(index);
self.data[byte_index] & bit_mask != 0
}
/// Sets all bits to the specified value
///
/// # Arguments
///
/// * `value`: the value to set all bits to
///
/// # Examples
/// ```
/// use servicepoint::BitVec;
/// let mut vec = BitVec::new(8);
/// vec.fill(true);
/// ```
pub fn fill(&mut self, value: bool) {
let byte: u8 = if value { 0xFF } else { 0x00 };
self.data.fill(byte);
}
/// Gets the length in bits
#[must_use]
pub fn len(&self) -> usize {
self.size
}
/// returns true if length is 0.
#[must_use]
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Calculates the byte index and bitmask for a specific bit in the vector
fn get_indexes(&self, bit_index: usize) -> (usize, u8) {
assert!(
bit_index < self.size,
"bit index {bit_index} is outside of range 0..<{}",
self.size
);
let byte_index = bit_index / 8;
let bit_in_byte_index = 7 - bit_index % 8;
let bit_mask: u8 = 1 << bit_in_byte_index;
(byte_index, bit_mask)
}
}
impl DataRef for BitVec {
fn data_ref_mut(&mut self) -> &mut [u8] {
self.data.as_mut_slice()
}
fn data_ref(&self) -> &[u8] {
self.data.as_slice()
}
}
impl From<BitVec> for Vec<u8> {
/// Turns the `BitVec` into the underlying `Vec<u8>`
fn from(value: BitVec) -> Self {
value.data
}
}
impl From<&[u8]> for BitVec {
/// Interpret the data as a series of bits and load then into a new `BitVec` instance.
fn from(value: &[u8]) -> Self {
Self {
size: value.len() * 8,
data: Vec::from(value),
}
}
}
#[cfg(feature = "c_api")]
pub mod c_api {
use crate::{BitVec, CByteSlice, DataRef};
/// Creates a new `BitVec` instance.
/// The returned instance has to be freed with `bit_vec_dealloc`.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_new(size: usize) -> *mut BitVec {
Box::into_raw(Box::new(BitVec::new(size)))
}
/// Loads a `BitVec` from the provided data.
/// The returned instance has to be freed with `bit_vec_dealloc`.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_load(
data: *const u8,
data_length: usize,
) -> *mut BitVec {
let data = std::slice::from_raw_parts(data, data_length);
Box::into_raw(Box::new(BitVec::from(data)))
}
/// Clones a `BitVec`.
/// The returned instance has to be freed with `bit_vec_dealloc`.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_clone(
this: *const BitVec,
) -> *mut BitVec {
Box::into_raw(Box::new((*this).clone()))
}
/// Deallocates a `BitVec`.
///
/// Note: do not call this if the grid has been consumed in another way, e.g. to create a command.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_dealloc(this: *mut BitVec) {
_ = Box::from_raw(this);
}
/// Gets the value of a bit from the `BitVec`.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_get(
this: *const BitVec,
index: usize,
) -> bool {
(*this).get(index)
}
/// Sets the value of a bit in the `BitVec`.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_set(
this: *mut BitVec,
index: usize,
value: bool,
) -> bool {
(*this).set(index, value)
}
/// Sets the value of all bits in the `BitVec`.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_fill(this: *mut BitVec, value: bool) {
(*this).fill(value)
}
/// Gets the length of the `BitVec` in bits.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_len(this: *const BitVec) -> usize {
(*this).len()
}
/// Returns true if length is 0.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_is_empty(this: *const BitVec) -> bool {
(*this).is_empty()
}
/// Gets an unsafe reference to the data of the `BitVec` instance.
///
/// ## Safety
///
/// The caller has to make sure to never access the returned memory after the `BitVec`
/// instance has been consumed or manually deallocated.
///
/// Reading and writing concurrently to either the original instance or the returned data will
/// result in undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn sp2_bit_vec_unsafe_data_ref(
this: *mut BitVec,
) -> CByteSlice {
let data = (*this).data_ref_mut();
CByteSlice {
start: data.as_mut_ptr_range().start,
length: data.len(),
}
}
}
#[cfg(test)]
mod tests {
use crate::{BitVec, DataRef};
#[test]
fn fill() {
let mut vec = BitVec::new(8 * 3);
assert_eq!(vec.data, [0x00, 0x00, 0x00]);
vec.fill(true);
assert_eq!(vec.data, [0xFF, 0xFF, 0xFF]);
vec.fill(false);
assert_eq!(vec.data, [0x00, 0x00, 0x00]);
}
#[test]
fn get_set() {
let mut vec = BitVec::new(8 * 3);
assert!(!vec.get(1));
assert!(!vec.get(11));
vec.set(1, true);
vec.set(11, true);
assert_eq!(vec.data, [0x40, 0x10, 0x00]);
assert!(!vec.get(0));
assert!(vec.get(1));
assert!(vec.get(11));
}
#[test]
fn load() {
let mut vec = BitVec::new(8 * 3);
vec.set(6, true);
vec.set(7, true);
vec.set(8, true);
vec.set(9, true);
vec.set(10, true);
vec.set(vec.len() - 1, true);
assert_eq!(vec.data, [0x03, 0xE0, 0x01]);
let data: Vec<u8> = vec.into();
let vec = BitVec::from(&*data);
assert_eq!(vec.data, [0x03, 0xE0, 0x01]);
}
#[test]
fn mut_data_ref() {
let mut vec = BitVec::new(8 * 3);
let data_ref = vec.data_ref_mut();
data_ref.copy_from_slice(&[0x40, 0x10, 0x00]);
assert_eq!(vec.data, [0x40, 0x10, 0x00]);
assert!(vec.get(1));
}
#[test]
fn is_empty() {
let vec = BitVec::new(8 * 3);
assert!(!vec.is_empty());
let vec = BitVec::new(0);
assert!(vec.is_empty());
}
#[test]
fn get_returns_old() {
let mut vec = BitVec::new(8);
assert!(!vec.set(1, true));
assert!(vec.set(1, true));
assert!(vec.set(1, false));
assert!(!vec.set(1, false));
}
#[test]
fn debug_print() {
let vec = BitVec::new(8 * 3);
format!("{vec:?}");
}
}

View file

@ -0,0 +1,279 @@
use crate::{DataRef, Grid};
/// A 2D grid of bytes
#[derive(Debug, Clone, PartialEq)]
pub struct ByteGrid {
width: usize,
height: usize,
data: Vec<u8>,
}
impl ByteGrid {
/// Loads a `ByteGrid` with the specified dimensions from the provided data.
///
/// returns: `ByteGrid` that contains a copy of the provided data
///
/// # Panics
///
/// - when the dimensions and data size do not match exactly.
#[must_use]
pub fn load(width: usize, height: usize, data: &[u8]) -> Self {
assert_eq!(width * height, data.len());
Self {
data: Vec::from(data),
width,
height,
}
}
fn check_indexes(&self, x: usize, y: usize) {
assert!(
x < self.width,
"cannot access byte {x}-{y} because x is outside of bounds 0..{}",
self.width
);
assert!(
y < self.height,
"cannot access byte {x}-{y} because y is outside of bounds 0..{}",
self.height
);
}
}
impl Grid<u8> for ByteGrid {
/// Creates a new `ByteGrid` with the specified dimensions.
///
/// returns: `ByteGrid` initialized to 0.
fn new(width: usize, height: usize) -> Self {
Self {
data: vec![0; width * height],
width,
height,
}
}
fn set(&mut self, x: usize, y: usize, value: u8) -> u8 {
self.check_indexes(x, y);
let pos = &mut self.data[x + y * self.width];
let old_val = *pos;
*pos = value;
old_val
}
fn get(&self, x: usize, y: usize) -> u8 {
self.check_indexes(x, y);
self.data[x + y * self.width]
}
fn fill(&mut self, value: u8) {
self.data.fill(value);
}
fn width(&self) -> usize {
self.width
}
fn height(&self) -> usize {
self.height
}
fn window(&self, x: usize, y: usize, w: usize, h: usize) -> Self {
let mut win = Self::new(w, h);
for win_x in 0..w {
for win_y in 0..h {
let value = self.get(x + win_x, y + win_y);
win.set(win_x, win_y, value);
}
}
win
}
}
impl DataRef for ByteGrid {
/// Get the underlying byte rows mutable
fn data_ref_mut(&mut self) -> &mut [u8] {
self.data.as_mut_slice()
}
/// Get the underlying byte rows read only
fn data_ref(&self) -> &[u8] {
self.data.as_slice()
}
}
impl From<ByteGrid> for Vec<u8> {
/// Turn into the underlying `Vec<u8>` containing the rows of bytes.
fn from(value: ByteGrid) -> Self {
value.data
}
}
#[cfg(feature = "c_api")]
pub mod c_api {
use crate::data_ref::DataRef;
use crate::grid::Grid;
use crate::{ByteGrid, CByteSlice};
/// Creates a new `ByteGrid` instance.
/// The returned instance has to be freed with `byte_grid_dealloc`.
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_new(
width: usize,
height: usize,
) -> *mut ByteGrid {
Box::into_raw(Box::new(ByteGrid::new(width, height)))
}
/// Loads a `ByteGrid` with the specified dimensions from the provided data.
/// The returned instance has to be freed with `byte_grid_dealloc`.
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_load(
width: usize,
height: usize,
data: *const u8,
data_length: usize,
) -> *mut ByteGrid {
let data = std::slice::from_raw_parts(data, data_length);
Box::into_raw(Box::new(ByteGrid::load(width, height, data)))
}
/// Clones a `ByteGrid`.
/// The returned instance has to be freed with `byte_grid_dealloc`.
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_clone(
this: *const ByteGrid,
) -> *mut ByteGrid {
Box::into_raw(Box::new((*this).clone()))
}
/// Deallocates a `ByteGrid`.
///
/// Note: do not call this if the grid has been consumed in another way, e.g. to create a command.
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_dealloc(this: *mut ByteGrid) {
_ = Box::from_raw(this);
}
/// Get the current value at the specified position
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_get(
this: *const ByteGrid,
x: usize,
y: usize,
) -> u8 {
(*this).get(x, y)
}
/// Sets the current value at the specified position
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_set(
this: *mut ByteGrid,
x: usize,
y: usize,
value: u8,
) {
(*this).set(x, y, value);
}
/// Fills the whole `ByteGrid` with the specified value
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_fill(
this: *mut ByteGrid,
value: u8,
) {
(*this).fill(value);
}
/// Gets the width in pixels of the `ByteGrid` instance.
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_width(
this: *const ByteGrid,
) -> usize {
(*this).width
}
/// Gets the height in pixels of the `ByteGrid` instance.
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_height(
this: *const ByteGrid,
) -> usize {
(*this).height
}
/// Gets an unsafe reference to the data of the `ByteGrid` instance.
///
/// ## Safety
///
/// The caller has to make sure to never access the returned memory after the `ByteGrid`
/// instance has been consumed or manually deallocated.
///
/// Reading and writing concurrently to either the original instance or the returned data will
/// result in undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn sp2_byte_grid_unsafe_data_ref(
this: *mut ByteGrid,
) -> CByteSlice {
let data = (*this).data_ref_mut();
CByteSlice {
start: data.as_mut_ptr_range().start,
length: data.len(),
}
}
}
#[cfg(test)]
mod tests {
use crate::{ByteGrid, DataRef, Grid};
#[test]
fn fill() {
let mut grid = ByteGrid::new(2, 2);
assert_eq!(grid.data, [0x00, 0x00, 0x00, 0x00]);
grid.fill(42);
assert_eq!(grid.data, [42; 4]);
}
#[test]
fn get_set() {
let mut grid = ByteGrid::new(2, 2);
assert_eq!(grid.get(0, 0), 0);
assert_eq!(grid.get(1, 1), 0);
grid.set(0, 0, 42);
grid.set(1, 0, 23);
assert_eq!(grid.data, [42, 23, 0, 0]);
assert_eq!(grid.get(0, 0), 42);
assert_eq!(grid.get(1, 0), 23);
assert_eq!(grid.get(1, 1), 0);
}
#[test]
fn load() {
let mut grid = ByteGrid::new(2, 3);
for x in 0..grid.width {
for y in 0..grid.height {
grid.set(x, y, (x + y) as u8);
}
}
assert_eq!(grid.data, [0, 1, 1, 2, 2, 3]);
let data: Vec<u8> = grid.into();
let grid = ByteGrid::load(2, 3, &data);
assert_eq!(grid.data, [0, 1, 1, 2, 2, 3]);
}
#[test]
fn mut_data_ref() {
let mut vec = ByteGrid::new(2, 2);
let data_ref = vec.data_ref_mut();
data_ref.copy_from_slice(&[1, 2, 3, 4]);
assert_eq!(vec.data, [1, 2, 3, 4]);
assert_eq!(vec.get(1, 0), 2)
}
}

View file

@ -0,0 +1,11 @@
#[cfg(feature = "c_api")]
#[repr(C)]
/// Represents a span of memory (`&mut [u8]` ) as a struct usable by C code.
///
/// Usage of this type is inherently unsafe.
pub struct CByteSlice {
/// The start address of the memory
pub start: *mut u8,
/// The amount of memory in bytes
pub length: usize,
}

View file

@ -0,0 +1,863 @@
use crate::command_code::CommandCode;
use crate::compression::{into_compressed, into_decompressed};
use crate::{
BitVec, ByteGrid, CompressionCode, Grid, Header, Packet, PixelGrid,
TILE_SIZE,
};
/// An origin marks the top left position of a window sent to the display.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Origin(pub usize, pub usize);
impl std::ops::Add<Origin> for Origin {
type Output = Origin;
fn add(self, rhs: Origin) -> Self::Output {
let Origin(x1, y1) = self;
let Origin(x2, y2) = rhs;
Origin(x1 + x2, y1 + y2)
}
}
/// Type alias for documenting the meaning of the u16 in enum values
pub type Offset = usize;
/// Type alias for documenting the meaning of the u16 in enum values
pub type Brightness = u8;
/// A command to send to the display.
#[derive(Debug, Clone, PartialEq)]
pub enum Command {
/// Set all pixels to the off state
Clear,
/// Kills the udp daemon, usually results in a reboot of the display.
HardReset,
/// Slowly decrease brightness until off? Untested.
FadeOut,
/// Set the brightness of tiles
CharBrightness(Origin, ByteGrid),
/// Set the brightness of all tiles
Brightness(Brightness),
#[deprecated]
/// Legacy command code, gets ignored by the real display.
BitmapLegacy,
/// Set pixel data starting at the offset.
/// The contained `BitVec` is always uncompressed.
BitmapLinear(Offset, BitVec, CompressionCode),
/// Set pixel data according to an and-mask starting at the offset.
/// The contained `BitVec` is always uncompressed.
BitmapLinearAnd(Offset, BitVec, CompressionCode),
/// Set pixel data according to an or-mask starting at the offset.
/// The contained `BitVec` is always uncompressed.
BitmapLinearOr(Offset, BitVec, CompressionCode),
/// Set pixel data according to a xor-mask starting at the offset.
/// The contained `BitVec` is always uncompressed.
BitmapLinearXor(Offset, BitVec, CompressionCode),
/// Show text on the screen. Note that the byte data has to be CP437 encoded.
Cp437Data(Origin, ByteGrid),
/// Sets a window of pixels to the specified values
BitmapLinearWin(Origin, PixelGrid, CompressionCode),
}
impl From<Command> for Packet {
/// Move the `Command` into a `Packet` instance for sending.
#[allow(clippy::cast_possible_truncation)]
fn from(value: Command) -> Self {
match value {
Command::Clear => Command::command_code_only(CommandCode::Clear),
Command::FadeOut => {
Command::command_code_only(CommandCode::FadeOut)
}
Command::HardReset => {
Command::command_code_only(CommandCode::HardReset)
}
#[allow(deprecated)]
Command::BitmapLegacy => {
Command::command_code_only(CommandCode::BitmapLegacy)
}
Command::CharBrightness(Origin(x, y), grid) => Packet(
Header(
CommandCode::CharBrightness.into(),
x as u16,
y as u16,
grid.width() as u16,
grid.height() as u16,
),
grid.into(),
),
Command::Brightness(brightness) => Packet(
Header(
CommandCode::Brightness.into(),
0x00000,
0x0000,
0x0000,
0x0000,
),
vec![brightness],
),
Command::BitmapLinearWin(origin, pixels, compression) => {
bitmap_win_into_packet(origin, pixels, compression)
}
Command::BitmapLinear(offset, bits, compression) => {
Command::bitmap_linear_into_packet(
CommandCode::BitmapLinear,
offset,
compression,
bits.into(),
)
}
Command::BitmapLinearAnd(offset, bits, compression) => {
Command::bitmap_linear_into_packet(
CommandCode::BitmapLinearAnd,
offset,
compression,
bits.into(),
)
}
Command::BitmapLinearOr(offset, bits, compression) => {
Command::bitmap_linear_into_packet(
CommandCode::BitmapLinearOr,
offset,
compression,
bits.into(),
)
}
Command::BitmapLinearXor(offset, bits, compression) => {
Command::bitmap_linear_into_packet(
CommandCode::BitmapLinearXor,
offset,
compression,
bits.into(),
)
}
Command::Cp437Data(Origin(x, y), grid) => Packet(
Header(
CommandCode::Cp437Data.into(),
x as u16,
y as u16,
grid.width() as u16,
grid.height() as u16,
),
grid.into(),
),
}
}
}
#[allow(clippy::cast_possible_truncation)]
fn bitmap_win_into_packet(
origin: Origin,
pixels: PixelGrid,
compression: CompressionCode,
) -> Packet {
let Origin(pixel_x, pixel_y) = origin;
debug_assert_eq!(pixel_x % 8, 0);
debug_assert_eq!(pixels.width() % 8, 0);
let tile_x = (pixel_x / TILE_SIZE) as u16;
let tile_w = (pixels.width() / TILE_SIZE) as u16;
let pixel_h = pixels.height() as u16;
let payload = into_compressed(compression, pixels.into());
let command = match compression {
CompressionCode::Uncompressed => {
CommandCode::BitmapLinearWinUncompressed
}
#[cfg(feature = "compression_zlib")]
CompressionCode::Zlib => CommandCode::BitmapLinearWinZlib,
#[cfg(feature = "compression_bzip2")]
CompressionCode::Bzip2 => CommandCode::BitmapLinearWinBzip2,
#[cfg(feature = "compression_lzma")]
CompressionCode::Lzma => CommandCode::BitmapLinearWinLzma,
#[cfg(feature = "compression_zstd")]
CompressionCode::Zstd => CommandCode::BitmapLinearWinZstd,
};
Packet(
Header(command.into(), tile_x, pixel_y as u16, tile_w, pixel_h),
payload,
)
}
#[derive(Debug)]
/// Err values for `Command::try_from`.
#[derive(PartialEq)]
pub enum TryFromPacketError {
/// the contained command code does not correspond to a known command
InvalidCommand(u16),
/// the expected payload size was n, but size m was found
UnexpectedPayloadSize(usize, usize),
/// Header fields not needed for the command have been used.
///
/// Note that these commands would usually still work on the actual display.
ExtraneousHeaderValues,
/// The contained compression code is not known. This could be of disabled features.
InvalidCompressionCode(u16),
/// Decompression of the payload failed. This can be caused by corrupted packets.
DecompressionFailed,
}
impl TryFrom<Packet> for Command {
type Error = TryFromPacketError;
/// Try to interpret the `Packet` as one containing a `Command`
fn try_from(packet: Packet) -> Result<Self, Self::Error> {
let Packet(Header(command_u16, a, b, c, d), _) = packet;
let command_code = match CommandCode::try_from(command_u16) {
Err(()) => {
return Err(TryFromPacketError::InvalidCommand(command_u16));
}
Ok(value) => value,
};
match command_code {
CommandCode::Clear => match Self::check_command_only(packet) {
Some(err) => Err(err),
None => Ok(Command::Clear),
},
CommandCode::Brightness => {
let Packet(header, payload) = packet;
if payload.len() != 1 {
return Err(TryFromPacketError::UnexpectedPayloadSize(
1,
payload.len(),
));
}
let Header(_, a, b, c, d) = header;
if a != 0 || b != 0 || c != 0 || d != 0 {
Err(TryFromPacketError::ExtraneousHeaderValues)
} else {
Ok(Command::Brightness(payload[0]))
}
}
CommandCode::HardReset => match Self::check_command_only(packet) {
Some(err) => Err(err),
None => Ok(Command::HardReset),
},
CommandCode::FadeOut => match Self::check_command_only(packet) {
Some(err) => Err(err),
None => Ok(Command::FadeOut),
},
CommandCode::Cp437Data => {
let Packet(_, payload) = packet;
Ok(Command::Cp437Data(
Origin(a as usize, b as usize),
ByteGrid::load(c as usize, d as usize, &payload),
))
}
CommandCode::CharBrightness => {
let Packet(_, payload) = packet;
Ok(Command::CharBrightness(
Origin(a as usize, b as usize),
ByteGrid::load(c as usize, d as usize, &payload),
))
}
#[allow(deprecated)]
CommandCode::BitmapLegacy => Ok(Command::BitmapLegacy),
CommandCode::BitmapLinear => {
let (vec, compression) =
Self::packet_into_linear_bitmap(packet)?;
Ok(Command::BitmapLinear(a as Offset, vec, compression))
}
CommandCode::BitmapLinearAnd => {
let (vec, compression) =
Self::packet_into_linear_bitmap(packet)?;
Ok(Command::BitmapLinearAnd(a as Offset, vec, compression))
}
CommandCode::BitmapLinearOr => {
let (vec, compression) =
Self::packet_into_linear_bitmap(packet)?;
Ok(Command::BitmapLinearOr(a as Offset, vec, compression))
}
CommandCode::BitmapLinearXor => {
let (vec, compression) =
Self::packet_into_linear_bitmap(packet)?;
Ok(Command::BitmapLinearXor(a as Offset, vec, compression))
}
CommandCode::BitmapLinearWinUncompressed => {
Self::packet_into_bitmap_win(
packet,
CompressionCode::Uncompressed,
)
}
#[cfg(feature = "compression_zlib")]
CommandCode::BitmapLinearWinZlib => {
Self::packet_into_bitmap_win(packet, CompressionCode::Zlib)
}
#[cfg(feature = "compression_bzip2")]
CommandCode::BitmapLinearWinBzip2 => {
Self::packet_into_bitmap_win(packet, CompressionCode::Bzip2)
}
#[cfg(feature = "compression_lzma")]
CommandCode::BitmapLinearWinLzma => {
Self::packet_into_bitmap_win(packet, CompressionCode::Lzma)
}
#[cfg(feature = "compression_zstd")]
CommandCode::BitmapLinearWinZstd => {
Self::packet_into_bitmap_win(packet, CompressionCode::Zstd)
}
}
}
}
impl Command {
fn packet_into_bitmap_win(
packet: Packet,
compression: CompressionCode,
) -> Result<Command, TryFromPacketError> {
let Packet(Header(_, tiles_x, pixels_y, tile_w, pixel_h), payload) =
packet;
let payload = match into_decompressed(compression, payload) {
None => return Err(TryFromPacketError::DecompressionFailed),
Some(decompressed) => decompressed,
};
Ok(Command::BitmapLinearWin(
Origin(tiles_x as usize * TILE_SIZE, pixels_y as usize),
PixelGrid::load(
tile_w as usize * TILE_SIZE,
pixel_h as usize,
&payload,
),
compression,
))
}
/// Helper method for `BitMapLinear*`-Commands into `Packet`
#[allow(clippy::cast_possible_truncation)]
fn bitmap_linear_into_packet(
command: CommandCode,
offset: Offset,
compression: CompressionCode,
payload: Vec<u8>,
) -> Packet {
let length = payload.len() as u16;
let payload = into_compressed(compression, payload);
Packet(
Header(
command.into(),
offset as u16,
length,
compression.into(),
0,
),
payload,
)
}
/// Helper method for creating empty packets only containing the command code
fn command_code_only(code: CommandCode) -> Packet {
Packet(Header(code.into(), 0x0000, 0x0000, 0x0000, 0x0000), vec![])
}
/// Helper method for checking that a packet is empty and only contains a command code
fn check_command_only(packet: Packet) -> Option<TryFromPacketError> {
let Packet(Header(_, a, b, c, d), payload) = packet;
if !payload.is_empty() {
Some(TryFromPacketError::UnexpectedPayloadSize(0, payload.len()))
} else if a != 0 || b != 0 || c != 0 || d != 0 {
Some(TryFromPacketError::ExtraneousHeaderValues)
} else {
None
}
}
/// Helper method for Packets into `BitMapLinear*`-Commands
fn packet_into_linear_bitmap(
packet: Packet,
) -> Result<(BitVec, CompressionCode), TryFromPacketError> {
let Packet(Header(_, _, length, sub, reserved), payload) = packet;
if reserved != 0 {
return Err(TryFromPacketError::ExtraneousHeaderValues);
}
let sub = match CompressionCode::try_from(sub) {
Err(()) => {
return Err(TryFromPacketError::InvalidCompressionCode(sub));
}
Ok(value) => value,
};
let payload = match into_decompressed(sub, payload) {
None => return Err(TryFromPacketError::DecompressionFailed),
Some(value) => value,
};
if payload.len() != length as usize {
return Err(TryFromPacketError::UnexpectedPayloadSize(
length as usize,
payload.len(),
));
}
Ok((BitVec::from(&*payload), sub))
}
}
#[cfg(feature = "c_api")]
pub mod c_api {
use std::ptr::null_mut;
use crate::{
BitVec, Brightness, ByteGrid, Command, CompressionCode, Offset, Origin,
Packet, PixelGrid,
};
/// Tries to turn a `Packet` into a `Command`. The packet is gets deallocated in the process.
///
/// Returns: pointer to command or NULL
#[no_mangle]
pub unsafe extern "C" fn sp2_command_try_from_packet(
packet: *mut Packet,
) -> *mut Command {
let packet = *Box::from_raw(packet);
match Command::try_from(packet) {
Err(_) => null_mut(),
Ok(command) => Box::into_raw(Box::new(command)),
}
}
/// Clones a `Command` instance
#[no_mangle]
pub unsafe extern "C" fn sp2_command_clone(
original: *const Command,
) -> *mut Command {
Box::into_raw(Box::new((*original).clone()))
}
/// Allocates a new `Command::Clear` instance
#[no_mangle]
pub unsafe extern "C" fn sp2_command_clear() -> *mut Command {
Box::into_raw(Box::new(Command::Clear))
}
/// Allocates a new `Command::HardReset` instance
#[no_mangle]
pub unsafe extern "C" fn sp2_command_hard_reset() -> *mut Command {
Box::into_raw(Box::new(Command::HardReset))
}
/// Allocates a new `Command::FadeOut` instance
#[no_mangle]
pub unsafe extern "C" fn sp2_command_fade_out() -> *mut Command {
Box::into_raw(Box::new(Command::FadeOut))
}
/// Allocates a new `Command::Brightness` instance
#[no_mangle]
pub unsafe extern "C" fn sp2_command_brightness(
brightness: Brightness,
) -> *mut Command {
Box::into_raw(Box::new(Command::Brightness(brightness)))
}
/// Allocates a new `Command::CharBrightness` instance.
/// The passed `ByteGrid` gets deallocated in the process.
#[no_mangle]
pub unsafe extern "C" fn sp2_command_char_brightness(
x: usize,
y: usize,
byte_grid: *mut ByteGrid,
) -> *mut Command {
let byte_grid = *Box::from_raw(byte_grid);
Box::into_raw(Box::new(Command::CharBrightness(
Origin(x, y),
byte_grid,
)))
}
/// Allocates a new `Command::BitmapLinear` instance.
/// The passed `BitVec` gets deallocated in the process.
#[no_mangle]
pub unsafe extern "C" fn sp2_command_bitmap_linear(
offset: Offset,
bit_vec: *mut BitVec,
compression: CompressionCode,
) -> *mut Command {
let bit_vec = *Box::from_raw(bit_vec);
Box::into_raw(Box::new(Command::BitmapLinear(
offset,
bit_vec,
compression,
)))
}
/// Allocates a new `Command::BitmapLinearAnd` instance.
/// The passed `BitVec` gets deallocated in the process.
#[no_mangle]
pub unsafe extern "C" fn sp2_command_bitmap_linear_and(
offset: Offset,
bit_vec: *mut BitVec,
compression: CompressionCode,
) -> *mut Command {
let bit_vec = *Box::from_raw(bit_vec);
Box::into_raw(Box::new(Command::BitmapLinearAnd(
offset,
bit_vec,
compression,
)))
}
/// Allocates a new `Command::BitmapLinearOr` instance.
/// The passed `BitVec` gets deallocated in the process.
#[no_mangle]
pub unsafe extern "C" fn sp2_command_bitmap_linear_or(
offset: Offset,
bit_vec: *mut BitVec,
compression: CompressionCode,
) -> *mut Command {
let bit_vec = *Box::from_raw(bit_vec);
Box::into_raw(Box::new(Command::BitmapLinearOr(
offset,
bit_vec,
compression,
)))
}
/// Allocates a new `Command::BitmapLinearXor` instance.
/// The passed `BitVec` gets deallocated in the process.
#[no_mangle]
pub unsafe extern "C" fn sp2_command_bitmap_linear_xor(
offset: Offset,
bit_vec: *mut BitVec,
compression: CompressionCode,
) -> *mut Command {
let bit_vec = *Box::from_raw(bit_vec);
Box::into_raw(Box::new(Command::BitmapLinearXor(
offset,
bit_vec,
compression,
)))
}
/// Allocates a new `Command::Cp437Data` instance.
/// The passed `ByteGrid` gets deallocated in the process.
#[no_mangle]
pub unsafe extern "C" fn sp2_command_cp437_data(
x: usize,
y: usize,
byte_grid: *mut ByteGrid,
) -> *mut Command {
let byte_grid = *Box::from_raw(byte_grid);
Box::into_raw(Box::new(Command::Cp437Data(Origin(x, y), byte_grid)))
}
/// Allocates a new `Command::BitmapLinearWin` instance.
/// The passed `PixelGrid` gets deallocated in the process.
#[no_mangle]
pub unsafe extern "C" fn sp2_command_bitmap_linear_win(
x: usize,
y: usize,
byte_grid: *mut PixelGrid,
compression_code: CompressionCode,
) -> *mut Command {
let byte_grid = *Box::from_raw(byte_grid);
Box::into_raw(Box::new(Command::BitmapLinearWin(
Origin(x, y),
byte_grid,
compression_code,
)))
}
/// Deallocates a `Command`. Note that connection_send does this implicitly, so you only need
/// to do this if you use the library for parsing commands.
#[no_mangle]
pub unsafe extern "C" fn sp2_command_dealloc(ptr: *mut Command) {
_ = Box::from_raw(ptr);
}
}
#[cfg(test)]
mod tests {
use crate::command::TryFromPacketError;
use crate::command_code::CommandCode;
use crate::{
BitVec, ByteGrid, Command, CompressionCode, Grid, Header, Origin,
Packet, PixelGrid,
};
fn round_trip(original: Command) {
let packet: Packet = original.clone().into();
let copy: Command = match Command::try_from(packet) {
Ok(command) => command,
Err(err) => panic!("could not reload {original:?}: {err:?}"),
};
assert_eq!(copy, original);
}
fn all_compressions<'t>() -> &'t [CompressionCode] {
&[
CompressionCode::Uncompressed,
#[cfg(feature = "compression_lzma")]
CompressionCode::Lzma,
#[cfg(feature = "compression_bzip2")]
CompressionCode::Bzip2,
#[cfg(feature = "compression_zlib")]
CompressionCode::Zlib,
#[cfg(feature = "compression_zstd")]
CompressionCode::Zstd,
]
}
#[test]
fn round_trip_clear() {
round_trip(Command::Clear);
}
#[test]
fn round_trip_hard_reset() {
round_trip(Command::HardReset);
}
#[test]
fn round_trip_fade_out() {
round_trip(Command::FadeOut);
}
#[test]
fn round_trip_brightness() {
round_trip(Command::Brightness(6));
}
#[test]
#[allow(deprecated)]
fn round_trip_bitmap_legacy() {
round_trip(Command::BitmapLegacy);
}
#[test]
fn round_trip_char_brightness() {
round_trip(Command::CharBrightness(Origin(5, 2), ByteGrid::new(7, 5)));
}
#[test]
fn round_trip_cp437_data() {
round_trip(Command::Cp437Data(Origin(5, 2), ByteGrid::new(7, 5)));
}
#[test]
fn round_trip_bitmap_linear() {
for compression in all_compressions().to_owned() {
round_trip(Command::BitmapLinear(23, BitVec::new(40), compression));
round_trip(Command::BitmapLinearAnd(
23,
BitVec::new(40),
compression,
));
round_trip(Command::BitmapLinearOr(
23,
BitVec::new(40),
compression,
));
round_trip(Command::BitmapLinearXor(
23,
BitVec::new(40),
compression,
));
round_trip(Command::BitmapLinearWin(
Origin(0, 0),
PixelGrid::max_sized(),
compression,
));
}
}
#[test]
fn error_invalid_command() {
let p = Packet(Header(0xFF, 0x00, 0x00, 0x00, 0x00), vec![]);
let result = Command::try_from(p);
assert!(matches!(
result,
Err(TryFromPacketError::InvalidCommand(0xFF))
))
}
#[test]
fn error_extraneous_header_values_clear() {
let p = Packet(
Header(CommandCode::Clear.into(), 0x05, 0x00, 0x00, 0x00),
vec![],
);
let result = Command::try_from(p);
assert!(matches!(
result,
Err(TryFromPacketError::ExtraneousHeaderValues)
))
}
#[test]
fn error_extraneous_header_values_brightness() {
let p = Packet(
Header(CommandCode::Brightness.into(), 0x00, 0x13, 0x37, 0x00),
vec![5],
);
let result = Command::try_from(p);
assert!(matches!(
result,
Err(TryFromPacketError::ExtraneousHeaderValues)
))
}
#[test]
fn error_extraneous_header_hard_reset() {
let p = Packet(
Header(CommandCode::HardReset.into(), 0x00, 0x00, 0x00, 0x01),
vec![],
);
let result = Command::try_from(p);
assert!(matches!(
result,
Err(TryFromPacketError::ExtraneousHeaderValues)
))
}
#[test]
fn error_extraneous_header_fade_out() {
let p = Packet(
Header(CommandCode::FadeOut.into(), 0x10, 0x00, 0x00, 0x01),
vec![],
);
let result = Command::try_from(p);
assert!(matches!(
result,
Err(TryFromPacketError::ExtraneousHeaderValues)
))
}
#[test]
fn error_unexpected_payload() {
let p = Packet(
Header(CommandCode::FadeOut.into(), 0x00, 0x00, 0x00, 0x00),
vec![5, 7],
);
let result = Command::try_from(p);
assert!(matches!(
result,
Err(TryFromPacketError::UnexpectedPayloadSize(0, 2))
))
}
#[test]
fn error_decompression_failed_win() {
for compression in all_compressions().to_owned() {
let p: Packet = Command::BitmapLinearWin(
Origin(16, 8),
PixelGrid::new(8, 8),
compression,
)
.into();
let Packet(header, mut payload) = p;
// mangle it
for byte in payload.iter_mut() {
*byte -= *byte / 2;
}
let p = Packet(header, payload);
let result = Command::try_from(p);
if compression != CompressionCode::Uncompressed {
assert_eq!(result, Err(TryFromPacketError::DecompressionFailed))
} else {
assert!(result.is_ok());
}
}
}
#[test]
fn error_decompression_failed_and() {
for compression in all_compressions().to_owned() {
let p: Packet =
Command::BitmapLinearAnd(0, BitVec::new(8), compression).into();
let Packet(header, mut payload) = p;
// mangle it
for byte in payload.iter_mut() {
*byte -= *byte / 2;
}
let p = Packet(header, payload);
let result = Command::try_from(p);
if compression != CompressionCode::Uncompressed {
assert_eq!(result, Err(TryFromPacketError::DecompressionFailed))
} else {
// when not compressing, there is no way to detect corrupted data
assert!(result.is_ok());
}
}
}
#[test]
fn unexpected_payload_size_brightness() {
assert_eq!(
Command::try_from(Packet(
Header(CommandCode::Brightness.into(), 0, 0, 0, 0),
vec!(),
)),
Err(TryFromPacketError::UnexpectedPayloadSize(1, 0))
);
assert_eq!(
Command::try_from(Packet(
Header(CommandCode::Brightness.into(), 0, 0, 0, 0),
vec!(0, 0),
)),
Err(TryFromPacketError::UnexpectedPayloadSize(1, 2))
);
}
#[test]
fn error_reserved_used() {
let Packet(header, payload) = Command::BitmapLinear(
0,
BitVec::new(8),
CompressionCode::Uncompressed,
)
.into();
let Header(command, offset, length, sub, _reserved) = header;
let p = Packet(Header(command, offset, length, sub, 69), payload);
assert_eq!(
Command::try_from(p),
Err(TryFromPacketError::ExtraneousHeaderValues)
);
}
#[test]
fn error_invalid_compression() {
let Packet(header, payload) = Command::BitmapLinear(
0,
BitVec::new(8),
CompressionCode::Uncompressed,
)
.into();
let Header(command, offset, length, _sub, reserved) = header;
let p = Packet(Header(command, offset, length, 42, reserved), payload);
assert_eq!(
Command::try_from(p),
Err(TryFromPacketError::InvalidCompressionCode(42))
);
}
#[test]
fn error_unexpected_size() {
let Packet(header, payload) = Command::BitmapLinear(
0,
BitVec::new(8),
CompressionCode::Uncompressed,
)
.into();
let Header(command, offset, length, compression, reserved) = header;
let p = Packet(
Header(command, offset, 420, compression, reserved),
payload,
);
assert_eq!(
Command::try_from(p),
Err(TryFromPacketError::UnexpectedPayloadSize(
420,
length as usize,
))
);
}
#[test]
fn origin_add() {
assert_eq!(Origin(4, 2), Origin(1, 0) + Origin(3, 2));
}
}

View file

@ -0,0 +1,99 @@
/// The u16 command codes used for the `Commands`.
#[repr(u16)]
#[derive(Debug, Copy, Clone)]
pub(crate) enum CommandCode {
Clear = 0x0002,
Cp437Data = 0x0003,
CharBrightness = 0x0005,
Brightness = 0x0007,
HardReset = 0x000b,
FadeOut = 0x000d,
#[deprecated]
BitmapLegacy = 0x0010,
BitmapLinear = 0x0012,
BitmapLinearWinUncompressed = 0x0013,
BitmapLinearAnd = 0x0014,
BitmapLinearOr = 0x0015,
BitmapLinearXor = 0x0016,
#[cfg(feature = "compression_zlib")]
BitmapLinearWinZlib = 0x0017,
#[cfg(feature = "compression_bzip2")]
BitmapLinearWinBzip2 = 0x0018,
#[cfg(feature = "compression_lzma")]
BitmapLinearWinLzma = 0x0019,
#[cfg(feature = "compression_zstd")]
BitmapLinearWinZstd = 0x001A,
}
impl From<CommandCode> for u16 {
/// returns the u16 command code corresponding to the enum value
fn from(value: CommandCode) -> Self {
value as u16
}
}
impl TryFrom<u16> for CommandCode {
type Error = ();
/// Returns the enum value for the specified `u16` or `Error` if the code is unknown.
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
value if value == CommandCode::Clear as u16 => {
Ok(CommandCode::Clear)
}
value if value == CommandCode::Cp437Data as u16 => {
Ok(CommandCode::Cp437Data)
}
value if value == CommandCode::CharBrightness as u16 => {
Ok(CommandCode::CharBrightness)
}
value if value == CommandCode::Brightness as u16 => {
Ok(CommandCode::Brightness)
}
value if value == CommandCode::HardReset as u16 => {
Ok(CommandCode::HardReset)
}
value if value == CommandCode::FadeOut as u16 => {
Ok(CommandCode::FadeOut)
}
#[allow(deprecated)]
value if value == CommandCode::BitmapLegacy as u16 => {
Ok(CommandCode::BitmapLegacy)
}
value if value == CommandCode::BitmapLinear as u16 => {
Ok(CommandCode::BitmapLinear)
}
value
if value == CommandCode::BitmapLinearWinUncompressed as u16 =>
{
Ok(CommandCode::BitmapLinearWinUncompressed)
}
value if value == CommandCode::BitmapLinearAnd as u16 => {
Ok(CommandCode::BitmapLinearAnd)
}
value if value == CommandCode::BitmapLinearOr as u16 => {
Ok(CommandCode::BitmapLinearOr)
}
value if value == CommandCode::BitmapLinearXor as u16 => {
Ok(CommandCode::BitmapLinearXor)
}
#[cfg(feature = "compression_zstd")]
value if value == CommandCode::BitmapLinearWinZstd as u16 => {
Ok(CommandCode::BitmapLinearWinZstd)
}
#[cfg(feature = "compression_lzma")]
value if value == CommandCode::BitmapLinearWinLzma as u16 => {
Ok(CommandCode::BitmapLinearWinLzma)
}
#[cfg(feature = "compression_zlib")]
value if value == CommandCode::BitmapLinearWinZlib as u16 => {
Ok(CommandCode::BitmapLinearWinZlib)
}
#[cfg(feature = "compression_bzip2")]
value if value == CommandCode::BitmapLinearWinBzip2 as u16 => {
Ok(CommandCode::BitmapLinearWinBzip2)
}
_ => Err(()),
}
}
}

View file

@ -0,0 +1,115 @@
#[allow(unused)]
use std::io::{Read, Write};
#[cfg(feature = "compression_bzip2")]
use bzip2::read::{BzDecoder, BzEncoder};
#[cfg(feature = "compression_zlib")]
use flate2::{FlushCompress, FlushDecompress, Status};
#[cfg(feature = "compression_zstd")]
use zstd::{Decoder as ZstdDecoder, Encoder as ZstdEncoder};
use crate::{CompressionCode, Payload};
pub(crate) fn into_decompressed(
kind: CompressionCode,
payload: Payload,
) -> Option<Payload> {
match kind {
CompressionCode::Uncompressed => Some(payload),
#[cfg(feature = "compression_zlib")]
CompressionCode::Zlib => {
let mut decompress = flate2::Decompress::new(true);
let mut buffer = [0u8; 10000];
let status = match decompress.decompress(
&payload,
&mut buffer,
FlushDecompress::Finish,
) {
Err(_) => return None,
Ok(status) => status,
};
match status {
Status::Ok => None,
Status::BufError => None,
Status::StreamEnd => Some(
buffer[0..(decompress.total_out() as usize)].to_owned(),
),
}
}
#[cfg(feature = "compression_bzip2")]
CompressionCode::Bzip2 => {
let mut decoder = BzDecoder::new(&*payload);
let mut decompressed = vec![];
match decoder.read_to_end(&mut decompressed) {
Err(_) => None,
Ok(_) => Some(decompressed),
}
}
#[cfg(feature = "compression_lzma")]
CompressionCode::Lzma => match lzma::decompress(&payload) {
Err(_) => None,
Ok(decompressed) => Some(decompressed),
},
#[cfg(feature = "compression_zstd")]
CompressionCode::Zstd => {
let mut decoder = match ZstdDecoder::new(&*payload) {
Err(_) => return None,
Ok(value) => value,
};
let mut decompressed = vec![];
match decoder.read_to_end(&mut decompressed) {
Err(_) => None,
Ok(_) => Some(decompressed),
}
}
}
}
pub(crate) fn into_compressed(
kind: CompressionCode,
payload: Payload,
) -> Payload {
match kind {
CompressionCode::Uncompressed => payload,
#[cfg(feature = "compression_zlib")]
CompressionCode::Zlib => {
let mut compress =
flate2::Compress::new(flate2::Compression::fast(), true);
let mut buffer = [0u8; 10000];
match compress
.compress(&payload, &mut buffer, FlushCompress::Finish)
.expect("compress failed")
{
Status::Ok => panic!("buffer should be big enough"),
Status::BufError => panic!("BufError"),
Status::StreamEnd => {}
};
buffer[..compress.total_out() as usize].to_owned()
}
#[cfg(feature = "compression_bzip2")]
CompressionCode::Bzip2 => {
let mut encoder =
BzEncoder::new(&*payload, bzip2::Compression::fast());
let mut compressed = vec![];
match encoder.read_to_end(&mut compressed) {
Err(err) => panic!("could not compress payload: {}", err),
Ok(_) => compressed,
}
}
#[cfg(feature = "compression_lzma")]
CompressionCode::Lzma => lzma::compress(&payload, 6).unwrap(),
#[cfg(feature = "compression_zstd")]
CompressionCode::Zstd => {
let mut encoder =
ZstdEncoder::new(vec![], zstd::DEFAULT_COMPRESSION_LEVEL)
.expect("could not create encoder");
encoder
.write_all(&payload)
.expect("could not compress payload");
encoder.finish().expect("could not finish encoding")
}
}
}

View file

@ -0,0 +1,49 @@
/// Specifies the kind of compression to use. Availability depends on features.
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CompressionCode {
Uncompressed = 0x0,
#[cfg(feature = "compression_zlib")]
Zlib = 0x677a,
#[cfg(feature = "compression_bzip2")]
Bzip2 = 0x627a,
#[cfg(feature = "compression_lzma")]
Lzma = 0x6c7a,
#[cfg(feature = "compression_zstd")]
Zstd = 0x7a73,
}
impl From<CompressionCode> for u16 {
fn from(value: CompressionCode) -> Self {
value as u16
}
}
impl TryFrom<u16> for CompressionCode {
type Error = ();
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
value if value == CompressionCode::Uncompressed as u16 => {
Ok(CompressionCode::Uncompressed)
}
#[cfg(feature = "compression_zlib")]
value if value == CompressionCode::Zlib as u16 => {
Ok(CompressionCode::Zlib)
}
#[cfg(feature = "compression_bzip2")]
value if value == CompressionCode::Bzip2 as u16 => {
Ok(CompressionCode::Bzip2)
}
#[cfg(feature = "compression_lzma")]
value if value == CompressionCode::Lzma as u16 => {
Ok(CompressionCode::Lzma)
}
#[cfg(feature = "compression_zstd")]
value if value == CompressionCode::Zstd as u16 => {
Ok(CompressionCode::Zstd)
}
_ => Err(()),
}
}
}

View file

@ -0,0 +1,117 @@
use std::fmt::Debug;
use std::net::{ToSocketAddrs, UdpSocket};
use log::{debug, info};
use crate::Packet;
/// A connection to the display.
pub struct Connection {
socket: UdpSocket,
}
impl Connection {
/// Open a new UDP socket and connect to the provided host.
///
/// Note that this is UDP, which means that the open call can succeed even if the display is unreachable.
///
/// # Errors
///
/// Any errors resulting from binding the udp socket.
///
/// # Examples
/// ```rust
/// let connection = servicepoint::Connection::open("172.23.42.29:2342")
/// .expect("connection failed");
/// ```
pub fn open(addr: impl ToSocketAddrs + Debug) -> std::io::Result<Self> {
info!("connecting to {addr:?}");
let socket = UdpSocket::bind("0.0.0.0:0")?;
socket.connect(addr)?;
Ok(Self { socket })
}
/// Send something packet-like to the display. Usually this is in the form of a Command.
///
/// # Arguments
///
/// * `packet`: the packet-like to send
///
/// returns: Ok if packet was sent, otherwise socket error
///
/// # Errors
///
/// Any errors produced while sending using the underlying socket.
///
/// # Examples
///
/// ```rust
/// use servicepoint::{Command, CompressionCode, Grid, PixelGrid};
/// let connection = servicepoint::Connection::open("172.23.42.29:2342")
/// .expect("connection failed");
///
/// // turn off all pixels
/// connection.send(Command::Clear)
/// .expect("send failed");
///
/// // turn on all pixels
/// let mut pixels = PixelGrid::max_sized();
/// pixels.fill(true);
///
/// // send pixels to display
/// connection.send(Command::BitmapLinearWin(servicepoint::Origin(0, 0), pixels, CompressionCode::Uncompressed))
/// .expect("send failed");
/// ```
pub fn send(&self, packet: impl Into<Packet>) -> Result<(), std::io::Error> {
let packet = packet.into();
debug!("sending {packet:?}");
let data: Vec<u8> = packet.into();
self.socket.send(&data)?;
Ok(())
}
}
#[cfg(feature = "c_api")]
pub mod c_api {
use std::ffi::{c_char, CStr};
use std::ptr::null_mut;
use crate::{Connection, Packet};
/// Creates a new instance of Connection.
/// The returned instance has to be deallocated with `connection_dealloc`.
///
/// returns: NULL if connection fails or connected instance
///
/// Panics: bad string encoding
#[no_mangle]
pub unsafe extern "C" fn sp2_connection_open(
host: *const c_char,
) -> *mut Connection {
let host = CStr::from_ptr(host).to_str().expect("Bad encoding");
let connection = match Connection::open(host) {
Err(_) => return null_mut(),
Ok(value) => value,
};
Box::into_raw(Box::new(connection))
}
/// Sends the command instance. The instance is consumed / destroyed and cannot be used after this call.
#[no_mangle]
pub unsafe extern "C" fn sp2_connection_send(
connection: *const Connection,
command_ptr: *mut Packet,
) -> bool {
let packet = Box::from_raw(command_ptr);
(*connection).send(*packet).is_ok()
}
/// Closes and deallocates a connection instance
#[no_mangle]
pub unsafe extern "C" fn sp2_connection_dealloc(ptr: *mut Connection) {
_ = Box::from_raw(ptr);
}
}

View file

@ -0,0 +1,11 @@
/// A trait for getting the underlying raw byte slices of data containers.
///
/// The expectation is that you can create an equal instance with this data given the additional
/// metadata needed.
pub trait DataRef {
/// Get the underlying bytes writable.
fn data_ref_mut(&mut self) -> &mut [u8];
/// Get the underlying bytes read-only.
fn data_ref(&self) -> &[u8];
}

View file

@ -0,0 +1,53 @@
pub trait Grid<T> {
#[must_use]
fn new(width: usize, height: usize) -> Self;
/// Sets the value at the specified position
///
/// returns: the old value
fn set(&mut self, x: usize, y: usize, value: T) -> T;
/// Get the current value at the specified position
fn get(&self, x: usize, y: usize) -> T;
/// Sets all cells in the grid to the specified value
fn fill(&mut self, value: T);
/// the size in x-direction
fn width(&self) -> usize;
/// the height in y-direction
fn height(&self) -> usize;
/// Creates a new instance containing the specified window.
///
/// Use concrete types to avoid boxing.
///
/// # Arguments
///
/// * `x`: column of the top left cell
/// * `y`: row of the top left cell
/// * `w`: size of window in x-direction
/// * `h`: size of window in y-direction
///
/// returns: Self
///
/// # Examples
/// To avoid boxing, this example is using the concrete type `ByteGrid`.
/// ```
/// use servicepoint::{ByteGrid, Grid};
/// fn split(grid: ByteGrid) -> (ByteGrid, ByteGrid) {
/// assert!(grid.width() >= 2);
/// let split_x = grid.width() / 2;
/// let right_w = grid.width() - split_x;
///
/// let left = grid.window(0, 0, split_x, grid.height());
/// let right = grid.window(split_x, 0, right_w, grid.height());
/// (left, right)
/// }
///
/// let (l, r) = split(ByteGrid::new(9, 5));
/// ```
#[must_use]
fn window(&self, x: usize, y: usize, w: usize, h: usize) -> Self;
}

View file

@ -0,0 +1,47 @@
use std::time::Duration;
pub use crate::bit_vec::BitVec;
pub use crate::byte_grid::ByteGrid;
#[cfg(feature = "c_api")]
pub use crate::c_slice::CByteSlice;
pub use crate::command::{Brightness, Command, Offset, Origin};
pub use crate::compression_code::CompressionCode;
pub use crate::connection::Connection;
pub use crate::data_ref::DataRef;
pub use crate::grid::Grid;
pub use crate::packet::{Header, Packet, Payload};
pub use crate::pixel_grid::PixelGrid;
mod bit_vec;
mod byte_grid;
mod c_slice;
mod command;
mod command_code;
mod compression;
mod compression_code;
mod connection;
mod data_ref;
mod grid;
mod packet;
mod pixel_grid;
/// size of a single tile in one dimension
pub const TILE_SIZE: usize = 8;
/// tile count in the x-direction
pub const TILE_WIDTH: usize = 56;
/// tile count in the y-direction
pub const TILE_HEIGHT: usize = 20;
/// screen width in pixels
pub const PIXEL_WIDTH: usize = TILE_WIDTH * TILE_SIZE;
/// screen height in pixels
pub const PIXEL_HEIGHT: usize = TILE_HEIGHT * TILE_SIZE;
/// pixel count on whole screen
pub const PIXEL_COUNT: usize = PIXEL_WIDTH * PIXEL_HEIGHT;
/// Actual hardware limit is around 28-29ms/frame. Rounded up for less dropped packets.
pub const FRAME_PACING: Duration = Duration::from_millis(30);

View file

@ -0,0 +1,112 @@
use std::mem::size_of;
/// A raw header. Should probably not be used directly.
#[derive(Debug, PartialEq)]
pub struct Header(pub u16, pub u16, pub u16, pub u16, pub u16);
/// The raw payload. Should probably not be used directly.
pub type Payload = Vec<u8>;
/// The raw packet. Should probably not be used directly.
#[derive(Debug, PartialEq)]
pub struct Packet(pub Header, pub Payload);
impl From<Packet> for Vec<u8> {
/// Turn the packet into raw bytes ready to send
fn from(value: Packet) -> Self {
let Packet(Header(mode, a, b, c, d), payload) = value;
let mut packet = vec![0u8; 10 + payload.len()];
packet[0..=1].copy_from_slice(&u16::to_be_bytes(mode));
packet[2..=3].copy_from_slice(&u16::to_be_bytes(a));
packet[4..=5].copy_from_slice(&u16::to_be_bytes(b));
packet[6..=7].copy_from_slice(&u16::to_be_bytes(c));
packet[8..=9].copy_from_slice(&u16::to_be_bytes(d));
packet[10..].copy_from_slice(&payload);
packet
}
}
fn u16_from_be_slice(slice: &[u8]) -> u16 {
let mut bytes = [0u8; 2];
bytes[0] = slice[0];
bytes[1] = slice[1];
u16::from_be_bytes(bytes)
}
impl TryFrom<&[u8]> for Packet {
type Error = ();
/// Tries to interpret the bytes as a `Packet`.
///
/// returns: `Error` if slice is not long enough to be a `Packet`
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
if value.len() < size_of::<Header>() {
return Err(());
}
let mode = u16_from_be_slice(&value[0..=1]);
let a = u16_from_be_slice(&value[2..=3]);
let b = u16_from_be_slice(&value[4..=5]);
let c = u16_from_be_slice(&value[6..=7]);
let d = u16_from_be_slice(&value[8..=9]);
let payload = value[10..].to_vec();
Ok(Packet(Header(mode, a, b, c, d), payload))
}
}
#[cfg(feature = "c_api")]
mod c_api {
use std::ptr::null_mut;
use crate::{Command, Packet};
/// Turns a `Command` into a `Packet`. The command gets deallocated in the process.
#[no_mangle]
pub unsafe extern "C" fn sp2_packet_from_command(
command: *mut Command,
) -> *mut Packet {
let command = *Box::from_raw(command);
let packet = command.into();
Box::into_raw(Box::new(packet))
}
/// 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
#[no_mangle]
pub unsafe extern "C" fn sp2_packet_try_load(
data: *const u8,
length: usize,
) -> *mut Packet {
let data = std::slice::from_raw_parts(data, length);
match Packet::try_from(data) {
Err(_) => null_mut(),
Ok(packet) => Box::into_raw(Box::new(packet)),
}
}
/// Deallocates a `Packet`.
///
/// Note: do not call this if the instance has been consumed in another way, e.g. by sending it.
#[no_mangle]
pub unsafe extern "C" fn sp2_packet_dealloc(this: *mut Packet) {
_ = Box::from_raw(this)
}
}
#[cfg(test)]
mod tests {
use crate::{Header, Packet};
#[test]
fn round_trip() {
let p = Packet(Header(0, 1, 2, 3, 4), vec![42u8; 23]);
let data: Vec<u8> = p.into();
let p = Packet::try_from(&*data).unwrap();
assert_eq!(p, Packet(Header(0, 1, 2, 3, 4), vec![42u8; 23]));
}
}

View file

@ -0,0 +1,289 @@
use crate::{BitVec, DataRef, Grid, PIXEL_HEIGHT, PIXEL_WIDTH};
/// A grid of pixels stored in packed bytes.
#[derive(Debug, Clone, PartialEq)]
pub struct PixelGrid {
width: usize,
height: usize,
bit_vec: BitVec,
}
impl PixelGrid {
/// Creates a new pixel grid with the size of the whole screen.
#[must_use]
pub fn max_sized() -> Self {
Self::new(PIXEL_WIDTH, PIXEL_HEIGHT)
}
/// Loads a `PixelGrid` with the specified dimensions from the provided data.
///
/// # Arguments
///
/// * `width`: size in pixels in x-direction
/// * `height`: size in pixels in y-direction
///
/// returns: `PixelGrid` that contains a copy of the provided data
///
/// # Panics
///
/// - when the dimensions and data size do not match exactly.
/// - when the width is not dividable by 8
#[must_use]
pub fn load(width: usize, height: usize, data: &[u8]) -> Self {
assert_eq!(width % 8, 0);
assert_eq!(data.len(), height * width / 8);
Self {
width,
height,
bit_vec: BitVec::from(data),
}
}
fn check_indexes(&self, x: usize, y: usize) {
assert!(
x < self.width,
"cannot access pixel {x}-{y} because x is outside of bounds 0..{}",
self.width
);
assert!(
y < self.height,
"cannot access pixel {x}-{y} because y is outside of bounds 0..{}",
self.height
);
}
}
impl Grid<bool> for PixelGrid {
/// Creates a new `PixelGrid` with the specified dimensions.
///
/// # Arguments
///
/// * `width`: size in pixels in x-direction
/// * `height`: size in pixels in y-direction
///
/// returns: `PixelGrid` initialized to all pixels off
///
/// # Panics
///
/// - when the width is not dividable by 8
fn new(width: usize, height: usize) -> Self {
assert_eq!(width % 8, 0);
Self {
width,
height,
bit_vec: BitVec::new(width * height),
}
}
fn set(&mut self, x: usize, y: usize, value: bool) -> bool {
self.check_indexes(x, y);
self.bit_vec.set(x + y * self.width, value)
}
fn get(&self, x: usize, y: usize) -> bool {
self.bit_vec.get(x + y * self.width)
}
fn fill(&mut self, value: bool) {
self.bit_vec.fill(value);
}
fn width(&self) -> usize {
self.width
}
fn height(&self) -> usize {
self.height
}
fn window(&self, x: usize, y: usize, w: usize, h: usize) -> Self {
// TODO: how to deduplicate?
// this cannot be moved into the trait because there, Self is not Sized
let mut win = Self::new(w, h);
for win_x in 0..w {
for win_y in 0..h {
let value = self.get(x + win_x, y + win_y);
win.set(win_x, win_y, value);
}
}
win
}
}
impl DataRef for PixelGrid {
fn data_ref_mut(&mut self) -> &mut [u8] {
self.bit_vec.data_ref_mut()
}
fn data_ref(&self) -> &[u8] {
self.bit_vec.data_ref()
}
}
impl From<PixelGrid> for Vec<u8> {
/// Turns a `PixelGrid` into the underlying `Vec<u8>`.
fn from(value: PixelGrid) -> Self {
value.bit_vec.into()
}
}
#[cfg(feature = "c_api")]
pub mod c_api {
use crate::c_slice::CByteSlice;
use crate::{DataRef, Grid, PixelGrid};
/// Creates a new `PixelGrid` instance.
/// The returned instance has to be freed with `pixel_grid_dealloc`.
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_new(
width: usize,
height: usize,
) -> *mut PixelGrid {
Box::into_raw(Box::new(PixelGrid::new(width, height)))
}
/// Loads a `PixelGrid` with the specified dimensions from the provided data.
/// The returned instance has to be freed with `pixel_grid_dealloc`.
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_load(
width: usize,
height: usize,
data: *const u8,
data_length: usize,
) -> *mut PixelGrid {
let data = std::slice::from_raw_parts(data, data_length);
Box::into_raw(Box::new(PixelGrid::load(width, height, data)))
}
/// Clones a `PixelGrid`.
/// The returned instance has to be freed with `pixel_grid_dealloc`.
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_clone(
this: *const PixelGrid,
) -> *mut PixelGrid {
Box::into_raw(Box::new((*this).clone()))
}
/// Deallocates a `PixelGrid`.
///
/// Note: do not call this if the grid has been consumed in another way, e.g. to create a command.
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_dealloc(this: *mut PixelGrid) {
_ = Box::from_raw(this);
}
/// Get the current value at the specified position
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_get(
this: *const PixelGrid,
x: usize,
y: usize,
) -> bool {
(*this).get(x, y)
}
/// Sets the current value at the specified position
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_set(
this: *mut PixelGrid,
x: usize,
y: usize,
value: bool,
) {
(*this).set(x, y, value);
}
/// Fills the whole `PixelGrid` with the specified value
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_fill(
this: *mut PixelGrid,
value: bool,
) {
(*this).fill(value);
}
/// Gets the width in pixels of the `PixelGrid` instance.
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_width(
this: *const PixelGrid,
) -> usize {
(*this).width
}
/// Gets the height in pixels of the `PixelGrid` instance.
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_height(
this: *const PixelGrid,
) -> usize {
(*this).height
}
/// Gets an unsafe reference to the data of the `PixelGrid` instance.
///
/// ## Safety
///
/// The caller has to make sure to never access the returned memory after the `PixelGrid`
/// instance has been consumed or manually deallocated.
///
/// Reading and writing concurrently to either the original instance or the returned data will
/// result in undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn sp2_pixel_grid_unsafe_data_ref(
this: *mut PixelGrid,
) -> CByteSlice {
let data = (*this).data_ref_mut();
CByteSlice {
start: data.as_mut_ptr_range().start,
length: data.len(),
}
}
}
#[cfg(test)]
mod tests {
use crate::{DataRef, Grid, PixelGrid};
#[test]
fn fill() {
let mut grid = PixelGrid::new(8, 2);
assert_eq!(grid.data_ref(), [0x00, 0x00]);
grid.fill(true);
assert_eq!(grid.data_ref(), [0xFF, 0xFF]);
grid.fill(false);
assert_eq!(grid.data_ref(), [0x00, 0x00]);
}
#[test]
fn get_set() {
let mut grid = PixelGrid::new(8, 2);
assert!(!grid.get(0, 0));
assert!(!grid.get(1, 1));
grid.set(5, 0, true);
grid.set(1, 1, true);
assert_eq!(grid.data_ref(), [0x04, 0x40]);
assert!(grid.get(5, 0));
assert!(grid.get(1, 1));
assert!(!grid.get(1, 0));
}
#[test]
fn load() {
let mut grid = PixelGrid::new(8, 3);
for x in 0..grid.width {
for y in 0..grid.height {
grid.set(x, y, (x + y) % 2 == 0);
}
}
assert_eq!(grid.data_ref(), [0xAA, 0x55, 0xAA]);
let data: Vec<u8> = grid.into();
let grid = PixelGrid::load(8, 3, &data);
assert_eq!(grid.data_ref(), [0xAA, 0x55, 0xAA]);
}
}

View file

@ -0,0 +1,13 @@
[package]
name = "servicepoint_binding_c"
version = "0.4.2"
publish = false
edition = "2021"
license = "GPL-3.0-or-later"
description = "C bindings for the servicepoint crate."
homepage = "https://docs.rs/crate/servicepoint"
repository = "https://github.com/cccb/servicepoint"
readme = "../README.md"
[build-dependencies]
cbindgen = "0.26.0"

View file

@ -0,0 +1,13 @@
use std::env;
use cbindgen::{generate_with_config, Config};
fn main() {
let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let config = Config::from_file(crate_dir.clone() + "/cbindgen.toml").unwrap();
let servicepoint_dir = crate_dir.clone() + "/../servicepoint";
generate_with_config(servicepoint_dir, config)
.unwrap()
.write_to_file("servicepoint.h");
}

View file

@ -0,0 +1,35 @@
language = "C"
include_version = true
cpp_compat = true
############################ Code Style Options ################################
braces = "SameLine"
line_length = 80
tab_width = 4
documentation = true
documentation_style = "auto"
documentation_length = "full"
line_endings = "LF"
############################# Codegen Options ##################################
style = "both"
sort_by = "Name"
usize_is_size_t = true
[defines]
"feature = compression_zlib" = "SP2_FEATURE_compression_zlib"
"feature = compression_bzip2" = "SP2_FEATURE_compression_bzip2"
"feature = compression_lzma" = "SP2_FEATURE_compression_lzma"
"feature = compression_zstd" = "SP2_FEATURE_compression_zstd"
[export]
prefix = "sp2_"
[parse]
#include = ["servicepoint"]
[parse.expand]
features = ["c-api"]
all_features = true

View file

@ -0,0 +1,463 @@
/* Generated with cbindgen:0.26.0 */
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
/**
* pixel count on whole screen
*/
#define sp2_PIXEL_COUNT (sp2_PIXEL_WIDTH * sp2_PIXEL_HEIGHT)
/**
* screen height in pixels
*/
#define sp2_PIXEL_HEIGHT (sp2_TILE_HEIGHT * sp2_TILE_SIZE)
/**
* screen width in pixels
*/
#define sp2_PIXEL_WIDTH (sp2_TILE_WIDTH * sp2_TILE_SIZE)
/**
* tile count in the y-direction
*/
#define sp2_TILE_HEIGHT 20
/**
* size of a single tile in one dimension
*/
#define sp2_TILE_SIZE 8
/**
* tile count in the x-direction
*/
#define sp2_TILE_WIDTH 56
/**
* Specifies the kind of compression to use. Availability depends on features.
*/
enum sp2_CompressionCode
#ifdef __cplusplus
: uint16_t
#endif // __cplusplus
{
Uncompressed = 0,
#if defined(SP2_FEATURE_compression_zlib)
Zlib = 26490,
#endif
#if defined(SP2_FEATURE_compression_bzip2)
Bzip2 = 25210,
#endif
#if defined(SP2_FEATURE_compression_lzma)
Lzma = 27770,
#endif
#if defined(SP2_FEATURE_compression_zstd)
Zstd = 31347,
#endif
};
#ifndef __cplusplus
typedef uint16_t sp2_CompressionCode;
#endif // __cplusplus
/**
* A vector of bits
*/
typedef struct sp2_BitVec sp2_BitVec;
/**
* A 2D grid of bytes
*/
typedef struct sp2_ByteGrid sp2_ByteGrid;
/**
* A command to send to the display.
*/
typedef struct sp2_Command sp2_Command;
/**
* A connection to the display.
*/
typedef struct sp2_Connection sp2_Connection;
/**
* The raw packet. Should probably not be used directly.
*/
typedef struct sp2_Packet sp2_Packet;
/**
* A grid of pixels stored in packed bytes.
*/
typedef struct sp2_PixelGrid sp2_PixelGrid;
/**
* Represents a span of memory (`&mut [u8]` ) as a struct usable by C code.
*
* Usage of this type is inherently unsafe.
*/
typedef struct sp2_CByteSlice {
/**
* The start address of the memory
*/
uint8_t *start;
/**
* The amount of memory in bytes
*/
size_t length;
} sp2_CByteSlice;
/**
* Type alias for documenting the meaning of the u16 in enum values
*/
typedef size_t sp2_Offset;
/**
* Type alias for documenting the meaning of the u16 in enum values
*/
typedef uint8_t sp2_Brightness;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* Clones a `BitVec`.
* The returned instance has to be freed with `bit_vec_dealloc`.
*/
struct sp2_BitVec *sp2_bit_vec_clone(const struct sp2_BitVec *this_);
/**
* Deallocates a `BitVec`.
*
* Note: do not call this if the grid has been consumed in another way, e.g. to create a command.
*/
void sp2_bit_vec_dealloc(struct sp2_BitVec *this_);
/**
* Sets the value of all bits in the `BitVec`.
*/
void sp2_bit_vec_fill(struct sp2_BitVec *this_, bool value);
/**
* Gets the value of a bit from the `BitVec`.
*/
bool sp2_bit_vec_get(const struct sp2_BitVec *this_, size_t index);
/**
* Returns true if length is 0.
*/
bool sp2_bit_vec_is_empty(const struct sp2_BitVec *this_);
/**
* Gets the length of the `BitVec` in bits.
*/
size_t sp2_bit_vec_len(const struct sp2_BitVec *this_);
/**
* Loads a `BitVec` from the provided data.
* The returned instance has to be freed with `bit_vec_dealloc`.
*/
struct sp2_BitVec *sp2_bit_vec_load(const uint8_t *data, size_t data_length);
/**
* Creates a new `BitVec` instance.
* The returned instance has to be freed with `bit_vec_dealloc`.
*/
struct sp2_BitVec *sp2_bit_vec_new(size_t size);
/**
* Sets the value of a bit in the `BitVec`.
*/
bool sp2_bit_vec_set(struct sp2_BitVec *this_, size_t index, bool value);
/**
* Gets an unsafe reference to the data of the `BitVec` instance.
*
* ## Safety
*
* The caller has to make sure to never access the returned memory after the `BitVec`
* instance has been consumed or manually deallocated.
*
* Reading and writing concurrently to either the original instance or the returned data will
* result in undefined behavior.
*/
struct sp2_CByteSlice sp2_bit_vec_unsafe_data_ref(struct sp2_BitVec *this_);
/**
* Clones a `ByteGrid`.
* The returned instance has to be freed with `byte_grid_dealloc`.
*/
struct sp2_ByteGrid *sp2_byte_grid_clone(const struct sp2_ByteGrid *this_);
/**
* Deallocates a `ByteGrid`.
*
* Note: do not call this if the grid has been consumed in another way, e.g. to create a command.
*/
void sp2_byte_grid_dealloc(struct sp2_ByteGrid *this_);
/**
* Fills the whole `ByteGrid` with the specified value
*/
void sp2_byte_grid_fill(struct sp2_ByteGrid *this_, uint8_t value);
/**
* Get the current value at the specified position
*/
uint8_t sp2_byte_grid_get(const struct sp2_ByteGrid *this_, size_t x, size_t y);
/**
* Gets the height in pixels of the `ByteGrid` instance.
*/
size_t sp2_byte_grid_height(const struct sp2_ByteGrid *this_);
/**
* Loads a `ByteGrid` with the specified dimensions from the provided data.
* The returned instance has to be freed with `byte_grid_dealloc`.
*/
struct sp2_ByteGrid *sp2_byte_grid_load(size_t width,
size_t height,
const uint8_t *data,
size_t data_length);
/**
* Creates a new `ByteGrid` instance.
* The returned instance has to be freed with `byte_grid_dealloc`.
*/
struct sp2_ByteGrid *sp2_byte_grid_new(size_t width, size_t height);
/**
* Sets the current value at the specified position
*/
void sp2_byte_grid_set(struct sp2_ByteGrid *this_,
size_t x,
size_t y,
uint8_t value);
/**
* Gets an unsafe reference to the data of the `ByteGrid` instance.
*
* ## Safety
*
* The caller has to make sure to never access the returned memory after the `ByteGrid`
* instance has been consumed or manually deallocated.
*
* Reading and writing concurrently to either the original instance or the returned data will
* result in undefined behavior.
*/
struct sp2_CByteSlice sp2_byte_grid_unsafe_data_ref(struct sp2_ByteGrid *this_);
/**
* Gets the width in pixels of the `ByteGrid` instance.
*/
size_t sp2_byte_grid_width(const struct sp2_ByteGrid *this_);
/**
* Allocates a new `Command::BitmapLinear` instance.
* The passed `BitVec` gets deallocated in the process.
*/
struct sp2_Command *sp2_command_bitmap_linear(sp2_Offset offset,
struct sp2_BitVec *bit_vec,
sp2_CompressionCode compression);
/**
* Allocates a new `Command::BitmapLinearAnd` instance.
* The passed `BitVec` gets deallocated in the process.
*/
struct sp2_Command *sp2_command_bitmap_linear_and(sp2_Offset offset,
struct sp2_BitVec *bit_vec,
sp2_CompressionCode compression);
/**
* Allocates a new `Command::BitmapLinearOr` instance.
* The passed `BitVec` gets deallocated in the process.
*/
struct sp2_Command *sp2_command_bitmap_linear_or(sp2_Offset offset,
struct sp2_BitVec *bit_vec,
sp2_CompressionCode compression);
/**
* Allocates a new `Command::BitmapLinearWin` instance.
* The passed `PixelGrid` gets deallocated in the process.
*/
struct sp2_Command *sp2_command_bitmap_linear_win(size_t x,
size_t y,
struct sp2_PixelGrid *byte_grid,
sp2_CompressionCode compression_code);
/**
* Allocates a new `Command::BitmapLinearXor` instance.
* The passed `BitVec` gets deallocated in the process.
*/
struct sp2_Command *sp2_command_bitmap_linear_xor(sp2_Offset offset,
struct sp2_BitVec *bit_vec,
sp2_CompressionCode compression);
/**
* Allocates a new `Command::Brightness` instance
*/
struct sp2_Command *sp2_command_brightness(sp2_Brightness brightness);
/**
* Allocates a new `Command::CharBrightness` instance.
* The passed `ByteGrid` gets deallocated in the process.
*/
struct sp2_Command *sp2_command_char_brightness(size_t x,
size_t y,
struct sp2_ByteGrid *byte_grid);
/**
* Allocates a new `Command::Clear` instance
*/
struct sp2_Command *sp2_command_clear(void);
/**
* Clones a `Command` instance
*/
struct sp2_Command *sp2_command_clone(const struct sp2_Command *original);
/**
* Allocates a new `Command::Cp437Data` instance.
* The passed `ByteGrid` gets deallocated in the process.
*/
struct sp2_Command *sp2_command_cp437_data(size_t x,
size_t y,
struct sp2_ByteGrid *byte_grid);
/**
* Deallocates a `Command`. Note that connection_send does this implicitly, so you only need
* to do this if you use the library for parsing commands.
*/
void sp2_command_dealloc(struct sp2_Command *ptr);
/**
* Allocates a new `Command::FadeOut` instance
*/
struct sp2_Command *sp2_command_fade_out(void);
/**
* Allocates a new `Command::HardReset` instance
*/
struct sp2_Command *sp2_command_hard_reset(void);
/**
* Tries to turn a `Packet` into a `Command`. The packet is gets deallocated in the process.
*
* Returns: pointer to command or NULL
*/
struct sp2_Command *sp2_command_try_from_packet(struct sp2_Packet *packet);
/**
* Closes and deallocates a connection instance
*/
void sp2_connection_dealloc(struct sp2_Connection *ptr);
/**
* Creates a new instance of Connection.
* The returned instance has to be deallocated with `connection_dealloc`.
*
* returns: NULL if connection fails or connected instance
*
* Panics: bad string encoding
*/
struct sp2_Connection *sp2_connection_open(const char *host);
/**
* Sends the command instance. The instance is consumed / destroyed and cannot be used after this call.
*/
bool sp2_connection_send(const struct sp2_Connection *connection,
struct sp2_Packet *command_ptr);
/**
* Deallocates a `Packet`.
*
* Note: do not call this if the instance has been consumed in another way, e.g. by sending it.
*/
void sp2_packet_dealloc(struct sp2_Packet *this_);
/**
* Turns a `Command` into a `Packet`. The command gets deallocated in the process.
*/
struct sp2_Packet *sp2_packet_from_command(struct sp2_Command *command);
/**
* 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
*/
struct sp2_Packet *sp2_packet_try_load(const uint8_t *data, size_t length);
/**
* Clones a `PixelGrid`.
* The returned instance has to be freed with `pixel_grid_dealloc`.
*/
struct sp2_PixelGrid *sp2_pixel_grid_clone(const struct sp2_PixelGrid *this_);
/**
* Deallocates a `PixelGrid`.
*
* Note: do not call this if the grid has been consumed in another way, e.g. to create a command.
*/
void sp2_pixel_grid_dealloc(struct sp2_PixelGrid *this_);
/**
* Fills the whole `PixelGrid` with the specified value
*/
void sp2_pixel_grid_fill(struct sp2_PixelGrid *this_, bool value);
/**
* Get the current value at the specified position
*/
bool sp2_pixel_grid_get(const struct sp2_PixelGrid *this_, size_t x, size_t y);
/**
* Gets the height in pixels of the `PixelGrid` instance.
*/
size_t sp2_pixel_grid_height(const struct sp2_PixelGrid *this_);
/**
* Loads a `PixelGrid` with the specified dimensions from the provided data.
* The returned instance has to be freed with `pixel_grid_dealloc`.
*/
struct sp2_PixelGrid *sp2_pixel_grid_load(size_t width,
size_t height,
const uint8_t *data,
size_t data_length);
/**
* Creates a new `PixelGrid` instance.
* The returned instance has to be freed with `pixel_grid_dealloc`.
*/
struct sp2_PixelGrid *sp2_pixel_grid_new(size_t width, size_t height);
/**
* Sets the current value at the specified position
*/
void sp2_pixel_grid_set(struct sp2_PixelGrid *this_,
size_t x,
size_t y,
bool value);
/**
* Gets an unsafe reference to the data of the `PixelGrid` instance.
*
* ## Safety
*
* The caller has to make sure to never access the returned memory after the `PixelGrid`
* instance has been consumed or manually deallocated.
*
* Reading and writing concurrently to either the original instance or the returned data will
* result in undefined behavior.
*/
struct sp2_CByteSlice sp2_pixel_grid_unsafe_data_ref(struct sp2_PixelGrid *this_);
/**
* Gets the width in pixels of the `PixelGrid` instance.
*/
size_t sp2_pixel_grid_width(const struct sp2_PixelGrid *this_);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus

View file

264
crates/servicepoint_binding_cs/Cargo.lock generated Normal file
View file

@ -0,0 +1,264 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "adler"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "bzip2"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8"
dependencies = [
"bzip2-sys",
"libc",
]
[[package]]
name = "bzip2-sys"
version = "0.1.11+1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "736a955f3fa7875102d57c82b8cac37ec45224a07fd32d58f9f7a186b6cd4cdc"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "cc"
version = "1.0.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "099a5357d84c4c61eb35fc8eafa9a79a902c2f76911e5747ced4e032edd8d9b4"
dependencies = [
"jobserver",
"libc",
"once_cell",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "crc32fast"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3855a8a784b474f333699ef2bbca9db2c4a1f6d9088a90a2d25b1eb53111eaa"
dependencies = [
"cfg-if",
]
[[package]]
name = "csbindgen"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf70eb656f35e0e6956cbde31c66431c53d8a546823489719099c71525767a9c"
dependencies = [
"regex",
"syn",
]
[[package]]
name = "flate2"
version = "1.0.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "jobserver"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2b099aaa34a9751c5bf0878add70444e1ed2dd73f347be99003d4577277de6e"
dependencies = [
"libc",
]
[[package]]
name = "libc"
version = "0.2.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346"
[[package]]
name = "log"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
[[package]]
name = "lz4"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e9e2dd86df36ce760a60f6ff6ad526f7ba1f14ba0356f8254fb6905e6494df1"
dependencies = [
"libc",
"lz4-sys",
]
[[package]]
name = "lz4-sys"
version = "1.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57d27b317e207b10f69f5e75494119e391a96f48861ae870d1da6edac98ca900"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "memchr"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
[[package]]
name = "miniz_oxide"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7"
dependencies = [
"adler",
]
[[package]]
name = "once_cell"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "pkg-config"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec"
[[package]]
name = "proc-macro2"
version = "1.0.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"
[[package]]
name = "servicepoint-binding-cs"
version = "0.1.0"
dependencies = [
"csbindgen",
"servicepoint2",
]
[[package]]
name = "servicepoint2"
version = "0.2.0"
dependencies = [
"bzip2",
"flate2",
"log",
"lz4",
"zstd",
]
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "zstd"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d789b1514203a1120ad2429eae43a7bd32b90976a7bb8a05f7ec02fa88cc23a"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "7.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cd99b45c6bc03a018c8b8a86025678c87e55526064e38f9df301989dce7ec0a"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.0.10+zstd.1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa"
dependencies = [
"cc",
"pkg-config",
]

View file

@ -0,0 +1,14 @@
[package]
name = "servicepoint_binding_cs"
version = "0.4.2"
edition = "2021"
publish = false
[lib]
crate-type = ["cdylib"]
[dependencies]
servicepoint = { path = "../servicepoint", features = ["c_api"] }
[build-dependencies]
csbindgen = "1.8.0"

View file

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServicePoint", "src/ServicePoint.csproj", "{70EFFA3F-012A-4518-9627-466BEAE4252E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "lang-cs", "../examples/lang_cs/lang_cs.csproj", "{DA3B8B6E-993A-47DA-844B-F92AF520FF59}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{70EFFA3F-012A-4518-9627-466BEAE4252E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{70EFFA3F-012A-4518-9627-466BEAE4252E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{70EFFA3F-012A-4518-9627-466BEAE4252E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{70EFFA3F-012A-4518-9627-466BEAE4252E}.Release|Any CPU.Build.0 = Release|Any CPU
{DA3B8B6E-993A-47DA-844B-F92AF520FF59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DA3B8B6E-993A-47DA-844B-F92AF520FF59}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DA3B8B6E-993A-47DA-844B-F92AF520FF59}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DA3B8B6E-993A-47DA-844B-F92AF520FF59}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,19 @@
fn main() {
println!("cargo:rerun-if-changed=DOESNOTEXIST"); // rebuild every time
csbindgen::Builder::default()
.input_extern_file("../servicepoint/src/bit_vec.rs")
.input_extern_file("../servicepoint/src/byte_grid.rs")
.input_extern_file("../servicepoint/src/command.rs")
.input_extern_file("../servicepoint/src/compression_code.rs")
.input_extern_file("../servicepoint/src/connection.rs")
.input_extern_file("../servicepoint/src/pixel_grid.rs")
.input_extern_file("../servicepoint/src/lib.rs")
.input_extern_file("../servicepoint/src/c_slice.rs")
.input_extern_file("../servicepoint/src/packet.rs")
.csharp_dll_name("servicepoint")
.csharp_namespace("ServicePoint.BindGen")
.csharp_use_nint_types(true)
.csharp_class_accessibility("public")
.generate_csharp_file("src/BindGen/ServicePoint.g.cs")
.unwrap();
}

View file

@ -0,0 +1,286 @@
// <auto-generated>
// This code is generated by csbindgen.
// DON'T CHANGE THIS DIRECTLY.
// </auto-generated>
#pragma warning disable CS8500
#pragma warning disable CS8981
using System;
using System.Runtime.InteropServices;
namespace ServicePoint.BindGen
{
public static unsafe partial class NativeMethods
{
const string __DllName = "servicepoint";
/// <summary>Creates a new `BitVec` instance. The returned instance has to be freed with `bit_vec_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_new", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern BitVec* sp2_bit_vec_new(nuint size);
/// <summary>Loads a `BitVec` from the provided data. The returned instance has to be freed with `bit_vec_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_load", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern BitVec* sp2_bit_vec_load(byte* data, nuint data_length);
/// <summary>Clones a `BitVec`. The returned instance has to be freed with `bit_vec_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_clone", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern BitVec* sp2_bit_vec_clone(BitVec* @this);
/// <summary>Deallocates a `BitVec`. Note: do not call this if the grid has been consumed in another way, e.g. to create a command.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_bit_vec_dealloc(BitVec* @this);
/// <summary>Gets the value of a bit from the `BitVec`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_get", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_bit_vec_get(BitVec* @this, nuint index);
/// <summary>Sets the value of a bit in the `BitVec`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_set", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_bit_vec_set(BitVec* @this, nuint index, [MarshalAs(UnmanagedType.U1)] bool value);
/// <summary>Sets the value of all bits in the `BitVec`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_fill", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_bit_vec_fill(BitVec* @this, [MarshalAs(UnmanagedType.U1)] bool value);
/// <summary>Gets the length of the `BitVec` in bits.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_len", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_bit_vec_len(BitVec* @this);
/// <summary>Returns true if length is 0.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_is_empty", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_bit_vec_is_empty(BitVec* @this);
/// <summary>Gets an unsafe reference to the data of the `BitVec` instance. ## Safety The caller has to make sure to never access the returned memory after the `BitVec` instance has been consumed or manually deallocated. Reading and writing concurrently to either the original instance or the returned data will result in undefined behavior.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_unsafe_data_ref", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern CByteSlice sp2_bit_vec_unsafe_data_ref(BitVec* @this);
/// <summary>Creates a new `ByteGrid` instance. The returned instance has to be freed with `byte_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_new", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ByteGrid* sp2_byte_grid_new(nuint width, nuint height);
/// <summary>Loads a `ByteGrid` with the specified dimensions from the provided data. The returned instance has to be freed with `byte_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_load", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ByteGrid* sp2_byte_grid_load(nuint width, nuint height, byte* data, nuint data_length);
/// <summary>Clones a `ByteGrid`. The returned instance has to be freed with `byte_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_clone", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ByteGrid* sp2_byte_grid_clone(ByteGrid* @this);
/// <summary>Deallocates a `ByteGrid`. Note: do not call this if the grid has been consumed in another way, e.g. to create a command.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_byte_grid_dealloc(ByteGrid* @this);
/// <summary>Get the current value at the specified position</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_get", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern byte sp2_byte_grid_get(ByteGrid* @this, nuint x, nuint y);
/// <summary>Sets the current value at the specified position</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_set", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_byte_grid_set(ByteGrid* @this, nuint x, nuint y, byte value);
/// <summary>Fills the whole `ByteGrid` with the specified value</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_fill", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_byte_grid_fill(ByteGrid* @this, byte value);
/// <summary>Gets the width in pixels of the `ByteGrid` instance.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_width", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_byte_grid_width(ByteGrid* @this);
/// <summary>Gets the height in pixels of the `ByteGrid` instance.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_height", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_byte_grid_height(ByteGrid* @this);
/// <summary>Gets an unsafe reference to the data of the `ByteGrid` instance. ## Safety The caller has to make sure to never access the returned memory after the `ByteGrid` instance has been consumed or manually deallocated. Reading and writing concurrently to either the original instance or the returned data will result in undefined behavior.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_unsafe_data_ref", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern CByteSlice sp2_byte_grid_unsafe_data_ref(ByteGrid* @this);
/// <summary>Tries to turn a `Packet` into a `Command`. The packet is gets deallocated in the process. Returns: pointer to command or NULL</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_try_from_packet", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_try_from_packet(Packet* packet);
/// <summary>Clones a `Command` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_clone", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_clone(Command* original);
/// <summary>Allocates a new `Command::Clear` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_clear", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_clear();
/// <summary>Allocates a new `Command::HardReset` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_hard_reset", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_hard_reset();
/// <summary>Allocates a new `Command::FadeOut` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_fade_out", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_fade_out();
/// <summary>Allocates a new `Command::Brightness` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_brightness", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_brightness(byte brightness);
/// <summary>Allocates a new `Command::CharBrightness` instance. The passed `ByteGrid` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_char_brightness", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_char_brightness(nuint x, nuint y, ByteGrid* byte_grid);
/// <summary>Allocates a new `Command::BitmapLinear` instance. The passed `BitVec` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear(nuint offset, BitVec* bit_vec, CompressionCode compression);
/// <summary>Allocates a new `Command::BitmapLinearAnd` instance. The passed `BitVec` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear_and", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear_and(nuint offset, BitVec* bit_vec, CompressionCode compression);
/// <summary>Allocates a new `Command::BitmapLinearOr` instance. The passed `BitVec` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear_or", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear_or(nuint offset, BitVec* bit_vec, CompressionCode compression);
/// <summary>Allocates a new `Command::BitmapLinearXor` instance. The passed `BitVec` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear_xor", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear_xor(nuint offset, BitVec* bit_vec, CompressionCode compression);
/// <summary>Allocates a new `Command::Cp437Data` instance. The passed `ByteGrid` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_cp437_data", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_cp437_data(nuint x, nuint y, ByteGrid* byte_grid);
/// <summary>Allocates a new `Command::BitmapLinearWin` instance. The passed `PixelGrid` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear_win", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear_win(nuint x, nuint y, PixelGrid* byte_grid, CompressionCode compression_code);
/// <summary>Deallocates a `Command`. Note that connection_send does this implicitly, so you only need to do this if you use the library for parsing commands.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_command_dealloc(Command* ptr);
/// <summary>Creates a new instance of Connection. The returned instance has to be deallocated with `connection_dealloc`. returns: NULL if connection fails or connected instance Panics: bad string encoding</summary>
[DllImport(__DllName, EntryPoint = "sp2_connection_open", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Connection* sp2_connection_open(byte* host);
/// <summary>Sends the command instance. The instance is consumed / destroyed and cannot be used after this call.</summary>
[DllImport(__DllName, EntryPoint = "sp2_connection_send", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_connection_send(Connection* connection, Packet* command_ptr);
/// <summary>Closes and deallocates a connection instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_connection_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_connection_dealloc(Connection* ptr);
/// <summary>Creates a new `PixelGrid` instance. The returned instance has to be freed with `pixel_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_new", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern PixelGrid* sp2_pixel_grid_new(nuint width, nuint height);
/// <summary>Loads a `PixelGrid` with the specified dimensions from the provided data. The returned instance has to be freed with `pixel_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_load", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern PixelGrid* sp2_pixel_grid_load(nuint width, nuint height, byte* data, nuint data_length);
/// <summary>Clones a `PixelGrid`. The returned instance has to be freed with `pixel_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_clone", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern PixelGrid* sp2_pixel_grid_clone(PixelGrid* @this);
/// <summary>Deallocates a `PixelGrid`. Note: do not call this if the grid has been consumed in another way, e.g. to create a command.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_pixel_grid_dealloc(PixelGrid* @this);
/// <summary>Get the current value at the specified position</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_get", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_pixel_grid_get(PixelGrid* @this, nuint x, nuint y);
/// <summary>Sets the current value at the specified position</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_set", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_pixel_grid_set(PixelGrid* @this, nuint x, nuint y, [MarshalAs(UnmanagedType.U1)] bool value);
/// <summary>Fills the whole `PixelGrid` with the specified value</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_fill", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_pixel_grid_fill(PixelGrid* @this, [MarshalAs(UnmanagedType.U1)] bool value);
/// <summary>Gets the width in pixels of the `PixelGrid` instance.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_width", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_pixel_grid_width(PixelGrid* @this);
/// <summary>Gets the height in pixels of the `PixelGrid` instance.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_height", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_pixel_grid_height(PixelGrid* @this);
/// <summary>Gets an unsafe reference to the data of the `PixelGrid` instance. ## Safety The caller has to make sure to never access the returned memory after the `PixelGrid` instance has been consumed or manually deallocated. Reading and writing concurrently to either the original instance or the returned data will result in undefined behavior.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_unsafe_data_ref", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern CByteSlice sp2_pixel_grid_unsafe_data_ref(PixelGrid* @this);
/// <summary>Turns a `Command` into a `Packet`. The command gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_packet_from_command", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Packet* sp2_packet_from_command(Command* command);
/// <summary>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</summary>
[DllImport(__DllName, EntryPoint = "sp2_packet_try_load", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Packet* sp2_packet_try_load(byte* data, nuint length);
/// <summary>Deallocates a `Packet`. Note: do not call this if the instance has been consumed in another way, e.g. by sending it.</summary>
[DllImport(__DllName, EntryPoint = "sp2_packet_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_packet_dealloc(Packet* @this);
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct BitVec
{
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct ByteGrid
{
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct Connection
{
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct PixelGrid
{
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct CByteSlice
{
public byte* start;
public nuint length;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct Packet
{
}
public enum Command
{
Clear,
HardReset,
FadeOut,
CharBrightness,
Brightness,
BitmapLegacy,
BitmapLinear,
BitmapLinearAnd,
BitmapLinearOr,
BitmapLinearXor,
Cp437Data,
BitmapLinearWin,
}
public enum CompressionCode : ushort
{
Uncompressed = 0,
Zlib = 26490,
Bzip2 = 25210,
Lzma = 27770,
Zstd = 31347,
}
}

View file

@ -0,0 +1,286 @@
// <auto-generated>
// This code is generated by csbindgen.
// DON'T CHANGE THIS DIRECTLY.
// </auto-generated>
#pragma warning disable CS8500
#pragma warning disable CS8981
using System;
using System.Runtime.InteropServices;
namespace ServicePoint.BindGen
{
public static unsafe partial class NativeMethods
{
const string __DllName = "servicepoint";
/// <summary>Creates a new `BitVec` instance. The returned instance has to be freed with `bit_vec_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_new", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern BitVec* sp2_bit_vec_new(nuint size);
/// <summary>Loads a `BitVec` from the provided data. The returned instance has to be freed with `bit_vec_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_load", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern BitVec* sp2_bit_vec_load(byte* data, nuint data_length);
/// <summary>Clones a `BitVec`. The returned instance has to be freed with `bit_vec_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_clone", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern BitVec* sp2_bit_vec_clone(BitVec* @this);
/// <summary>Deallocates a `BitVec`. Note: do not call this if the grid has been consumed in another way, e.g. to create a command.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_bit_vec_dealloc(BitVec* @this);
/// <summary>Gets the value of a bit from the `BitVec`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_get", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_bit_vec_get(BitVec* @this, nuint index);
/// <summary>Sets the value of a bit in the `BitVec`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_set", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_bit_vec_set(BitVec* @this, nuint index, [MarshalAs(UnmanagedType.U1)] bool value);
/// <summary>Sets the value of all bits in the `BitVec`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_fill", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_bit_vec_fill(BitVec* @this, [MarshalAs(UnmanagedType.U1)] bool value);
/// <summary>Gets the length of the `BitVec` in bits.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_len", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_bit_vec_len(BitVec* @this);
/// <summary>Returns true if length is 0.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_is_empty", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_bit_vec_is_empty(BitVec* @this);
/// <summary>Gets an unsafe reference to the data of the `BitVec` instance. ## Safety The caller has to make sure to never access the returned memory after the `BitVec` instance has been consumed or manually deallocated. Reading and writing concurrently to either the original instance or the returned data will result in undefined behavior.</summary>
[DllImport(__DllName, EntryPoint = "sp2_bit_vec_unsafe_data_ref", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern CByteSlice sp2_bit_vec_unsafe_data_ref(BitVec* @this);
/// <summary>Creates a new `ByteGrid` instance. The returned instance has to be freed with `byte_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_new", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ByteGrid* sp2_byte_grid_new(nuint width, nuint height);
/// <summary>Loads a `ByteGrid` with the specified dimensions from the provided data. The returned instance has to be freed with `byte_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_load", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ByteGrid* sp2_byte_grid_load(nuint width, nuint height, byte* data, nuint data_length);
/// <summary>Clones a `ByteGrid`. The returned instance has to be freed with `byte_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_clone", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern ByteGrid* sp2_byte_grid_clone(ByteGrid* @this);
/// <summary>Deallocates a `ByteGrid`. Note: do not call this if the grid has been consumed in another way, e.g. to create a command.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_byte_grid_dealloc(ByteGrid* @this);
/// <summary>Get the current value at the specified position</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_get", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern byte sp2_byte_grid_get(ByteGrid* @this, nuint x, nuint y);
/// <summary>Sets the current value at the specified position</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_set", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_byte_grid_set(ByteGrid* @this, nuint x, nuint y, byte value);
/// <summary>Fills the whole `ByteGrid` with the specified value</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_fill", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_byte_grid_fill(ByteGrid* @this, byte value);
/// <summary>Gets the width in pixels of the `ByteGrid` instance.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_width", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_byte_grid_width(ByteGrid* @this);
/// <summary>Gets the height in pixels of the `ByteGrid` instance.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_height", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_byte_grid_height(ByteGrid* @this);
/// <summary>Gets an unsafe reference to the data of the `ByteGrid` instance. ## Safety The caller has to make sure to never access the returned memory after the `ByteGrid` instance has been consumed or manually deallocated. Reading and writing concurrently to either the original instance or the returned data will result in undefined behavior.</summary>
[DllImport(__DllName, EntryPoint = "sp2_byte_grid_unsafe_data_ref", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern CByteSlice sp2_byte_grid_unsafe_data_ref(ByteGrid* @this);
/// <summary>Tries to turn a `Packet` into a `Command`. The packet is gets deallocated in the process. Returns: pointer to command or NULL</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_try_from_packet", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_try_from_packet(Packet* packet);
/// <summary>Clones a `Command` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_clone", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_clone(Command* original);
/// <summary>Allocates a new `Command::Clear` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_clear", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_clear();
/// <summary>Allocates a new `Command::HardReset` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_hard_reset", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_hard_reset();
/// <summary>Allocates a new `Command::FadeOut` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_fade_out", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_fade_out();
/// <summary>Allocates a new `Command::Brightness` instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_brightness", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_brightness(byte brightness);
/// <summary>Allocates a new `Command::CharBrightness` instance. The passed `ByteGrid` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_char_brightness", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_char_brightness(nuint x, nuint y, ByteGrid* byte_grid);
/// <summary>Allocates a new `Command::BitmapLinear` instance. The passed `BitVec` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear(nuint offset, BitVec* bit_vec, CompressionCode compression);
/// <summary>Allocates a new `Command::BitmapLinearAnd` instance. The passed `BitVec` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear_and", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear_and(nuint offset, BitVec* bit_vec, CompressionCode compression);
/// <summary>Allocates a new `Command::BitmapLinearOr` instance. The passed `BitVec` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear_or", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear_or(nuint offset, BitVec* bit_vec, CompressionCode compression);
/// <summary>Allocates a new `Command::BitmapLinearXor` instance. The passed `BitVec` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear_xor", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear_xor(nuint offset, BitVec* bit_vec, CompressionCode compression);
/// <summary>Allocates a new `Command::Cp437Data` instance. The passed `ByteGrid` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_cp437_data", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_cp437_data(nuint x, nuint y, ByteGrid* byte_grid);
/// <summary>Allocates a new `Command::BitmapLinearWin` instance. The passed `PixelGrid` gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_bitmap_linear_win", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Command* sp2_command_bitmap_linear_win(nuint x, nuint y, PixelGrid* byte_grid, CompressionCode compression_code);
/// <summary>Deallocates a `Command`. Note that connection_send does this implicitly, so you only need to do this if you use the library for parsing commands.</summary>
[DllImport(__DllName, EntryPoint = "sp2_command_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_command_dealloc(Command* ptr);
/// <summary>Creates a new instance of Connection. The returned instance has to be deallocated with `connection_dealloc`. returns: NULL if connection fails or connected instance Panics: bad string encoding</summary>
[DllImport(__DllName, EntryPoint = "sp2_connection_open", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Connection* sp2_connection_open(byte* host);
/// <summary>Sends the command instance. The instance is consumed / destroyed and cannot be used after this call.</summary>
[DllImport(__DllName, EntryPoint = "sp2_connection_send", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_connection_send(Connection* connection, Packet* command_ptr);
/// <summary>Closes and deallocates a connection instance</summary>
[DllImport(__DllName, EntryPoint = "sp2_connection_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_connection_dealloc(Connection* ptr);
/// <summary>Creates a new `PixelGrid` instance. The returned instance has to be freed with `pixel_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_new", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern PixelGrid* sp2_pixel_grid_new(nuint width, nuint height);
/// <summary>Loads a `PixelGrid` with the specified dimensions from the provided data. The returned instance has to be freed with `pixel_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_load", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern PixelGrid* sp2_pixel_grid_load(nuint width, nuint height, byte* data, nuint data_length);
/// <summary>Clones a `PixelGrid`. The returned instance has to be freed with `pixel_grid_dealloc`.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_clone", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern PixelGrid* sp2_pixel_grid_clone(PixelGrid* @this);
/// <summary>Deallocates a `PixelGrid`. Note: do not call this if the grid has been consumed in another way, e.g. to create a command.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_pixel_grid_dealloc(PixelGrid* @this);
/// <summary>Get the current value at the specified position</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_get", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool sp2_pixel_grid_get(PixelGrid* @this, nuint x, nuint y);
/// <summary>Sets the current value at the specified position</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_set", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_pixel_grid_set(PixelGrid* @this, nuint x, nuint y, [MarshalAs(UnmanagedType.U1)] bool value);
/// <summary>Fills the whole `PixelGrid` with the specified value</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_fill", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_pixel_grid_fill(PixelGrid* @this, [MarshalAs(UnmanagedType.U1)] bool value);
/// <summary>Gets the width in pixels of the `PixelGrid` instance.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_width", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_pixel_grid_width(PixelGrid* @this);
/// <summary>Gets the height in pixels of the `PixelGrid` instance.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_height", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern nuint sp2_pixel_grid_height(PixelGrid* @this);
/// <summary>Gets an unsafe reference to the data of the `PixelGrid` instance. ## Safety The caller has to make sure to never access the returned memory after the `PixelGrid` instance has been consumed or manually deallocated. Reading and writing concurrently to either the original instance or the returned data will result in undefined behavior.</summary>
[DllImport(__DllName, EntryPoint = "sp2_pixel_grid_unsafe_data_ref", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern CByteSlice sp2_pixel_grid_unsafe_data_ref(PixelGrid* @this);
/// <summary>Turns a `Command` into a `Packet`. The command gets deallocated in the process.</summary>
[DllImport(__DllName, EntryPoint = "sp2_packet_from_command", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Packet* sp2_packet_from_command(Command* command);
/// <summary>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</summary>
[DllImport(__DllName, EntryPoint = "sp2_packet_try_load", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern Packet* sp2_packet_try_load(byte* data, nuint length);
/// <summary>Deallocates a `Packet`. Note: do not call this if the instance has been consumed in another way, e.g. by sending it.</summary>
[DllImport(__DllName, EntryPoint = "sp2_packet_dealloc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void sp2_packet_dealloc(Packet* @this);
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct BitVec
{
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct ByteGrid
{
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct Connection
{
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct PixelGrid
{
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct CByteSlice
{
public byte* start;
public nuint length;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct Packet
{
}
public enum Command
{
Clear,
HardReset,
FadeOut,
CharBrightness,
Brightness,
BitmapLegacy,
BitmapLinear,
BitmapLinearAnd,
BitmapLinearOr,
BitmapLinearXor,
Cp437Data,
BitmapLinearWin,
}
public enum CompressionCode : ushort
{
Uncompressed = 0,
Zlib = 26490,
Bzip2 = 25210,
Lzma = 27770,
Zstd = 31347,
}
}

View file

@ -0,0 +1,91 @@
using ServicePoint.BindGen;
namespace ServicePoint;
public sealed class BitVec : SpNativeInstance<BindGen.BitVec>
{
public static BitVec New(int size)
{
unsafe
{
return new BitVec(NativeMethods.sp2_bit_vec_new((nuint)size));
}
}
public static BitVec Load(Span<byte> bytes)
{
unsafe
{
fixed (byte* bytesPtr = bytes)
{
return new BitVec(NativeMethods.sp2_bit_vec_load(bytesPtr, (nuint)bytes.Length));
}
}
}
public BitVec Clone()
{
unsafe
{
return new BitVec(NativeMethods.sp2_bit_vec_clone(Instance));
}
}
public bool this[int index]
{
get
{
unsafe
{
return NativeMethods.sp2_bit_vec_get(Instance, (nuint)index);
}
}
set
{
unsafe
{
NativeMethods.sp2_bit_vec_set(Instance, (nuint)index, value);
}
}
}
public void Fill(bool value)
{
unsafe
{
NativeMethods.sp2_bit_vec_fill(Instance, value);
}
}
public int Length
{
get
{
unsafe
{
return (int)NativeMethods.sp2_bit_vec_len(Instance);
}
}
}
public Span<byte> Data
{
get
{
unsafe
{
var slice = NativeMethods.sp2_bit_vec_unsafe_data_ref(Instance);
return new Span<byte>(slice.start, (int)slice.length);
}
}
}
private unsafe BitVec(BindGen.BitVec* instance) : base(instance)
{
}
private protected override unsafe void Dealloc()
{
NativeMethods.sp2_bit_vec_dealloc(Instance);
}
}

View file

@ -0,0 +1,134 @@
using System.Text;
using ServicePoint.BindGen;
namespace ServicePoint;
public sealed class ByteGrid : SpNativeInstance<BindGen.ByteGrid>
{
public static ByteGrid New(int width, int height)
{
unsafe
{
return new ByteGrid(NativeMethods.sp2_byte_grid_new((nuint)width, (nuint)height));
}
}
public static ByteGrid Load(int width, int height, Span<byte> bytes)
{
unsafe
{
fixed (byte* bytesPtr = bytes)
{
return new ByteGrid(NativeMethods.sp2_byte_grid_load((nuint)width, (nuint)height, bytesPtr,
(nuint)bytes.Length));
}
}
}
public ByteGrid Clone()
{
unsafe
{
return new ByteGrid(NativeMethods.sp2_byte_grid_clone(Instance));
}
}
public byte this[int x, int y]
{
get
{
unsafe
{
return NativeMethods.sp2_byte_grid_get(Instance, (nuint)x, (nuint)y);
}
}
set
{
unsafe
{
NativeMethods.sp2_byte_grid_set(Instance, (nuint)x, (nuint)y, value);
}
}
}
public string this[int y]
{
set
{
var width = Width;
ArgumentOutOfRangeException.ThrowIfGreaterThan(value.Length, width);
var x = 0;
for (; x < value.Length; x++)
this[x, y] = (byte)value[x];
for (; x < width; x++)
this[x, y] = 0;
}
get
{
var sb = new StringBuilder();
for (int x = 0; x < Width; x++)
{
var val = this[x, y];
if (val == 0)
break;
sb.Append((char)val);
}
return sb.ToString();
}
}
public void Fill(byte value)
{
unsafe
{
NativeMethods.sp2_byte_grid_fill(Instance, value);
}
}
public int Width
{
get
{
unsafe
{
return (int)NativeMethods.sp2_byte_grid_width(Instance);
}
}
}
public int Height
{
get
{
unsafe
{
return (int)NativeMethods.sp2_byte_grid_height(Instance);
}
}
}
public Span<byte> Data
{
get
{
unsafe
{
var slice = NativeMethods.sp2_byte_grid_unsafe_data_ref(Instance);
return new Span<byte>(slice.start, (int)slice.length);
}
}
}
private unsafe ByteGrid(BindGen.ByteGrid* instance) : base(instance)
{
}
private protected override unsafe void Dealloc()
{
NativeMethods.sp2_byte_grid_dealloc(Instance);
}
}

View file

@ -0,0 +1,132 @@
using System.Diagnostics.CodeAnalysis;
using ServicePoint.BindGen;
namespace ServicePoint;
public sealed class Command : SpNativeInstance<BindGen.Command>
{
public static bool TryFromPacket(Packet packet, [MaybeNullWhen(false)] out Command command)
{
unsafe
{
var result = NativeMethods.sp2_command_try_from_packet(packet.Into());
if (result == null)
{
command = null;
return false;
}
command = new Command(result);
return true;
}
}
public Command Clone()
{
unsafe
{
return new Command(NativeMethods.sp2_command_clone(Instance));
}
}
public static Command Clear()
{
unsafe
{
return new Command(NativeMethods.sp2_command_clear());
}
}
public static Command HardReset()
{
unsafe
{
return new Command(NativeMethods.sp2_command_hard_reset());
}
}
public static Command FadeOut()
{
unsafe
{
return new Command(NativeMethods.sp2_command_fade_out());
}
}
public static Command Brightness(byte brightness)
{
unsafe
{
return new Command(NativeMethods.sp2_command_brightness(brightness));
}
}
public static Command CharBrightness(int x, int y, ByteGrid grid)
{
unsafe
{
return new Command(NativeMethods.sp2_command_char_brightness((ushort)x, (ushort)y, grid.Into()));
}
}
public static Command BitmapLinear(int offset, BitVec bitVec, CompressionCode compressionCode)
{
unsafe
{
return new Command(
NativeMethods.sp2_command_bitmap_linear((ushort)offset, bitVec.Into(), compressionCode));
}
}
public static Command BitmapLinearAnd(int offset, BitVec bitVec, CompressionCode compressionCode)
{
unsafe
{
return new Command(
NativeMethods.sp2_command_bitmap_linear_and((ushort)offset, bitVec.Into(), compressionCode));
}
}
public static Command BitmapLinearOr(int offset, BitVec bitVec, CompressionCode compressionCode)
{
unsafe
{
return new Command(
NativeMethods.sp2_command_bitmap_linear_or((ushort)offset, bitVec.Into(), compressionCode));
}
}
public static Command BitmapLinearXor(int offset, BitVec bitVec, CompressionCode compressionCode)
{
unsafe
{
return new Command(
NativeMethods.sp2_command_bitmap_linear_xor((ushort)offset, bitVec.Into(), compressionCode));
}
}
public static Command BitmapLinearWin(int x, int y, PixelGrid pixelGrid, CompressionCode compression)
{
unsafe
{
return new Command(NativeMethods.sp2_command_bitmap_linear_win((ushort)x, (ushort)y, pixelGrid.Into(), compression));
}
}
public static Command Cp437Data(int x, int y, ByteGrid byteGrid)
{
unsafe
{
return new Command(NativeMethods.sp2_command_cp437_data((ushort)x, (ushort)y, byteGrid.Into()));
}
}
private unsafe Command(BindGen.Command* instance) : base(instance)
{
}
private protected override unsafe void Dealloc()
{
NativeMethods.sp2_command_dealloc(Instance);
}
}

View file

@ -0,0 +1,35 @@
using System.Text;
using ServicePoint.BindGen;
namespace ServicePoint;
public sealed class Connection : SpNativeInstance<BindGen.Connection>
{
public static Connection Open(string host)
{
unsafe
{
fixed (byte* bytePtr = Encoding.UTF8.GetBytes(host))
{
return new Connection(NativeMethods.sp2_connection_open(bytePtr));
}
}
}
public bool Send(Packet packet)
{
unsafe
{
return NativeMethods.sp2_connection_send(Instance, packet.Into());
}
}
private protected override unsafe void Dealloc()
{
NativeMethods.sp2_connection_dealloc(Instance);
}
private unsafe Connection(BindGen.Connection* instance) : base(instance)
{
}
}

View file

@ -0,0 +1,22 @@
namespace ServicePoint;
public static class Constants
{
/// size of a single tile in one dimension
public const int TileSize = 8;
/// tile count in the x-direction
public const int TileWidth = 56;
/// tile count in the y-direction
public const int TileHeight = 20;
/// screen width in pixels
public const int PixelWidth = TileWidth * TileSize;
/// screen height in pixels
public const int PixelHeight = TileHeight * TileSize;
/// pixel count on whole screen
public const int PixelCount = PixelWidth * PixelHeight;
}

View file

@ -0,0 +1 @@
global using System;

View file

@ -0,0 +1,39 @@
using System.Diagnostics.CodeAnalysis;
using ServicePoint.BindGen;
namespace ServicePoint;
public sealed class Packet : SpNativeInstance<BindGen.Packet>
{
public static Packet FromCommand(Command command)
{
unsafe
{
return new Packet(NativeMethods.sp2_packet_from_command(command.Into()));
}
}
public static bool TryFromBytes(Span<byte> bytes, [MaybeNullWhen(false)] out Packet packet)
{
unsafe
{
fixed (byte* bytesPtr = bytes)
{
var instance = NativeMethods.sp2_packet_try_load(bytesPtr, (nuint)bytes.Length);
packet = instance == null
? null
: new Packet(instance);
return packet != null;
}
}
}
private unsafe Packet(BindGen.Packet* instance) : base(instance)
{
}
private protected override unsafe void Dealloc()
{
NativeMethods.sp2_packet_dealloc(Instance);
}
}

View file

@ -0,0 +1,103 @@
using ServicePoint.BindGen;
namespace ServicePoint;
public sealed class PixelGrid : SpNativeInstance<BindGen.PixelGrid>
{
public static PixelGrid New(int width, int height)
{
unsafe
{
return new PixelGrid(NativeMethods.sp2_pixel_grid_new((nuint)width, (nuint)height));
}
}
public static PixelGrid Load(int width, int height, Span<byte> bytes)
{
unsafe
{
fixed (byte* bytesPtr = bytes)
{
return new PixelGrid(NativeMethods.sp2_pixel_grid_load((nuint)width, (nuint)height, bytesPtr,
(nuint)bytes.Length));
}
}
}
public PixelGrid Clone()
{
unsafe
{
return new PixelGrid(NativeMethods.sp2_pixel_grid_clone(Instance));
}
}
public bool this[int x, int y]
{
get
{
unsafe
{
return NativeMethods.sp2_pixel_grid_get(Instance, (nuint)x, (nuint)y);
}
}
set
{
unsafe
{
NativeMethods.sp2_pixel_grid_set(Instance, (nuint)x, (nuint)y, value);
}
}
}
public void Fill(bool value)
{
unsafe
{
NativeMethods.sp2_pixel_grid_fill(Instance, value);
}
}
public int Width
{
get
{
unsafe
{
return (int)NativeMethods.sp2_pixel_grid_width(Instance);
}
}
}
public int Height
{
get
{
unsafe
{
return (int)NativeMethods.sp2_pixel_grid_height(Instance);
}
}
}
public Span<byte> Data
{
get
{
unsafe
{
var slice = NativeMethods.sp2_pixel_grid_unsafe_data_ref(Instance);
return new Span<byte>(slice.start, (int)slice.length);
}
}
}
private unsafe PixelGrid(BindGen.PixelGrid* instance) : base(instance)
{
}
private protected override unsafe void Dealloc()
{
NativeMethods.sp2_pixel_grid_dealloc(Instance);
}
}

View file

@ -0,0 +1,70 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DisableFastUpToDateCheck>true</DisableFastUpToDateCheck>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<PropertyGroup>
<PackageId>ServicePoint</PackageId>
<Version>0.3.0</Version>
<Authors>Repository Authors</Authors>
<Company>None</Company>
<Product>ServicePoint</Product>
<PackageTags>CCCB</PackageTags>
<Description>
C# bindings for the rust crate servicepoint. You will need a suitable native shared library to use this.
For documentation, see the rust documentation: https://docs.rs/servicepoint/latest/servicepoint/.
Note that this library is still in early development. Breaking changes are expected before 1.0 is released.
</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
</PropertyGroup>
<Target Name="BuildLibrary" Condition="'$(Configuration)'=='Release'" BeforeTargets="Build">
<Exec Command="cargo build --manifest-path ../../servicepoint/Cargo.toml --all-features --release"/>
</Target>
<Target Name="BuildLibrary" Condition="'$(Configuration)'=='Debug'" BeforeTargets="Build">
<Exec Command="cargo build --manifest-path ../../servicepoint/Cargo.toml --all-features"/>
</Target>
<Target Name="BuildBindings" Condition="'$(Configuration)'=='Release'" BeforeTargets="Build">
<Exec Command="cargo build --release"/>
</Target>
<Target Name="BuildBindings" Condition="'$(Configuration)'=='Debug'" BeforeTargets="Build">
<Exec Command="cargo build"/>
</Target>
<ItemGroup Condition="'$(Configuration)'=='Debug'">
<Content Include="../../target/debug/libservicepoint.so" CopyToOutputDirectory="Always">
<Link>libservicepoint.so</Link>
</Content>
</ItemGroup>
<ItemGroup Condition="'$(Configuration)'=='Release'">
<Content Include="../../target/release/libservicepoint.so" CopyToOutputDirectory="Always">
<Link>libservicepoint.so</Link>
</Content>
</ItemGroup>
<ItemGroup>
<!-- include link to source code at revision -->
<None Include="../../README.md" Pack="true" PackagePath="\"/>
<!-- add README.md to package -->
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All"/>
</ItemGroup>
<ItemGroup>
<Content Include="..\build.rs">
<Link>build.rs</Link>
</Content>
</ItemGroup>
</Project>

View file

@ -0,0 +1,16 @@
using System.Diagnostics.CodeAnalysis;
namespace ServicePoint;
public static class ServicePointExtensions
{
public static Packet IntoPacket(this Command command)
{
return Packet.FromCommand(command);
}
public static bool TryIntoCommand(this Packet packet, [MaybeNullWhen(false)] out Command command)
{
return Command.TryFromPacket(packet, out command);
}
}

View file

@ -0,0 +1,51 @@
namespace ServicePoint;
public abstract class SpNativeInstance<T>
: IDisposable
where T : unmanaged
{
private unsafe T* _instance;
internal unsafe T* Instance
{
get
{
if (_instance == null)
throw new NullReferenceException("instance is null");
return _instance;
}
}
private protected unsafe SpNativeInstance(T* instance)
{
ArgumentNullException.ThrowIfNull(instance);
_instance = instance;
}
private protected abstract void Dealloc();
internal unsafe T* Into()
{
var instance = _instance;
_instance = null;
return instance;
}
private unsafe void ReleaseUnmanagedResources()
{
if (_instance != null)
Dealloc();
_instance = null;
}
public void Dispose()
{
ReleaseUnmanagedResources();
GC.SuppressFinalize(this);
}
~SpNativeInstance()
{
ReleaseUnmanagedResources();
}
}

View file

@ -0,0 +1 @@