WIP: type per command #4

Draft
vinzenz wants to merge 25 commits from next into main
41 changed files with 2892 additions and 955 deletions

View file

@ -36,9 +36,9 @@ jobs:
run: output=$(git status --porcelain) && [ -z "$output" ]
- name: build example -- glibc release
run: cd example && make clean && make TARGET=aarch64-unknown-linux-gnu PROFILE=release
run: cd example && make -r clean-all && make -r LIBC=gnu LINK=dynamic PROFILE=release
- name: build example -- glibc debug
run: cd example && make clean && make TARGET=aarch64-unknown-linux-gnu PROFILE=debug
run: cd example && make -r clean-all && make -r LIBC=gnu LINK=dynamic PROFILE=debug
build-size-gnu-unstable:
runs-on: ubuntu-latest
@ -52,5 +52,6 @@ jobs:
- name: install rust targets
run: rustup toolchain install nightly -t aarch64-unknown-linux-gnu -c rust-src --no-self-update
- name: build example -- glibc size-optimized
run: cd example && make clean && make TARGET=aarch64-unknown-linux-gnu PROFILE=size-optimized CARGO="rustup run nightly cargo" LTO=1
- name: build example -- glibc size_optimized
run: cd example && make clean-all -r
&& make -r LIBC=gnu LINK=dynamic PROFILE=size_optimized CARGO="rustup run nightly cargo" LTO=1

3
.gitignore vendored
View file

@ -4,4 +4,5 @@ out
.direnv
.envrc
result
mutants.*
mutants.*
_out_*

149
Cargo.lock generated
View file

@ -8,6 +8,15 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "0.6.18"
@ -49,20 +58,20 @@ dependencies = [
[[package]]
name = "anstyle-wincon"
version = "3.0.7"
version = "3.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e"
checksum = "6680de5231bd6ee4c6191b8a1325daa282b415391ec9d3a37bd34f2060dc73fa"
dependencies = [
"anstyle",
"once_cell",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "bitflags"
version = "2.9.0"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
[[package]]
name = "bitvec"
@ -116,9 +125,9 @@ dependencies = [
[[package]]
name = "cc"
version = "1.2.21"
version = "1.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8691782945451c1c383942c4874dbe63814f61cb57ef773cda2972682b7bb3c0"
checksum = "16595d3be041c03b09d08d0858631facccee9221e579704070e6e9e4915d3bc7"
dependencies = [
"jobserver",
"libc",
@ -133,18 +142,18 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "4.5.37"
version = "4.5.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eccb054f56cbd38340b380d4a8e69ef1f02f1af43db2f0cc817a4774d80ae071"
checksum = "ed93b9805f8ba930df42c2590f05453d5ec36cbb85d018868a5b24d31f6ac000"
dependencies = [
"clap_builder",
]
[[package]]
name = "clap_builder"
version = "4.5.37"
version = "4.5.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efd9466fac8543255d3b1fcad4762c5e116ffe808c8a3043d4263cd4fd4862a2"
checksum = "379026ff283facf611b0ea629334361c4211d1b12ee01024eec1591133b04120"
dependencies = [
"anstream",
"anstyle",
@ -173,6 +182,29 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "env_filter"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0"
dependencies = [
"log",
"regex",
]
[[package]]
name = "env_logger"
version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f"
dependencies = [
"anstream",
"anstyle",
"env_filter",
"jiff",
"log",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@ -181,9 +213,9 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "errno"
version = "0.3.11"
version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e"
checksum = "cea14ef9355e3beab063703aa9dab15afd25f0667c341310c1e5274bb1d0da18"
dependencies = [
"libc",
"windows-sys",
@ -213,9 +245,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "getrandom"
version = "0.3.2"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0"
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [
"cfg-if",
"libc",
@ -257,6 +289,30 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
[[package]]
name = "jiff"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a194df1107f33c79f4f93d02c80798520551949d59dfad22b6157048a88cca93"
dependencies = [
"jiff-static",
"log",
"portable-atomic",
"portable-atomic-util",
"serde",
]
[[package]]
name = "jiff-static"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c6e1db7ed32c6c71b759497fae34bf7933636f75a251b9e736555da426f6442"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "jobserver"
version = "0.1.33"
@ -306,12 +362,33 @@ version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "once_cell_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad"
[[package]]
name = "pkg-config"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "portable-atomic"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e"
[[package]]
name = "portable-atomic-util"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507"
dependencies = [
"portable-atomic",
]
[[package]]
name = "proc-macro2"
version = "1.0.95"
@ -342,6 +419,35 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "rust-lzma"
version = "0.6.0"
@ -414,9 +520,9 @@ dependencies = [
[[package]]
name = "servicepoint"
version = "0.14.1"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6bd5cfa49c73aeecb344680ffbf697abf73e0563a441b93b9723ae43867500f"
checksum = "91a33bff7f9db5008748b23ca0c906c276fe00694390b681f004a55968a42cfe"
dependencies = [
"bitvec",
"bzip2",
@ -433,6 +539,7 @@ name = "servicepoint_binding_c"
version = "0.14.1"
dependencies = [
"cbindgen",
"env_logger",
"servicepoint",
]
@ -467,9 +574,9 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tempfile"
version = "3.19.1"
version = "3.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf"
checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1"
dependencies = [
"fastrand",
"getrandom",
@ -641,9 +748,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.7.9"
version = "0.7.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9fb597c990f03753e08d3c29efbfcf2019a003b4bf4ba19225c158e1549f0f3"
checksum = "c06928c8748d81b05c9be96aad92e1b6ff01833332f281e8cfca3be4b35fc9ec"
dependencies = [
"memchr",
]

View file

@ -18,13 +18,17 @@ crate-type = ["staticlib", "cdylib", "rlib"]
cbindgen = "0.28.0"
[dependencies.servicepoint]
package = "servicepoint"
version = "0.14.1"
version = "0.15.0"
default-features = false
[dependencies.env_logger]
version = "0.11.8"
optional = true
[features]
all_compressions = ["servicepoint/all_compressions"]
default = ["all_compressions", "servicepoint/default"]
default = ["all_compressions", "servicepoint/default", "env_logger"]
env_logger = ["dep:env_logger"]
[lints.rust]
missing-docs = "warn"
@ -36,7 +40,7 @@ missing_safety_doc = "allow"
[package.metadata.docs.rs]
all-features = true
[profile.size-optimized]
[profile.size_optimized]
inherits = "release"
opt-level = 'z' # Optimize for size
lto = true # Enable link-time optimization

View file

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

View file

@ -4,32 +4,55 @@
//! the out directory. This can be used to use the build script as a command line tool from other
//! build tools.
use std::{env, fs::copy};
use std::{env, fs};
fn main() {
let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
println!("cargo::rerun-if-changed={crate_dir}");
println!("cargo::rerun-if-changed={crate_dir}/src");
println!("cargo::rerun-if-changed={crate_dir}/build.rs");
println!("cargo::rerun-if-changed={crate_dir}/Cargo.toml");
println!("cargo::rerun-if-changed={crate_dir}/Cargo.lock");
println!("cargo::rerun-if-changed={crate_dir}/cbindgen.toml");
println!("cargo::rerun-if-env-changed=SERVICEPOINT_HEADER_OUT");
let config =
cbindgen::Config::from_file(crate_dir.clone() + "/cbindgen.toml")
.unwrap();
let output_dir = env::var("OUT_DIR").unwrap();
let header_file = output_dir.clone() + "/servicepoint.h";
if let Ok(bindings) = cbindgen::generate_with_config(crate_dir, config) {
bindings.write_to_file(&header_file);
println!("cargo:include={output_dir}");
println!("cargo::rerun-if-env-changed=SERVICEPOINT_HEADER_OUT");
if let Ok(header_out) = env::var("SERVICEPOINT_HEADER_OUT") {
let header_copy = header_out + "/servicepoint.h";
println!("cargo:warning=Copying header to {header_copy}");
copy(header_file, &header_copy).unwrap();
println!("cargo::rerun-if-changed={header_copy}");
let bindings = match cbindgen::generate_with_config(crate_dir, config) {
Ok(bindings) => bindings,
Err(e) => {
eprintln!("cargo:warning=Servicepoint header could not be generated: {e:?}");
return;
}
} else {
eprintln!("cargo:warning=Servicepoint header could not be generated");
};
bindings.write_to_file(&header_file);
println!("cargo:include={output_dir}");
if let Ok(header_out) = env::var("SERVICEPOINT_HEADER_OUT") {
let header_copy = header_out + "/servicepoint.h";
if fs::exists(&header_copy).ok().unwrap_or(false) {
// check if content changed to prevent rebuild of dependents if not
let mut bindings_text = Vec::new();
bindings.write(&mut bindings_text);
match fs::read(&header_copy) {
Ok(old_content) if old_content == bindings_text => {
println!("cargo:warning=Header did not change, not updating timestamp");
return;
}
_ => {}
};
}
// file does not exist or is different
println!("cargo:warning=Copying header to {header_copy}");
fs::copy(header_file, &header_copy).unwrap();
println!("cargo::rerun-if-changed={header_copy}");
}
}

View file

@ -16,27 +16,29 @@ line_endings = "LF"
############################# Codegen Options ##################################
style = "type"
style = "both"
usize_is_size_t = true
# this is needed because otherwise the order in the C bindings is different on different machines
sort_by = "Name"
include_guard = "SERVICEPOINT_BINDINGS_C"
[parse]
parse_deps = true
include = ["servicepoint", "std"]
extra_bindings = ["servicepoint"]
extra_bindings = ["servicepoint", "servicepoint_binding_c"]
[parse.expand]
features = ["full"]
[export]
include = []
exclude = []
exclude = ["BitVec"]
[export.rename]
"SpBitVec" = "BitVec"
"SpByteSlice" = "ByteSlice"
"SPCommand" = "Command"
"DisplayBitVec" = "BitVec"
[enum]
rename_variants = "QualifiedScreamingSnakeCase"

View file

@ -1,129 +1,120 @@
# based on https://make.mad-scientist.net/papers/multi-architecture-builds/
_libc := $(if $(LIBC),$(LIBC),gnu)
ifeq (,$(filter gnu musl,$(_libc)))
_link_type := $(error "LIBC has to be set to one of: gnu, musl")
endif
_link_type := $(if $(LINK),$(LINK),dynamic)
ifeq (,$(filter dynamic static,$(_link_type)))
_link_type := $(error "LINK has to be set to one of: dynamic, static")
endif
_profile := $(if $(PROFILE),$(PROFILE),release)
ifeq (,$(filter release debug size_optimized,$(_profile)))
_profile := $(error "PROFILE has to be set to one of: debug, release, size_optimized")
endif
ARCH ?= $(shell uname -m)
RUST_TARGET := $(ARCH)-unknown-linux-$(_libc)
#----- Begin Boilerplate
ifeq (,$(filter _out_%,$(notdir $(CURDIR))))
include target.mk
else
#----- End Boilerplate
VPATH = $(SRCDIR)
CARGO ?= cargo
STRIP ?= strip
CC ?= gcc
FEATURES := ""
FEATURES := ""#"env_logger"
THIS_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
REPO_ROOT := $(realpath $(THIS_DIR)/..)
export SERVICEPOINT_HEADER_OUT := $(REPO_ROOT)/include
CARGO_OBJDIR := cargo/$(RUST_TARGET)/$(_profile)
override CFG_MUSL := $(if $(CFG_MUSL),$(CFG_MUSL),$(if $(MUSL),$(MUSL),0))
override CFG_PROFILE := $(if $(CFG_PROFILE),$(CFG_PROFILE),$(if $(PROFILE),$(PROFILE),release))
_rust_cli_profile := $(if $(filter $(_profile),debug),dev,$(_profile))
CCFLAGS += -Wall -fwhole-program -fPIE -pie
# TODO: `make LINK=static` fails with linker error "undefined reference to `_dl_find_object'" in libgcc_eh.a
STRIPFLAGS := -s --strip-unneeded -R .comment -R .gnu.version -R .note -R .note.gnu.build-id -R .note.ABI-tag
ifeq ($(CFG_MUSL), 1)
TARGET ?= x86_64-unknown-linux-musl
CC ?= musl-gcc
CCFLAGS += -static -lservicepoint_binding_c
RUSTFLAGS += --crate-type=staticlib -Ctarget-feature=-crt-static
else
TARGET ?= x86_64-unknown-linux-gnu
CC ?= gcc
#CCFLAGS += -shared
CCFLAGS += -Wl,-Bstatic -lservicepoint_binding_c -Wl,-Bdynamic
endif
#ifeq ($(CFG_PROFILE), size-optimized)
# CCFLAGS += -nodefaultlibs -lc
#endif
RUST_TARGET_DIR := $(REPO_ROOT)/target/$(TARGET)/$(CFG_PROFILE)
ifeq ($(CFG_PROFILE), size-optimized)
CARGO_PROFILE := size-optimized
CCFLAGS += -Oz \
-fwrapv -fomit-frame-pointer -fno-stack-protector\
-fno-unroll-loops \
-fno-unwind-tables -fno-asynchronous-unwind-tables \
-fmerge-all-constants \
-Wl,-z,norelro \
-Wl,--hash-style=gnu \
-fvisibility=hidden \
-Bsymbolic \
-Wl,--exclude-libs,ALL \
-fno-ident \
-fno-exceptions
CARGOFLAGS += -Zbuild-std="core,std,alloc,proc_macro,panic_abort" \
-Zbuild-std-features="panic_immediate_abort"
RUSTFLAGS += -Zlocation-detail=none \
-Zfmt-debug=none \
-C link-arg=-z,norelro \
-C panic=abort
#-C link-arg=--hash-style=gnu
else ifeq ($(CFG_PROFILE), release)
CARGO_PROFILE := release
CCFLAGS += -O2
else ifeq ($(CFG_PROFILE), debug)
CCFLAGS += -Og
CARGO_PROFILE := dev
else
CFG_PROFILE := $(error "PROFILE has to be set to one of: debug, release, size-optimized")
endif
STRIPFLAGS += -s --strip-unneeded -R .comment -R .gnu.version -R .note -R .note.gnu.build-id -R .note.ABI-tag
STATIC_LINK_LIBS += -lservicepoint_binding_c
size_optimized_CARGOFLAGS += -Zbuild-std="core,std,alloc,proc_macro,panic_abort" \
-Zbuild-std-features="panic_immediate_abort"
CARGOFLAGS += --manifest-path=$(REPO_ROOT)/Cargo.toml \
--profile=$(CARGO_PROFILE) \
--profile=$(_rust_cli_profile) \
--no-default-features \
--features=$(FEATURES) \
--target=$(TARGET)
--target=$(RUST_TARGET) \
$($(_profile)_CARGOFLAGS) \
--target-dir=cargo
ifneq ($(CFG_PROFILE), debug)
CCFLAGS += -ffunction-sections -fdata-sections -Wl,--gc-sections
CFLAGS += -Wall -Wextra -pedantic -fwhole-program -fPIE -pie
_no_debug_cflags := -ffunction-sections -fdata-sections -Wl,--gc-sections
size_optimized_CFLAGS += -Oz \
-fwrapv -fomit-frame-pointer -fno-stack-protector \
-fno-unroll-loops \
-fno-unwind-tables -fno-asynchronous-unwind-tables \
-fmerge-all-constants \
-Wl,-z,norelro \
-Wl,--hash-style=gnu \
-fvisibility=hidden \
-Bsymbolic \
-Wl,--exclude-libs,ALL \
-fno-ident \
-fno-exceptions \
$(_no_debug_cflags)
release_CFLAGS += -O2 \
$(_no_debug_cflags)
debug_CFLAGS += -Og
static_CFLAGS += -static $(STATIC_LINK_LIBS)
dynamic_CFLAGS += -Wl,-Bstatic $(STATIC_LINK_LIBS) -Wl,-Bdynamic
_servicepoint_cflags := -I $(REPO_ROOT)/include -L $(CARGO_OBJDIR)
CFLAGS += $($(_libc)_CFLAGS) $($(_profile)_CFLAGS) $($(_link_type)_CFLAGS) $(_servicepoint_cflags)
ifeq ($(LTO), 1)
CFLAGS += -flto
endif
size_optimized_RUSTFLAGS += -Zlocation-detail=none \
-Zfmt-debug=none \
-C link-arg=-z,norelro \
-C panic=abort \
-C link-arg=-Wl,--hash-style=gnu
static_RUSTFLAGS += --crate-type=staticlib -Ctarget-feature=+crt-static
RUSTFLAGS += $($(_libc)_RUSTFLAGS) $($(_profile)_RUSTFLAGS) $($(_link_type)_RUSTFLAGS)
ifneq ($(_profile), debug)
RUSTFLAGS += -C link-arg=-s -C link-arg=-Wl,--gc-sections
endif
ifeq ($(LTO), 1)
CCFLAGS += -flto
endif
_c_src := $(wildcard ./src/*.c)
# ADD NEW EXAMPLES HERE
_c_src := src/announce.c src/brightness_tester.c src/header_logger.c \
src/moving_line.c src/random_stuff.c src/wiping_clear.c
_programs := $(basename $(notdir $(_c_src)))
_bins := $(addprefix out/, $(_programs))
_bins := $(_programs)
_unstripped_bins := $(addsuffix _unstripped, $(_bins))
_run_programs := $(addprefix run_, $(_programs))
_rs_src := $(wildcard ../src/**.rs) ../Cargo.lock ../Cargo.toml ../cbindgen.toml
_sp_artifacts := $(SERVICEPOINT_HEADER_OUT)/servicepoint.h $(RUST_TARGET_DIR)/libservicepoint_binding_c.a $(RUST_TARGET_DIR)/libservicepoint_binding_c.so
.SUFFIXES:
.PHONY: all build-rust
all: $(_bins)
clean: clean-c clean-rust
$(_unstripped_bins): %_unstripped: src/%.c src/helpers.h build-rust
$(CC) $< $(CFLAGS) -o $@
clean-c:
rm -r out || true
clean-rust:
rm $(SERVICEPOINT_HEADER_OUT)/servicepoint.h || true
cargo clean
.PHONY: all clean sizes $(_run_programs) clean-c clean-rust
$(_unstripped_bins): out/%_unstripped: src/%.c $(SERVICEPOINT_HEADER_OUT)/servicepoint.h $(_sp_artifacts)
mkdir -p out || true
$(CC) $< \
-I $(SERVICEPOINT_HEADER_OUT) \
-L $(RUST_TARGET_DIR) \
$(CCFLAGS) \
-o $@
$(_bins): out/%: out/%_unstripped
$(_bins): %: %_unstripped
$(STRIP) $(STRIPFLAGS) $^ -o $@
$(_sp_artifacts): $(_rs_src)
mkdir -p $(SERVICEPOINT_HEADER_OUT) || true
build-rust:
# generate servicepoint header and library to link against
$(CARGO) rustc $(CARGOFLAGS) -- $(RUSTFLAGS)
$(_run_programs): run_%: out/% FORCE
./$<
sizes: $(_bins)
ls -lB out
analyze-size: out/$(BIN)_unstripped
nm --print-size --size-sort --reverse-sort --radix=d --demangle out/$(BIN)_unstripped \
| awk '{size=$$2+0; print size "\t" $$4}' \
| less
FORCE: ;
#----- Begin Boilerplate
endif

View file

@ -1,16 +1,9 @@
#include <stdio.h>
#include "servicepoint.h"
#include "helpers.h"
int main(void) {
printf("test\n");
sock_init();
UdpSocket *connection = sp_udp_open_ipv4(172, 23, 42, 29, 2342);
//UdpSocket *connection = sp_udp_open_ipv4(127, 0, 0, 1, 2342);
if (connection == NULL)
return 1;
sp_udp_send_header(connection, (Header) {.command_code = COMMAND_CODE_CLEAR});
sp_udp_send_header(sock, (Header) {.command_code = COMMAND_CODE_CLEAR});
CharGrid *grid = sp_char_grid_new(5, 2);
if (grid == NULL)
@ -30,8 +23,7 @@ int main(void) {
Packet *packet = sp_char_grid_into_packet(grid, 0, 0);
if (packet == NULL)
return 1;
sp_udp_send_packet(connection, packet);
sp_udp_send_packet(sock, packet);
sp_udp_free(connection);
return 0;
}

View file

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

204
example/src/header_logger.c Normal file
View file

@ -0,0 +1,204 @@
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include "servicepoint.h"
#define DEFAULT_LISTEN_IP "127.0.0.1"
void handle_error(const char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
int main(int argc, char **argv) {
//init_env_logger();
int udp_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (udp_socket == -1)
handle_error("socket could not be created\n");
char *listen_addr_arg;
if (argc > 1) {
listen_addr_arg = argv[1];
} else {
listen_addr_arg = DEFAULT_LISTEN_IP;
}
struct in_addr addr;
if (inet_aton(listen_addr_arg, &addr) == 0)
handle_error("listen ip could not be parsed\n");
struct sockaddr_in sockaddrIn = {
.sin_addr = addr,
.sin_family = AF_INET,
.sin_port = htons(2342),
};
memset(sockaddrIn.sin_zero, 0, sizeof(sockaddrIn.sin_zero));
if (bind(udp_socket, (struct sockaddr *) &sockaddrIn, sizeof(sockaddrIn)) == -1)
handle_error("could not bind socket\n");
printf("socket ready to receive on %s\n", listen_addr_arg);
uint8_t buffer[10000];
bool done = false;
while (!done) {
memset(buffer, 0, sizeof(buffer));
printf("\n");
ssize_t num_bytes = recv(udp_socket, (void *) buffer, sizeof(buffer), 0);
if (num_bytes == -1)
handle_error("could not read from client");
Packet *packet = sp_packet_try_load((ByteSlice) {
.start = buffer,
.length = num_bytes,
});
if (packet == NULL) {
printf("received invalid packet\n");
continue;
}
struct Header *header = sp_packet_get_header(packet);
ByteSlice payload = sp_packet_get_payload(packet);
printf("Received packet: cc=%d, a=%d, b=%d, c=%d, d=%d, payload=%p (len %zu)\n",
header->command_code, header->a, header->b, header->c, header->d,
payload.start, payload.length);
struct Command command = sp_cmd_generic_try_from_packet(packet);
switch (command.tag) {
case COMMAND_TAG_INVALID: {
printf("-> this is an invalid command\n");
break;
}
case COMMAND_TAG_HARD_RESET: {
printf("-> HardReset command - exiting\n");
done = true;
break;
}
case COMMAND_TAG_BITMAP: {
BitmapCommand *bitmapCommand = command.data.bitmap;
CompressionCode compression = sp_cmd_bitmap_get_compression(bitmapCommand);
size_t x, y;
sp_cmd_bitmap_get_origin(bitmapCommand, &x, &y);
Bitmap *bitmap = sp_cmd_bitmap_get(bitmapCommand);
size_t w = sp_bitmap_width(bitmap);
size_t h = sp_bitmap_height(bitmap);
printf("-> BitmapCommand with params: x=%zu, y=%zu, w=%zu, h=%zu, compression=%hu\n",
x, y, w, h, compression);
break;
}
case COMMAND_TAG_BRIGHTNESS_GRID: {
BrightnessGridCommand *gridCommand = command.data.brightness_grid;
size_t x, y;
sp_cmd_brightness_grid_get_origin(gridCommand, &x, &y);
BrightnessGrid *grid = sp_cmd_brightness_grid_get(gridCommand);
size_t w = sp_brightness_grid_width(grid);
size_t h = sp_brightness_grid_height(grid);
printf("-> BrightnessGridCommand with params: x=%zu, y=%zu, w=%zu, h=%zu\n",
x, y, w, h);
break;
}
case COMMAND_TAG_CHAR_GRID: {
CharGridCommand *gridCommand = command.data.char_grid;
size_t x, y;
sp_cmd_char_grid_get_origin(gridCommand, &x, &y);
CharGrid *grid = sp_cmd_char_grid_get(gridCommand);
size_t w = sp_char_grid_width(grid);
size_t h = sp_char_grid_height(grid);
printf("-> CharGridCommand with params: x=%zu, y=%zu, w=%zu, h=%zu\n",
x, y, w, h);
break;
}
case COMMAND_TAG_CP437_GRID: {
Cp437GridCommand *gridCommand = command.data.cp437_grid;
size_t x, y;
sp_cmd_cp437_grid_get_origin(gridCommand, &x, &y);
Cp437Grid *grid = sp_cmd_cp437_grid_get(gridCommand);
size_t w = sp_cp437_grid_width(grid);
size_t h = sp_cp437_grid_height(grid);
printf("-> Cp437GridCommand with params: x=%zu, y=%zu, w=%zu, h=%zu\n",
x, y, w, h);
break;
}
case COMMAND_TAG_BIT_VEC: {
BitVecCommand *bitvecCommand = command.data.bitvec;
size_t offset = sp_cmd_bitvec_get_offset(bitvecCommand);
CompressionCode compression = sp_cmd_bitvec_get_compression(bitvecCommand);
BinaryOperation operation = sp_cmd_bitvec_get_operation(bitvecCommand);
char *operationText;
switch (operation) {
case BINARY_OPERATION_AND:
operationText = "and";
break;
case BINARY_OPERATION_OR:
operationText = "or";
break;
case BINARY_OPERATION_XOR:
operationText = "xor";
break;
case BINARY_OPERATION_OVERWRITE:
operationText ="overwrite";
break;
default:
operationText ="unknown";
break;
}
BitVec *bitvec = sp_cmd_bitvec_get(bitvecCommand);
size_t len = sp_bitvec_len(bitvec);
printf("-> BitVecCommand with params: offset=%zu, length=%zu, compression=%hu, operation=%s\n",
offset, len, compression, operationText);
break;
}
case COMMAND_TAG_CLEAR: {
printf("-> ClearCommand\n");
break;
}
case COMMAND_TAG_BITMAP_LEGACY: {
printf("-> BitmapLinearLegacy\n");
break;
}
case COMMAND_TAG_FADE_OUT:{
printf("-> FadeOutCommand\n");
break;
}
case COMMAND_TAG_GLOBAL_BRIGHTNESS: {
Brightness brightness = sp_cmd_brightness_global_get(command.data.global_brightness);
printf("-> GlobalBrightnessCommand with params: brightness=%hu\n", brightness);
break;
}
default: {
printf("-> unknown command tag %d\n", command.tag);
break;
}
}
sp_cmd_generic_free(command);
}
close(udp_socket);
exit(EXIT_SUCCESS);
}

45
example/src/helpers.h Normal file
View file

@ -0,0 +1,45 @@
#pragma once
#ifndef SERVICEPOINT_BINDING_C_MSLEEP_H
#define SERVICEPOINT_BINDING_C_MSLEEP_H
#include <time.h>
#include <errno.h>
#include <stdlib.h>
#include "servicepoint.h"
static UdpSocket *sock = NULL;
void sock_free() {
sp_udp_free(sock);
}
void sock_init() {
//sock = sp_udp_open_ipv4(127, 0, 0, 1, 2342);
sock = sp_udp_open_ipv4(172, 23, 42, 29, 2342);
if (sock == NULL)
exit(-1);
atexit(sock_free);
}
/// TODO: all of this for sleeping n ms? There should be a better way!
int msleep(long msec) {
int res;
if (msec < 0) {
errno = EINVAL;
return -1;
}
struct timespec ts = {
.tv_sec = msec / 1000,
.tv_nsec = (msec % 1000) * 1000000,
};
do {
res = nanosleep(&ts, &ts);
} while (res && errno == EINTR);
return res;
}
#endif //SERVICEPOINT_BINDING_C_MSLEEP_H

34
example/src/moving_line.c Normal file
View file

@ -0,0 +1,34 @@
#include "servicepoint.h"
#include "helpers.h"
int main(void) {
sock_init();
int result = 0;
Bitmap *bitmap = sp_bitmap_new_max_sized();
for (size_t x = 0; x < sp_bitmap_width(bitmap); x++) {
sp_bitmap_fill(bitmap, false);
for (size_t y = 0; y < sp_bitmap_height(bitmap); y++) {
sp_bitmap_set(bitmap, (y + x) % PIXEL_WIDTH, y, true);
}
BitmapCommand *command = sp_cmd_bitmap_from_bitmap(sp_bitmap_clone(bitmap));
Packet *packet = sp_cmd_bitmap_try_into_packet(command);
if (packet == NULL) {
result = -2;
goto exit;
}
if (!sp_udp_send_packet(sock, packet)) {
result = -3;
goto exit;
}
msleep(SP_FRAME_PACING_MS);
}
exit:
sp_bitmap_free(bitmap);
return result;
}

View file

@ -1,10 +1,9 @@
#include <stdio.h>
#include "servicepoint.h"
#include "helpers.h"
int main(void) {
UdpSocket *connection = sp_udp_open_ipv4(127, 0, 0, 1, 2342);
if (connection == NULL)
return 1;
sock_init();
Bitmap *pixels = sp_bitmap_new(PIXEL_WIDTH, PIXEL_HEIGHT);
if (pixels == NULL)
@ -19,8 +18,6 @@ int main(void) {
Header *header = sp_packet_get_header(packet);
printf("[%d, %d, %d, %d, %d]\n", header->command_code, header->a, header->b, header->c, header->d);
sp_udp_send_packet(connection, packet);
sp_udp_free(connection);
sp_udp_send_packet(sock, packet);
return 0;
}

View file

@ -0,0 +1,34 @@
#include "servicepoint.h"
#include "helpers.h"
int main() {
sock_init();
Bitmap *enabled_pixels = sp_bitmap_new_max_sized();
sp_bitmap_fill(enabled_pixels, true);
int result = 0;
for (int x = 0; x < PIXEL_WIDTH; x++) {
for (int y = 0; y < PIXEL_HEIGHT; y++) {
sp_bitmap_set(enabled_pixels, x, y, false);
}
BitVec *bitvec = sp_bitmap_into_bitvec(sp_bitmap_clone(enabled_pixels));
BitVecCommand *command = sp_cmd_bitvec_new(bitvec, 0, BINARY_OPERATION_AND, COMPRESSION_CODE_LZMA);
Packet *packet = sp_cmd_bitvec_try_into_packet(command);
if (packet == NULL) {
result = -2;
goto exit;
}
if (!sp_udp_send_packet(sock, packet)) {
result = -3;
goto exit;
}
msleep(SP_FRAME_PACING_MS);
}
exit:
sp_bitmap_free(enabled_pixels);
return result;
}

56
example/target.mk Normal file
View file

@ -0,0 +1,56 @@
# Based on https://make.mad-scientist.net/papers/multi-architecture-builds/
.SUFFIXES:
OBJDIR := _out_$(RUST_TARGET)-$(_link_type)-$(_profile)
# Define the rules to build in the target subdirectories.
#
MAKETARGET = $(MAKE) --no-print-directory -C $@ -f $(CURDIR)/Makefile \
SRCDIR=$(CURDIR) $(MAKECMDGOALS)
.PHONY: $(OBJDIR)
$(OBJDIR):
+@[ -d "$@" ] || mkdir -p "$@"
+@$(MAKETARGET)
# These rules keep make from trying to use the match-anything rule below to
# rebuild the makefiles--ouch! Obviously, if you don't follow my convention
# of using a `.mk' suffix on all non-standard makefiles you'll need to change
# the pattern rule.
#
Makefile : ;
%.mk :: ;
# Anything we don't know how to build will use this rule. The command is a
# do-nothing command, but the prerequisites ensure that the appropriate
# recursive invocations of make will occur.
#
% :: $(OBJDIR) ;
# The clean rule is best handled from the source directory: since we're
# rigorous about keeping the target directories containing only target files
# and the source directory containing only source files, `clean' is as trivial
# as removing the target directories!
#
.PHONY: clean clean-all help
clean:
rm -rf $(OBJDIR)
clean-all:
rm -rf _out_*
help:
@echo "You have the choice of the following parameters:"
@echo ""
@echo "Variable | Description | Default | Values"
@echo "---------+----------------------+-----------+---------------------------"
@echo "LIBC | libc to link against | 'gnu' | 'gnu' or 'musl'"
@echo "PROFILE | Optimization profile | 'release' | 'debug' or 'size_optimized'"
@echo "LINK | | 'dynamic' | 'dynamic' or 'static'"
@echo "CARGO | cargo binary to use | 'cargo' | 'rustup run nightly cargo'"
@echo "CC | C compiler to use | 'gcc' | 'musl-gcc'"
@echo "STRIP | strip command to use | 'strip' | -"
@echo ""
@echo "When building this project, each configuration will result in a separate output directory."
@echo "The target clean only removes the output directory of the specified configuration."
@echo "The target clean-all can be used to remove the builds of all configurations."

View file

@ -2,16 +2,16 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1739357830,
"narHash": "sha256-9xim3nJJUFbVbJCz48UP4fGRStVW5nv4VdbimbKxJ3I=",
"lastModified": 1748302896,
"narHash": "sha256-ixMT0a8mM091vSswlTORZj93WQAJsRNmEvqLL+qwTFM=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "0ff09db9d034a04acd4e8908820ba0b410d7a33a",
"rev": "7848cd8c982f7740edf76ddb3b43d234cb80fc4d",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-24.11",
"ref": "nixos-25.05",
"repo": "nixpkgs",
"type": "github"
}

View file

@ -2,7 +2,7 @@
description = "Flake for the servicepoint library.";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-24.11";
nixpkgs.url = "github:nixos/nixpkgs/nixos-25.05";
};
outputs =
@ -31,37 +31,41 @@
{
devShells = forAllSystems (
{ pkgs, system }:
let
toolchain = pkgs.symlinkJoin {
name = "rust-toolchain";
paths = with pkgs; [
rustc
cargo
rustPlatform.rustcSrc
rustPlatform.rustLibSrc
rustfmt
clippy
cargo-expand
cargo-tarpaulin
];
};
in
{
default = pkgs.mkShell rec {
buildInputs = with pkgs; [
packages = with pkgs; [
toolchain
gcc
gdb
gnumake
pkg-config
xe
xz
libgcc
libunwind
pkgsStatic.gcc
pkgsStatic.libgcc
pkgsStatic.musl
];
nativeBuildInputs = with pkgs; [
(pkgs.symlinkJoin {
name = "rust-toolchain";
paths = with pkgs; [
rustc
cargo
rustPlatform.rustcSrc
rustfmt
clippy
cargo-expand
cargo-tarpaulin
];
})
gcc
gdb
pkgsStatic.gcc
gnumake
pkg-config
];
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
RUST_SRC_PATH = "${pkgs.rustPlatform.rustLibSrc}";
RUST_BACKTRACE = 1;
RUST_LOG = "all";
};
}
);

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

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

View file

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

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

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

View file

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

View file

@ -1,7 +1,5 @@
//! FFI slice helper
use std::ptr::NonNull;
/// Represents a span of memory (`&mut [u8]` ) as a struct.
///
/// # Safety
@ -11,28 +9,39 @@ use std::ptr::NonNull;
/// - accesses to the memory pointed to with `start` is never accessed outside `length`
/// - the lifetime of the `CByteSlice` does not outlive the memory it points to, as described in
/// the function returning this type.
/// - if `start` is NULL or `length` is 0, do not dereference `start`.
///
/// # Examples
///
/// ```c
/// ByteSlice empty = {.start: NULL, .length = 0};
/// ```
#[repr(C)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ByteSlice {
/// The start address of the memory.
pub start: NonNull<u8>,
pub start: *mut u8,
/// The amount of memory in bytes.
pub length: usize,
}
impl ByteSlice {
pub(crate) const INVALID: ByteSlice = ByteSlice {
start: std::ptr::null_mut(),
length: 0,
};
pub(crate) unsafe fn as_slice(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.start.as_ptr(), self.length) }
unsafe { std::slice::from_raw_parts(self.start, self.length) }
}
pub(crate) unsafe fn as_slice_mut(&mut self) -> &mut [u8] {
unsafe {
std::slice::from_raw_parts_mut(self.start.as_ptr(), self.length)
}
unsafe { std::slice::from_raw_parts_mut(self.start, self.length) }
}
pub(crate) unsafe fn from_slice(slice: &mut [u8]) -> Self {
Self {
start: NonNull::new(slice.as_mut_ptr()).unwrap(),
start: slice.as_mut_ptr(),
length: slice.len(),
}
}

View file

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

View file

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

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

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

View file

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

29
src/mem.rs Normal file
View file

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

View file

@ -1,33 +1,17 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice};
use servicepoint::{CommandCode, Header, Packet, TypedCommand};
use crate::{
containers::ByteSlice,
mem::{heap_clone, heap_drop, heap_move_nonnull, heap_move_ok},
};
use servicepoint::{CommandCode, Header, Packet};
use std::ptr::NonNull;
/// Turns a [TypedCommand] into a [Packet].
/// The [TypedCommand] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_packet_from_command(
command: NonNull<TypedCommand>,
) -> *mut Packet {
let command = unsafe { heap_remove(command) };
if let Ok(packet) = command.try_into() {
heap_move(packet)
} else {
std::ptr::null_mut()
}
}
/// Tries to load a [Packet] from the passed array with the specified length.
///
/// returns: NULL in case of an error, pointer to the allocated packet otherwise
#[no_mangle]
pub unsafe extern "C" fn sp_packet_try_load(data: ByteSlice) -> *mut Packet {
let data = unsafe { data.as_slice() };
match servicepoint::Packet::try_from(data) {
Err(_) => std::ptr::null_mut(),
Ok(packet) => heap_move(packet),
}
heap_move_ok(servicepoint::Packet::try_from(data))
}
/// Creates a raw [Packet] from parts.
@ -36,13 +20,12 @@ pub unsafe extern "C" fn sp_packet_try_load(data: ByteSlice) -> *mut Packet {
#[no_mangle]
pub unsafe extern "C" fn sp_packet_from_parts(
header: Header,
payload: *const ByteSlice,
payload: ByteSlice,
) -> NonNull<Packet> {
let payload = if payload.is_null() {
vec![]
let payload = if payload == ByteSlice::INVALID {
None
} else {
let payload = unsafe { (*payload).as_slice() };
Vec::from(payload)
Some(Vec::from(unsafe { payload.as_slice() }))
};
heap_move_nonnull(Packet { header, payload })
@ -55,17 +38,24 @@ pub unsafe extern "C" fn sp_packet_from_parts(
pub unsafe extern "C" fn sp_packet_get_header(
packet: NonNull<Packet>,
) -> NonNull<Header> {
NonNull::from(&mut unsafe { (*packet.as_ptr()).header })
NonNull::from(unsafe { &mut (*packet.as_ptr()).header })
}
/// Returns a pointer to the current payload of the provided packet.
///
/// Returns an [ByteSlice::INVALID] instance in case the packet does not have any payload.
///
/// The returned memory can be changed and will be valid until a new payload is set.
#[no_mangle]
pub unsafe extern "C" fn sp_packet_get_payload(
packet: NonNull<Packet>,
) -> ByteSlice {
unsafe { ByteSlice::from_slice(&mut (*packet.as_ptr()).payload) }
unsafe {
match &mut (*packet.as_ptr()).payload {
None => ByteSlice::INVALID,
Some(payload) => ByteSlice::from_slice(payload),
}
}
}
/// Sets the payload of the provided packet to the provided data.
@ -76,7 +66,13 @@ pub unsafe extern "C" fn sp_packet_set_payload(
packet: NonNull<Packet>,
data: ByteSlice,
) {
unsafe { (*packet.as_ptr()).payload = data.as_slice().to_vec() }
unsafe {
(*packet.as_ptr()).payload = if data == ByteSlice::INVALID {
None
} else {
Some(data.as_slice().to_vec())
}
}
}
/// Serialize the packet into the provided buffer.
@ -95,11 +91,13 @@ pub unsafe extern "C" fn sp_packet_serialize_to(
}
/// Clones a [Packet].
///
/// returns: a new [Packet] instance.
#[no_mangle]
pub unsafe extern "C" fn sp_packet_clone(
packet: NonNull<Packet>,
) -> NonNull<Packet> {
heap_move_nonnull(unsafe { packet.as_ref().clone() })
unsafe { heap_clone(packet) }
}
/// Deallocates a [Packet].

View file

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

View file

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