rename to servicepoint, new dir structure, WIP build.rs
This commit is contained in:
parent
e9dc4b59d2
commit
f2d98af532
61 changed files with 751 additions and 140 deletions
167
crates/servicepoint/Cargo.lock
generated
Normal file
167
crates/servicepoint/Cargo.lock
generated
Normal 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",
|
||||
]
|
29
crates/servicepoint/Cargo.toml
Normal file
29
crates/servicepoint/Cargo.toml
Normal 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 = []
|
317
crates/servicepoint/src/bit_vec.rs
Normal file
317
crates/servicepoint/src/bit_vec.rs
Normal 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:?}");
|
||||
}
|
||||
}
|
279
crates/servicepoint/src/byte_grid.rs
Normal file
279
crates/servicepoint/src/byte_grid.rs
Normal 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)
|
||||
}
|
||||
}
|
11
crates/servicepoint/src/c_slice.rs
Normal file
11
crates/servicepoint/src/c_slice.rs
Normal 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,
|
||||
}
|
863
crates/servicepoint/src/command.rs
Normal file
863
crates/servicepoint/src/command.rs
Normal 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));
|
||||
}
|
||||
}
|
99
crates/servicepoint/src/command_code.rs
Normal file
99
crates/servicepoint/src/command_code.rs
Normal 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(()),
|
||||
}
|
||||
}
|
||||
}
|
115
crates/servicepoint/src/compression.rs
Normal file
115
crates/servicepoint/src/compression.rs
Normal 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")
|
||||
}
|
||||
}
|
||||
}
|
49
crates/servicepoint/src/compression_code.rs
Normal file
49
crates/servicepoint/src/compression_code.rs
Normal 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(()),
|
||||
}
|
||||
}
|
||||
}
|
117
crates/servicepoint/src/connection.rs
Normal file
117
crates/servicepoint/src/connection.rs
Normal 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);
|
||||
}
|
||||
}
|
11
crates/servicepoint/src/data_ref.rs
Normal file
11
crates/servicepoint/src/data_ref.rs
Normal 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];
|
||||
}
|
53
crates/servicepoint/src/grid.rs
Normal file
53
crates/servicepoint/src/grid.rs
Normal 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;
|
||||
}
|
47
crates/servicepoint/src/lib.rs
Normal file
47
crates/servicepoint/src/lib.rs
Normal 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);
|
112
crates/servicepoint/src/packet.rs
Normal file
112
crates/servicepoint/src/packet.rs
Normal 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]));
|
||||
}
|
||||
}
|
289
crates/servicepoint/src/pixel_grid.rs
Normal file
289
crates/servicepoint/src/pixel_grid.rs
Normal 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]);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue