WIP: type per command #4

Draft
vinzenz wants to merge 49 commits from next into main
51 changed files with 4129 additions and 1987 deletions

View file

@ -30,15 +30,10 @@ jobs:
- name: build
run: cargo build
- name: generate bindings
run: ./generate-binding.sh
- name: check that generated files did not change
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 +47,14 @@ 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: install csbindgen
run: rustup run nightly cargo install cbindgen@0.29.0
- name: generate bindings
run: ./generate-binding.sh
- name: check that generated files did not change
run: output=$(git status --porcelain) && [ -z "$output" ]
- 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_*

166
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"
@ -97,9 +106,9 @@ dependencies = [
[[package]]
name = "cbindgen"
version = "0.28.0"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff"
checksum = "975982cdb7ad6a142be15bdf84aea7ec6a9e5d4d797c004d43185b24cfe4e684"
dependencies = [
"clap",
"heck",
@ -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",
@ -231,9 +263,9 @@ checksum = "84b26c544d002229e640969970a2e74021aadf6e2f96372b9c58eff97de08eb3"
[[package]]
name = "heck"
version = "0.4.1"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "indexmap"
@ -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,39 @@ 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 = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[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 +425,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 +526,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",
@ -430,9 +542,11 @@ dependencies = [
[[package]]
name = "servicepoint_binding_c"
version = "0.14.1"
version = "0.15.0"
dependencies = [
"cbindgen",
"env_logger",
"paste",
"servicepoint",
]
@ -467,9 +581,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 +755,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

@ -1,6 +1,6 @@
[package]
name = "servicepoint_binding_c"
version = "0.14.1"
version = "0.15.0"
publish = true
edition = "2021"
license = "GPL-3.0-or-later"
@ -8,23 +8,29 @@ description = "C bindings for the servicepoint crate."
homepage = "https://docs.rs/crate/servicepoint_binding_c"
repository = "https://git.berlin.ccc.de/servicepoint/servicepoint"
readme = "README.md"
links = "servicepoint"
keywords = ["cccb", "cccb-servicepoint", "cbindgen"]
[lib]
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
cbindgen = "0.28.0"
cbindgen = "0.29.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
[dependencies]
paste = "1.0.15"
[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 +42,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

@ -1,35 +0,0 @@
//! Build script generating the header for the `servicepoint` C library.
//!
//! When the environment variable `SERVICEPOINT_HEADER_OUT` is set, the header is copied there from
//! 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};
fn main() {
let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
println!("cargo::rerun-if-changed={crate_dir}");
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}");
}
} else {
eprintln!("cargo:warning=Servicepoint header could not be generated");
}
}

View file

@ -16,27 +16,30 @@ 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"]
crates = ["servicepoint_binding_c", "paste"]
features = []
[export]
include = []
exclude = []
exclude = ["BitVec"]
[export.rename]
"SpBitVec" = "BitVec"
"SpByteSlice" = "ByteSlice"
"SPCommand" = "Command"
"DisplayBitVec" = "BitVec"
[enum]
rename_variants = "QualifiedScreamingSnakeCase"

60
devShells.nix Normal file
View file

@ -0,0 +1,60 @@
{
pkgs,
fenix,
selfPkgs,
...
}:
let
defaultAdditionalPkgs = with pkgs; [
rustfmt
clippy
cargo-expand
cargo-tarpaulin
gdb
nix-output-monitor
];
in
(builtins.mapAttrs (
packageName: package:
pkgs.mkShell {
inputsFrom = [ package ];
packages = defaultAdditionalPkgs;
RUST_BACKTRACE = 1;
RUST_LOG = "all";
}
) selfPkgs)
// {
default = pkgs.mkShell {
inputsFrom = [
selfPkgs.servicepoint-binding-c
selfPkgs.announce
];
packages =
defaultAdditionalPkgs
++ (with pkgs; [
(pkgs.symlinkJoin {
name = "rust-toolchain";
paths = with pkgs; [
rustc
cargo
rustPlatform.rustcSrc
rustPlatform.rustLibSrc
rustfmt
clippy
cargo-expand
cargo-tarpaulin
];
})
gcc
gnumake
xe
libgcc
libunwind
pkgsStatic.gcc
pkgsStatic.libgcc
pkgsStatic.musl
]);
RUST_SRC_PATH = "${pkgs.rustPlatform.rustLibSrc}";
};
}

View file

@ -1,129 +1,121 @@
# 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
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
CARGOFLAGS += --manifest-path=$(REPO_ROOT)/Cargo.toml \
--profile=$(CARGO_PROFILE) \
--profile=$(_rust_cli_profile) \
--no-default-features \
--features=$(FEATURES) \
--target=$(TARGET)
--target=$(RUST_TARGET) \
--target-dir=cargo
ifneq ($(CFG_PROFILE), debug)
CCFLAGS += -ffunction-sections -fdata-sections -Wl,--gc-sections
STATIC_LINK_LIBS += -lservicepoint_binding_c
_servicepoint_cflags := -I $(REPO_ROOT)/include -L $(CARGO_OBJDIR)
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 := $(shell pkg-config --libs servicepoint --cflags || echo -I $(REPO_ROOT)/include -L $(CARGO_OBJDIR))
CFLAGS += $($(_libc)_CFLAGS) $($(_profile)_CFLAGS) $($(_link_type)_CFLAGS) $(_servicepoint_cflags)
ifeq ($(LTO), 1)
CFLAGS += -flto
endif
ifeq ($(_libc),gnu)
ifeq ($(_link_type),static)
CFLAGS += $(error "statically linking glibc is known to be broken")
endif
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
all: $(_bins)
.SUFFIXES:
clean: clean-c clean-rust
.PHONY: all build-rust
clean-c:
rm -r out || true
all: build-rust $(_bins)
clean-rust:
rm $(SERVICEPOINT_HEADER_OUT)/servicepoint.h || true
cargo clean
$(_unstripped_bins): %_unstripped : src/%.c src/helpers.h build-rust
$(CC) $< $(CFLAGS) -o $@
.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;
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);
}
sp_udp_send_packet(connection, packet);
void make_brightness_pattern(BrightnessGrid *grid) {
ByteSlice slice = sp_brightness_grid_data_ref_mut(grid);
for (size_t index = 0; index < slice.length; index++) {
slice.start[index] = (uint8_t)(index % ((size_t) Brightness_MAX));
}
}
int main(void) {
sock_init();
enable_all_pixels();
BrightnessGrid *grid = sp_brightness_grid_new(TILE_WIDTH, TILE_HEIGHT);
make_brightness_pattern(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));
}
Packet *packet = sp_cmd_brightness_grid_into_packet(sp_cmd_brightness_grid_from_grid(grid));
if (packet == NULL)
return -2;
packet = sp_brightness_grid_into_packet(grid, 0, 0);
sp_udp_send_packet(connection, packet);
sp_udp_free(connection);
sp_udp_send_packet(sock, packet);
return 0;
}

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

@ -0,0 +1,209 @@
#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);
}
bool log_command(struct Command command) {
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");
return true;
}
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_brightness(command.data.global_brightness);
printf("-> GlobalBrightnessCommand with params: brightness=%hu\n", brightness);
break;
}
default: {
printf("-> unknown command tag %d\n", command.tag);
break;
}
}
return false;
}
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_mut(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);
done = log_command(command);
sp_cmd_generic_free(command);
}
close(udp_socket);
exit(EXIT_SUCCESS);
}

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

@ -0,0 +1,44 @@
#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) {
if (msec < 0) {
errno = EINVAL;
return -1;
}
struct timespec ts = {
.tv_sec = msec / 1000,
.tv_nsec = (msec % 1000) * 1000000,
};
int res;
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)
@ -16,11 +15,9 @@ int main(void) {
if (packet == NULL)
return 1;
Header *header = sp_packet_get_header(packet);
Header *header = sp_packet_get_header_mut(packet);
printf("[%d, %d, %d, %d, %d]\n", header->command_code, header->a, header->b, header->c, header->d);
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

@ -1,25 +1,80 @@
{
"nodes": {
"fenix": {
"inputs": {
"nixpkgs": [
"nixpkgs"
],
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1748759782,
"narHash": "sha256-MJNhEBsAbxRp/53qsXv6/eaWkGS8zMGX9LuCz1BLeck=",
"owner": "nix-community",
"repo": "fenix",
"rev": "9be40ad995bac282160ff374a47eed67c74f9c2a",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "fenix",
"type": "github"
}
},
"nix-filter": {
"locked": {
"lastModified": 1731533336,
"narHash": "sha256-oRam5PS1vcrr5UPgALW0eo1m/5/pls27Z/pabHNy2Ms=",
"owner": "numtide",
"repo": "nix-filter",
"rev": "f7653272fd234696ae94229839a99b73c9ab7de0",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "nix-filter",
"type": "github"
}
},
"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"
}
},
"root": {
"inputs": {
"fenix": "fenix",
"nix-filter": "nix-filter",
"nixpkgs": "nixpkgs"
}
},
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1748695646,
"narHash": "sha256-VwSuuRF4NvAoeHZJRRlX8zAFZ+nZyuiIvmVqBAX0Bcg=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "2a388d1103450d814a84eda98efe89c01b158343",
"type": "github"
},
"original": {
"owner": "rust-lang",
"ref": "nightly",
"repo": "rust-analyzer",
"type": "github"
}
}
},
"root": "root",

View file

@ -2,16 +2,22 @@
description = "Flake for the servicepoint library.";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-24.11";
nixpkgs.url = "github:nixos/nixpkgs/nixos-25.05";
nix-filter.url = "github:numtide/nix-filter";
fenix = {
url = "github:nix-community/fenix";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs =
inputs@{
self,
nixpkgs,
fenix,
nix-filter
}:
let
lib = nixpkgs.lib;
supported-systems = [
"x86_64-linux"
"aarch64-linux"
@ -20,52 +26,20 @@
];
forAllSystems =
f:
lib.genAttrs supported-systems (
nixpkgs.lib.genAttrs supported-systems (
system:
f rec {
inherit system self;
pkgs = nixpkgs.legacyPackages.${system};
inherit system;
lib = pkgs.lib // nix-filter.lib;
fenix = inputs.fenix.packages.${system};
selfPkgs = self.packages.${system};
}
);
in
{
devShells = forAllSystems (
{ pkgs, system }:
{
default = pkgs.mkShell rec {
buildInputs = with pkgs; [
xe
xz
libgcc
libunwind
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}";
};
}
);
packages = forAllSystems (import ./packages.nix);
devShells = forAllSystems (import ./devShells.nix);
formatter = forAllSystems ({ pkgs, ... }: pkgs.nixfmt-rfc-style);
};
}

View file

@ -3,4 +3,4 @@ set -e
SCRIPT_PATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
SERVICEPOINT_HEADER_OUT="$SCRIPT_PATH/include" cargo build --release
cbindgen --config $SCRIPT_PATH/cbindgen.toml --crate servicepoint_binding_c --output $SCRIPT_PATH/include/servicepoint.h

File diff suppressed because it is too large Load diff

29
nix-build-all.sh Executable file
View file

@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -e
set -x
BUILD="nom build -L"
$BUILD .#servicepoint-binding-c -o result
$BUILD .#servicepoint-binding-c-stable-release -o result-stable-release
$BUILD .#servicepoint-binding-c-stable-size -o result-stable-size
$BUILD .#servicepoint-binding-c-nightly-release -o result-nightly-release
$BUILD .#all-examples -o result-examples
$BUILD .#all-examples-size -o result-examples-size
# works, but needs to bootstrap a C and Rust compiler
# $BUILD .#servicepoint-binding-c-musl-stable-release -o result-musl-release
# $BUILD .#servicepoint-binding-c-musl-stable-size -o result-musl-size
# $BUILD .#all-examples-musl-static -o result-examples-musl-static
# $BUILD .#all-examples-musl-static-size -o result-examples-musl-static-size
# $BUILD .#all-examples-musl -o result-examples-musl
# do not work yet:
# $BUILD .#servicepoint-binding-c-nightly-size -o result-nightly-size
# $BUILD .#servicepoint-binding-c-musl-nightly-release
# $BUILD .#servicepoint-binding-c-musl-nightly-size
# $BUILD .#all-examples-nightly-size -o result-examples-nightly-size

248
packages.nix Normal file
View file

@ -0,0 +1,248 @@
{
pkgs,
lib,
fenix,
selfPkgs,
...
}:
let
version = "0.15.0";
mkServicepoint =
{
rustPlatform,
pkgs,
buildType ? "release",
buildNoDefaultFeatures ? false,
cargoBuildFlags ? [ ],
nativeBuildInputs ? [],
stdlib ? false,
}:
rustPlatform.buildRustPackage (finalAttrs: {
inherit version buildType cargoBuildFlags stdlib;
pname = "servicepoint-binding-c";
src = lib.filter {
root = ./.;
include = [
./Cargo.lock
./Cargo.toml
./src
./include
./LICENSE
./cbindgen.toml
];
};
cargoLock.lockFile = ./Cargo.lock;
useFetchCargoVendor = true;
meta = {
description = "C bindings for the servicepoint crate.";
homepage = "https://git.berlin.ccc.de/servicepoint/servicepoint-binding-c";
license = lib.licenses.gpl3Plus;
pkgConfigModules = [ "servicepoint" ];
};
nativeBuildInputs = [ pkgs.pkg-config ] ++ nativeBuildInputs;
buildInputs = [ pkgs.xz ];
postInstall = ''
cp -r $src/include $out
mkdir -p $out/lib/pkgconfig
sed "s:\$out:$out:g" ${./servicepoint.pc.in} | sed "s:\$version:$version:g" > $out/lib/pkgconfig/servicepoint.pc
'';
});
mkExample =
{
name,
servicepointBinding,
pkgs,
EXTRA_CFLAGS ? "",
static ? false,
}:
let
staticPkgConfigParam = if static then "--static" else "";
in
pkgs.gccStdenv.mkDerivation {
inherit version EXTRA_CFLAGS;
pname = "servicepoint-c-example-${name}";
nativeBuildInputs = [ pkgs.pkg-config ];
buildInputs = [
servicepointBinding
pkgs.xz
];
src = ./example/src;
buildPhase = ''
set -e
set -x
mkdir -p $out/bin
$CC ${name}.c ${if static then "-static" else ""} $CFLAGS $EXTRA_CFLAGS \
$(pkg-config --libs --cflags ${staticPkgConfigParam} servicepoint) \
$(pkg-config --libs --cflags ${staticPkgConfigParam} liblzma) \
-o $out/bin/${name}
'';
};
examples = [
"announce"
"brightness_tester"
"header_logger"
"moving_line"
"random_stuff"
"wiping_clear"
];
mkAllExamples =
suffix:
pkgs.symlinkJoin {
name = "servicepoint-all-examples";
paths = builtins.map (e: selfPkgs."${e}${suffix}") examples;
};
size-cflags = [
"-Oz"
"-fwrapv"
"-fomit-frame-pointer"
"-fno-stack-protector"
"-fno-unroll-loops"
"-fno-unwind-tables"
"-fno-asynchronous-unwind-tables"
"-fmerge-all-constants"
"-fvisibility=hidden"
"-Bsymbolic"
"-fno-ident"
"-fno-exceptions"
"-ffunction-sections"
"-fdata-sections"
"-Wl,-z,norelro"
"-Wl,--hash-style=gnu"
"-Wl,--gc-sections"
"-Wl,--exclude-libs,ALL"
];
rustPlatform-stable = pkgs.rustPlatform;
rustPlatform-nightly = pkgs.makeRustPlatform fenix.complete;
rustPlatform-musl-stable = pkgs.pkgsMusl.rustPlatform;
rustPlatform-musl-nightly = pkgs.pkgsMusl.makeRustPlatform fenix.complete;
stable-release-args = {
inherit pkgs;
rustPlatform = rustPlatform-stable;
};
nightly-release-args = {
inherit pkgs;
rustPlatform = rustPlatform-nightly;
};
musl-stable-release-args = {
pkgs = pkgs.pkgsMusl;
rustPlatform = rustPlatform-musl-stable;
};
musl-nightly-release-args = {
pkgs = pkgs.pkgsMusl;
rustPlatform = rustPlatform-musl-nightly;
};
stable-size-args = {
buildType = "size_optimized";
buildNoDefaultFeatures = true;
};
nightly-size-args = {
cargoBuildFlags = [
"-Zbuild-std=core,std,alloc,proc_macro,panic_abort"
"-Zbuild-std-features=panic_immediate_abort"
];
stdlib = true;
# TODO: remove hard-coded target
nativeBuildInputs = [fenix.targets."x86_64-unknown-linux-gnu".latest.rust-std];
# TODO: those override the nix flags
# NIX_CFLAGS_COMPILE = builtins.toString ["-Oz" "-fwrapv" "-fomit-frame-pointer" "-fno-stack-protector" "-fno-unroll-loops" "-fno-unwind-tables" "-fno-asynchronous-unwind-tables" "-fmerge-all-constants" "-fvisibility=hidden" "-Bsymbolic" "-fno-ident" "-fno-exceptions" "-ffunction-sections" "-fdata-sections"];
# NIX_CFLAGS_LINK = builtins.toString ["Wl,-z,norelro" "-Wl,--hash-style=gnu" "-Wl,--gc-sections" "-Wl,--exclude-libs,ALL"];
};
in
rec {
servicepoint-binding-c-stable-release = mkServicepoint stable-release-args;
servicepoint-binding-c-nightly-release = mkServicepoint nightly-release-args;
servicepoint-binding-c-musl-stable-release = mkServicepoint musl-stable-release-args;
servicepoint-binding-c-musl-nightly-release = mkServicepoint musl-nightly-release-args;
servicepoint-binding-c-stable-size = mkServicepoint (stable-release-args // stable-size-args);
servicepoint-binding-c-nightly-size = mkServicepoint (
nightly-release-args // stable-size-args // nightly-size-args
);
servicepoint-binding-c-musl-stable-size = mkServicepoint (
musl-stable-release-args // stable-size-args
);
servicepoint-binding-c-musl-nightly-size = mkServicepoint (
musl-nightly-release-args // stable-size-args // nightly-size-args
);
# default variants
servicepoint-binding-c = servicepoint-binding-c-stable-release;
servicepoint-binding-c-musl = servicepoint-binding-c-musl-stable-release;
all-examples = mkAllExamples "";
all-examples-size = mkAllExamples "-size";
all-examples-nightly-size = mkAllExamples "-nightly-size";
# TODO: musl targets do not work on darwin
all-examples-musl = mkAllExamples "-musl";
all-examples-musl-static = mkAllExamples "-musl-static";
all-examples-musl-static-size = mkAllExamples "-musl-static-size";
}
# construct one package per example
// (lib.genAttrs examples (
name:
mkExample {
inherit name pkgs;
servicepointBinding = selfPkgs.servicepoint-binding-c;
}
))
# construct another pakage per example, but optimized for size with stable rust
// (lib.mapAttrs' (name: value: lib.nameValuePair ("${name}-size") value) (
lib.genAttrs examples (
name:
mkExample {
inherit name pkgs;
servicepointBinding = selfPkgs.servicepoint-binding-c-stable-size;
EXTRA_CFLAGS = builtins.toString size-cflags;
}
)
))
# construct another pakage per example, but optimized for size with unstable rust
// (lib.mapAttrs' (name: value: lib.nameValuePair ("${name}-unstable-size") value) (
lib.genAttrs examples (
name:
mkExample {
inherit name pkgs;
servicepointBinding = selfPkgs.servicepoint-binding-c-nightly-size;
EXTRA_CFLAGS = builtins.toString size-cflags;
}
)
))
# construct another pakage per example, but with musl
// (lib.mapAttrs' (name: value: lib.nameValuePair ("${name}-musl") value) (
lib.genAttrs examples (
name:
mkExample {
inherit name;
pkgs = pkgs.pkgsMusl;
servicepointBinding = selfPkgs.servicepoint-binding-c-musl-stable-release;
}
)
))
# construct another pakage per example, but statically linked with musl
// (lib.mapAttrs' (name: value: lib.nameValuePair ("${name}-musl-static") value) (
lib.genAttrs examples (
name:
mkExample {
inherit name;
pkgs = pkgs.pkgsMusl;
servicepointBinding = selfPkgs.servicepoint-binding-c-musl-stable-release;
static = true;
}
)
))
# construct another pakage per example, but statically linked with musl and size optimized
// (lib.mapAttrs' (name: value: lib.nameValuePair ("${name}-musl-static-size") value) (
lib.genAttrs examples (
name:
mkExample {
inherit name;
pkgs = pkgs.pkgsMusl;
servicepointBinding = selfPkgs.servicepoint-binding-c-musl-stable-size;
static = true;
EXTRA_CFLAGS = builtins.toString size-cflags;
}
)
))

6
servicepoint.pc.in Normal file
View file

@ -0,0 +1,6 @@
Name: servicepoint
Description: C bindings for the servicepoint library
Version: $version
URL: https://git.berlin.ccc.de/servicepoint/servicepoint-binding-c
Libs: -L$out/lib -lservicepoint_binding_c
Cflags: -I$out/include

View file

@ -1,226 +0,0 @@
use crate::byte_slice::ByteSlice;
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, SPBitVec};
use servicepoint::{
Bitmap, BitmapCommand, CompressionCode, DataRef, Grid, Origin, Packet,
};
use std::ptr::NonNull;
/// Creates a new [Bitmap] with the specified dimensions.
///
/// # Arguments
///
/// - `width`: size in pixels in x-direction
/// - `height`: size in pixels in y-direction
///
/// returns: [Bitmap] initialized to all pixels off, or NULL in case of an error.
///
/// # Errors
///
/// In the following cases, this function will return NULL:
///
/// - when the width is not dividable by 8
///
/// # Examples
///
/// ```C
/// Cp437Grid grid = sp_bitmap_new(8, 3);
/// sp_bitmap_fill(grid, true);
/// sp_bitmap_set(grid, 0, 0, false);
/// sp_bitmap_free(grid);
/// ```
#[no_mangle]
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()
}
}
/// Creates a new [Bitmap] with a size matching the screen.
///
/// returns: [Bitmap] initialized to all pixels off.
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_new_max_sized() -> NonNull<Bitmap> {
heap_move_nonnull(Bitmap::max_sized())
}
/// Loads a [Bitmap] with the specified dimensions from the provided data.
///
/// # Arguments
///
/// - `width`: size in pixels in x-direction
/// - `height`: size in pixels in y-direction
///
/// returns: [Bitmap] that contains a copy of the provided data, or NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_load(
width: usize,
height: usize,
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()
}
}
/// Tries to convert the BitVec to a Bitmap.
///
/// The provided BitVec gets consumed.
///
/// Returns NULL in case of error.
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_from_bitvec(
width: usize,
bitvec: NonNull<SPBitVec>,
) -> *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()
}
}
/// Clones a [Bitmap].
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_clone(
bitmap: NonNull<Bitmap>,
) -> NonNull<Bitmap> {
heap_move_nonnull(unsafe { bitmap.as_ref().clone() })
}
/// Deallocates a [Bitmap].
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_free(bitmap: NonNull<Bitmap>) {
unsafe { heap_drop(bitmap) }
}
/// Gets the current value at the specified position in the [Bitmap].
///
/// # Arguments
///
/// - `bitmap`: instance to read from
/// - `x` and `y`: position of the cell to read
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_get(
bitmap: NonNull<Bitmap>,
x: usize,
y: usize,
) -> bool {
unsafe { bitmap.as_ref().get(x, y) }
}
/// Sets the value of the specified position in the [Bitmap].
///
/// # Arguments
///
/// - `bitmap`: instance to write to
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_set(
bitmap: NonNull<Bitmap>,
x: usize,
y: usize,
value: bool,
) {
unsafe { (*bitmap.as_ptr()).set(x, y, value) };
}
/// Sets the state of all pixels in the [Bitmap].
///
/// # Arguments
///
/// - `bitmap`: instance to write to
/// - `value`: the value to set all pixels to
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_fill(bitmap: NonNull<Bitmap>, value: bool) {
unsafe { (*bitmap.as_ptr()).fill(value) };
}
/// Gets the width in pixels of the [Bitmap] instance.
///
/// # Arguments
///
/// - `bitmap`: instance to read from
///
/// # Panics
///
/// - when `bitmap` is NULL
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - `bitmap` points to a valid [Bitmap]
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_width(bitmap: NonNull<Bitmap>) -> usize {
unsafe { bitmap.as_ref().width() }
}
/// Gets the height in pixels of the [Bitmap] instance.
///
/// # Arguments
///
/// - `bitmap`: instance to read from
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_height(bitmap: NonNull<Bitmap>) -> usize {
unsafe { bitmap.as_ref().height() }
}
/// Gets an unsafe reference to the data of the [Bitmap] instance.
///
/// The returned memory is valid for the lifetime of the bitmap.
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_unsafe_data_ref(
mut bitmap: NonNull<Bitmap>,
) -> ByteSlice {
unsafe { ByteSlice::from_slice(bitmap.as_mut().data_ref_mut()) }
}
/// Consumes the Bitmap and returns the contained BitVec
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_into_bitvec(
bitmap: NonNull<Bitmap>,
) -> NonNull<SPBitVec> {
let bitmap = unsafe { heap_remove(bitmap) };
heap_move_nonnull(SPBitVec(bitmap.into()))
}
/// Creates a [BitmapCommand] and immediately turns that into a [Packet].
///
/// The provided [Bitmap] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_into_packet(
bitmap: NonNull<Bitmap>,
x: usize,
y: usize,
compression: CompressionCode,
) -> *mut Packet {
let bitmap = unsafe { heap_remove(bitmap) };
match Packet::try_from(BitmapCommand {
bitmap,
origin: Origin::new(x, y),
compression,
}) {
Ok(packet) => heap_move(packet),
Err(_) => std::ptr::null_mut(),
}
}

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

@ -1,197 +0,0 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice};
use servicepoint::{
Brightness, BrightnessGrid, BrightnessGridCommand, ByteGrid, DataRef, Grid,
Origin, Packet,
};
use std::mem::transmute;
use std::ptr::NonNull;
/// Creates a new [BrightnessGrid] with the specified dimensions.
///
/// returns: [BrightnessGrid] initialized to 0.
///
/// # Examples
/// ```C
/// UdpConnection connection = sp_udp_open("127.0.0.1:2342");
/// if (connection == NULL)
/// return 1;
///
/// 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);
/// sp_udp_free(connection);
/// ```
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_new(
width: usize,
height: usize,
) -> NonNull<BrightnessGrid> {
heap_move_nonnull(BrightnessGrid::new(width, height))
}
/// Loads a [BrightnessGrid] with the specified dimensions from the provided data.
///
/// Any out of range values will be set to [Brightness::MAX] or [Brightness::MIN].
///
/// returns: new [BrightnessGrid] instance, or NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_load(
width: usize,
height: usize,
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),
}
}
/// Clones a [BrightnessGrid].
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_clone(
brightness_grid: NonNull<BrightnessGrid>,
) -> NonNull<BrightnessGrid> {
heap_move_nonnull(unsafe { brightness_grid.as_ref().clone() })
}
/// Deallocates a [BrightnessGrid].
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_free(
brightness_grid: NonNull<BrightnessGrid>,
) {
unsafe { heap_drop(brightness_grid) }
}
/// Gets the current value at the specified position.
///
/// # Arguments
///
/// - `brightness_grid`: instance to read from
/// - `x` and `y`: position of the cell to read
///
/// returns: value at position
///
/// # Panics
/// - When accessing `x` or `y` out of bounds.
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_get(
brightness_grid: NonNull<BrightnessGrid>,
x: usize,
y: usize,
) -> Brightness {
unsafe { brightness_grid.as_ref().get(x, y) }
}
/// Sets the value of the specified position in the [BrightnessGrid].
///
/// # Arguments
///
/// - `brightness_grid`: instance to write to
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// returns: old value of the cell
///
/// # Panics
///
/// - When accessing `x` or `y` out of bounds.
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_set(
brightness_grid: NonNull<BrightnessGrid>,
x: usize,
y: usize,
value: Brightness,
) {
unsafe { (*brightness_grid.as_ptr()).set(x, y, value) };
}
/// Sets the value of all cells in the [BrightnessGrid].
///
/// # Arguments
///
/// - `brightness_grid`: instance to write to
/// - `value`: the value to set all cells to
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_fill(
brightness_grid: NonNull<BrightnessGrid>,
value: Brightness,
) {
unsafe { (*brightness_grid.as_ptr()).fill(value) };
}
/// Gets the width of the [BrightnessGrid] instance.
///
/// # Arguments
///
/// - `brightness_grid`: instance to read from
///
/// returns: width
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_width(
brightness_grid: NonNull<BrightnessGrid>,
) -> usize {
unsafe { brightness_grid.as_ref().width() }
}
/// Gets the height of the [BrightnessGrid] instance.
///
/// # Arguments
///
/// - `brightness_grid`: instance to read from
///
/// returns: height
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_height(
brightness_grid: NonNull<BrightnessGrid>,
) -> usize {
unsafe { brightness_grid.as_ref().height() }
}
/// Gets an unsafe reference to the data of the [BrightnessGrid] instance.
///
/// The returned memory is valid for the lifetime of the brightness grid.
///
/// # Arguments
///
/// - `brightness_grid`: instance to read from
///
/// returns: slice of bytes underlying the `brightness_grid`.
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_unsafe_data_ref(
brightness_grid: NonNull<BrightnessGrid>,
) -> ByteSlice {
//noinspection RsAssertEqual
const _: () = assert!(size_of::<Brightness>() == 1);
let data = unsafe { (*brightness_grid.as_ptr()).data_ref_mut() };
unsafe {
ByteSlice::from_slice(transmute::<&mut [Brightness], &mut [u8]>(data))
}
}
/// Creates a [BrightnessGridCommand] and immediately turns that into a [Packet].
///
/// The provided [BrightnessGrid] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_brightness_grid_into_packet(
grid: NonNull<BrightnessGrid>,
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
match Packet::try_from(BrightnessGridCommand {
grid,
origin: Origin::new(x, y),
}) {
Ok(packet) => heap_move(packet),
Err(_) => std::ptr::null_mut(),
}
}

View file

@ -1,155 +0,0 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice};
use servicepoint::{CharGrid, CharGridCommand, Grid, Origin, Packet};
use std::ptr::NonNull;
/// Creates a new [CharGrid] with the specified dimensions.
///
/// returns: [CharGrid] initialized to 0.
///
/// # Examples
///
/// ```C
/// CharGrid grid = sp_char_grid_new(4, 3);
/// sp_char_grid_fill(grid, '?');
/// sp_char_grid_set(grid, 0, 0, '!');
/// sp_char_grid_free(grid);
/// ```
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_new(
width: usize,
height: usize,
) -> NonNull<CharGrid> {
heap_move_nonnull(CharGrid::new(width, height))
}
/// Loads a [CharGrid] with the specified dimensions from the provided data.
///
/// returns: new CharGrid or NULL in case of an error
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_load(
width: usize,
height: usize,
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()
}
}
/// Clones a [CharGrid].
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_clone(
char_grid: NonNull<CharGrid>,
) -> NonNull<CharGrid> {
heap_move_nonnull(unsafe { char_grid.as_ref().clone() })
}
/// Deallocates a [CharGrid].
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_free(char_grid: NonNull<CharGrid>) {
unsafe { heap_drop(char_grid) }
}
/// Returns the current value at the specified position.
///
/// # Arguments
///
/// - `char_grid`: instance to read from
/// - `x` and `y`: position of the cell to read
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_get(
char_grid: NonNull<CharGrid>,
x: usize,
y: usize,
) -> u32 {
unsafe { char_grid.as_ref().get(x, y) as u32 }
}
/// Sets the value of the specified position in the [CharGrid].
///
/// # Arguments
///
/// - `char_grid`: instance to write to
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// returns: old value of the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_set(
char_grid: NonNull<CharGrid>,
x: usize,
y: usize,
value: u32,
) {
unsafe { (*char_grid.as_ptr()).set(x, y, char::from_u32(value).unwrap()) };
}
/// Sets the value of all cells in the [CharGrid].
///
/// # Arguments
///
/// - `char_grid`: instance to write to
/// - `value`: the value to set all cells to
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_fill(
char_grid: NonNull<CharGrid>,
value: u32,
) {
unsafe { (*char_grid.as_ptr()).fill(char::from_u32(value).unwrap()) };
}
/// Gets the width of the [CharGrid] instance.
///
/// # Arguments
///
/// - `char_grid`: instance to read from
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_width(
char_grid: NonNull<CharGrid>,
) -> usize {
unsafe { char_grid.as_ref().width() }
}
/// Gets the height of the [CharGrid] instance.
///
/// # Arguments
///
/// - `char_grid`: instance to read from
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_height(
char_grid: NonNull<CharGrid>,
) -> usize {
unsafe { char_grid.as_ref().height() }
}
/// Creates a [CharGridCommand] and immediately turns that into a [Packet].
///
/// The provided [CharGrid] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_char_grid_into_packet(
grid: NonNull<CharGrid>,
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
match Packet::try_from(CharGridCommand {
grid,
origin: Origin::new(x, y),
}) {
Ok(packet) => heap_move(packet),
Err(_) => std::ptr::null_mut(),
}
}

View file

@ -0,0 +1,56 @@
use crate::{
commands::wrap_origin_accessors,
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
};
use servicepoint::{Bitmap, BitmapCommand, CompressionCode, Origin, Packet};
use std::ptr::NonNull;
wrap_clone!(sp_cmd_bitmap::BitmapCommand);
wrap_free!(sp_cmd_bitmap::BitmapCommand);
wrap_fields!(sp_cmd_bitmap::BitmapCommand;
prop bitmap: Bitmap { mut get(); move set(value); };
prop compression: CompressionCode { get(); set(value); };
);
wrap_origin_accessors!(sp_cmd_bitmap::BitmapCommand);
wrap_functions!(sp_cmd_bitmap;
/// Sets a window of pixels to the specified values.
///
/// The passed [Bitmap] gets consumed.
///
/// Returns: a new [BitmapCommand] instance.
fn 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)`
fn 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.
fn try_into_packet(
command: NonNull<BitmapCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
);

View file

@ -0,0 +1,58 @@
use crate::{
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
};
use servicepoint::{
BinaryOperation, BitVecCommand, CompressionCode, DisplayBitVec, Offset,
Packet,
};
use std::ptr::NonNull;
wrap_clone!(sp_cmd_bitvec::BitVecCommand);
wrap_free!(sp_cmd_bitvec::BitVecCommand);
wrap_fields!(sp_cmd_bitvec::BitVecCommand;
prop bitvec: DisplayBitVec { mut get(); move set(value); };
prop offset: Offset { get(); set(value); };
prop operation: BinaryOperation { get(); set(value); };
prop compression: CompressionCode { get(); set(value); };
);
wrap_functions!(sp_cmd_bitvec;
/// 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.
fn 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.
fn try_into_packet(
command: NonNull<BitVecCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
);

View file

@ -0,0 +1,53 @@
use crate::{
commands::wrap_origin_accessors,
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
};
use servicepoint::{BrightnessGrid, BrightnessGridCommand, Origin, Packet};
use std::ptr::NonNull;
wrap_clone!(sp_cmd_brightness_grid::BrightnessGridCommand);
wrap_free!(sp_cmd_brightness_grid::BrightnessGridCommand);
wrap_fields!(sp_cmd_brightness_grid::BrightnessGridCommand;
prop grid: BrightnessGrid { mut get(); move set(grid); };
);
wrap_origin_accessors!(sp_cmd_brightness_grid::BrightnessGridCommand);
wrap_functions!(sp_cmd_brightness_grid;
/// Set the brightness of individual tiles in a rectangular area of the display.
///
/// The passed [BrightnessGrid] gets consumed.
///
/// Returns: a new [BrightnessGridCommand] instance.
fn 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.
fn 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.
fn into_packet(
command: NonNull<BrightnessGridCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
);

View file

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

View file

@ -0,0 +1,53 @@
use crate::{
commands::wrap_origin_accessors,
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
};
use servicepoint::{CharGrid, CharGridCommand, Origin, Packet};
use std::ptr::NonNull;
wrap_clone!(sp_cmd_char_grid::CharGridCommand);
wrap_free!(sp_cmd_char_grid::CharGridCommand);
wrap_fields!(sp_cmd_char_grid::CharGridCommand;
prop grid: CharGrid { mut get(); move set(grid); };
);
wrap_origin_accessors!(sp_cmd_char_grid::CharGridCommand);
wrap_functions!(sp_cmd_char_grid;
/// Show UTF-8 encoded text on the screen.
///
/// The passed [CharGrid] gets consumed.
///
/// Returns: a new [CharGridCommand] instance.
fn 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.
fn 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.
fn try_into_packet(
command: NonNull<CharGridCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
);

View file

@ -0,0 +1,53 @@
use crate::{
commands::wrap_origin_accessors,
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
};
use servicepoint::{Cp437Grid, Cp437GridCommand, Origin, Packet};
use std::ptr::NonNull;
wrap_clone!(sp_cmd_cp437_grid::Cp437GridCommand);
wrap_free!(sp_cmd_cp437_grid::Cp437GridCommand);
wrap_fields!(sp_cmd_cp437_grid::Cp437GridCommand;
prop grid: Cp437Grid { mut get(); move set(grid); };
);
wrap_origin_accessors!(sp_cmd_cp437_grid::Cp437GridCommand);
wrap_functions!(sp_cmd_cp437_grid;
/// 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.
fn 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.
fn 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.
fn try_into_packet(
command: NonNull<Cp437GridCommand>,
) -> *mut Packet {
heap_move_ok(unsafe { heap_remove(command) }.try_into())
}
);

View file

@ -0,0 +1,301 @@
use crate::{
macros::wrap_functions,
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() },
};
}
wrap_functions!(sp_cmd_generic;
/// 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.
fn 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.
fn clone(command: SPCommand) -> SPCommand {
unsafe {
match command.tag {
CommandTag::Clear => SPCommand {
tag: CommandTag::Clear,
data: CommandUnion {
clear: heap_clone(command.data.clear),
},
},
CommandTag::CharGrid => SPCommand {
tag: CommandTag::CharGrid,
data: CommandUnion {
char_grid: heap_clone(command.data.char_grid),
},
},
CommandTag::Cp437Grid => SPCommand {
tag: CommandTag::Cp437Grid,
data: CommandUnion {
cp437_grid: heap_clone(command.data.cp437_grid),
},
},
CommandTag::Bitmap => SPCommand {
tag: CommandTag::Bitmap,
data: CommandUnion {
bitmap: heap_clone(command.data.bitmap),
},
},
CommandTag::GlobalBrightness => SPCommand {
tag: CommandTag::GlobalBrightness,
data: CommandUnion {
global_brightness: heap_clone(
command.data.global_brightness,
),
},
},
CommandTag::BrightnessGrid => SPCommand {
tag: CommandTag::BrightnessGrid,
data: CommandUnion {
brightness_grid: heap_clone(command.data.brightness_grid),
},
},
CommandTag::BitVec => SPCommand {
tag: CommandTag::BitVec,
data: CommandUnion {
bitvec: heap_clone(command.data.bitvec),
},
},
CommandTag::HardReset => SPCommand {
tag: CommandTag::HardReset,
data: CommandUnion {
hard_reset: heap_clone(command.data.hard_reset),
},
},
CommandTag::FadeOut => SPCommand {
tag: CommandTag::FadeOut,
data: CommandUnion {
fade_out: heap_clone(command.data.fade_out),
},
},
#[allow(deprecated)]
CommandTag::BitmapLegacy => SPCommand {
tag: CommandTag::BitmapLegacy,
data: CommandUnion {
bitmap_legacy: heap_clone(command.data.bitmap_legacy),
},
},
CommandTag::Invalid => SPCommand::INVALID,
}
}
}
/// Deallocates an [SPCommand].
///
/// Commands with an invalid `tag` do not have to be freed as the `data` pointer should be null.
///
/// # Examples
///
/// ```C
/// SPCommand c = sp_cmd_clear_into_generic(sp_cmd_clear_new());
/// sp_command_free(c);
/// ```
fn free(command: SPCommand) {
unsafe {
match command.tag {
CommandTag::Invalid => (),
CommandTag::Bitmap => heap_drop(command.data.bitmap),
CommandTag::BitVec => heap_drop(command.data.bitvec),
CommandTag::BrightnessGrid => {
heap_drop(command.data.brightness_grid)
}
CommandTag::CharGrid => heap_drop(command.data.char_grid),
CommandTag::Cp437Grid => heap_drop(command.data.cp437_grid),
CommandTag::GlobalBrightness => {
heap_drop(command.data.global_brightness)
}
CommandTag::Clear => heap_drop(command.data.clear),
CommandTag::HardReset => heap_drop(command.data.hard_reset),
CommandTag::FadeOut => heap_drop(command.data.fade_out),
CommandTag::BitmapLegacy => heap_drop(command.data.bitmap_legacy),
}
}
}
/// Tries to turn a [SPCommand] into a [Packet].
/// The [SPCommand] gets consumed.
///
/// Returns tag [CommandTag::Invalid] in case of an error.
fn 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,33 @@
use crate::{
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions},
mem::{heap_move_nonnull, heap_remove},
};
use servicepoint::{Brightness, GlobalBrightnessCommand, Packet};
use std::ptr::NonNull;
wrap_functions!(sp_cmd_brightness_global;
/// Set the brightness of all tiles to the same value.
///
/// Returns: a new [GlobalBrightnessCommand] instance.
fn new(brightness: Brightness) -> NonNull<GlobalBrightnessCommand> {
heap_move_nonnull(GlobalBrightnessCommand::from(brightness))
}
/// Turns the command into a packet
fn into_packet(command: NonNull<GlobalBrightnessCommand>) -> NonNull<Packet> {
heap_move_nonnull(unsafe { heap_remove(command) }.into())
}
);
wrap_clone!(sp_cmd_brightness_global::GlobalBrightnessCommand);
wrap_free!(sp_cmd_brightness_global::GlobalBrightnessCommand);
wrap_fields!(
sp_cmd_brightness_global::GlobalBrightnessCommand;
prop brightness: Brightness {
get();
set(value);
};
);

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

@ -0,0 +1,47 @@
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::*;
macro_rules! wrap_origin_accessors {
( $prefix:ident :: $object_type:ty ) => {
$crate::macros::wrap_functions!($prefix;
#[doc = concat!(" Reads the origin field of the [`", stringify!($object_type), "`].")]
fn get_origin(
command: NonNull<$object_type>,
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;
}
}
#[doc = concat!(" Overwrites the origin field of the [`", stringify!($object_type), "`].")]
fn set_origin(
command: NonNull<$object_type>,
origin_x: usize,
origin_y: usize,
) {
unsafe {
$crate::macros::nonnull_as_mut!(command).origin = ::servicepoint::Origin::new(origin_x, origin_y);
}
}
);
};
}
pub(crate) use wrap_origin_accessors;

154
src/containers/bitmap.rs Normal file
View file

@ -0,0 +1,154 @@
use crate::{
containers::ByteSlice,
macros::{wrap_clone, wrap_free, wrap_functions, wrap_methods},
mem::{heap_move_nonnull, heap_move_ok, heap_move_some, heap_remove},
};
use servicepoint::{
Bitmap, BitmapCommand, CompressionCode, DataRef, DisplayBitVec, Grid,
Origin, Packet,
};
use std::ptr::NonNull;
wrap_clone!(sp_bitmap::Bitmap);
wrap_free!(sp_bitmap::Bitmap);
wrap_functions!(sp_bitmap;
/// Creates a new [Bitmap] with the specified dimensions.
///
/// # Arguments
///
/// - `width`: size in pixels in x-direction
/// - `height`: size in pixels in y-direction
///
/// returns: [Bitmap] initialized to all pixels off, or NULL in case of an error.
///
/// # Errors
///
/// In the following cases, this function will return NULL:
///
/// - when the width is not dividable by 8
///
/// # Examples
///
/// ```C
/// Cp437Grid grid = sp_bitmap_new(8, 3);
/// sp_bitmap_fill(grid, true);
/// sp_bitmap_set(grid, 0, 0, false);
/// sp_bitmap_free(grid);
/// ```
fn new(width: usize, height: usize) -> *mut Bitmap {
heap_move_some(Bitmap::new(width, height))
}
/// Creates a new [Bitmap] with a size matching the screen.
///
/// returns: [Bitmap] initialized to all pixels off.
fn new_max_sized() -> NonNull<Bitmap> {
heap_move_nonnull(Bitmap::max_sized())
}
/// Loads a [Bitmap] with the specified dimensions from the provided data.
///
/// # Arguments
///
/// - `width`: size in pixels in x-direction
/// - `height`: size in pixels in y-direction
///
/// returns: [Bitmap] that contains a copy of the provided data, or NULL in case of an error.
fn load(
width: usize,
height: usize,
data: ByteSlice,
) -> *mut Bitmap {
let data = unsafe { data.as_slice() };
heap_move_ok(Bitmap::load(width, height, data))
}
/// Tries to convert the BitVec to a Bitmap.
///
/// The provided BitVec gets consumed.
///
/// Returns NULL in case of error.
fn from_bitvec(
width: usize,
bitvec: NonNull<DisplayBitVec>,
) -> *mut Bitmap {
let bitvec = unsafe { heap_remove(bitvec) };
heap_move_ok(Bitmap::from_bitvec(width, bitvec))
}
/// Consumes the Bitmap and returns the contained BitVec.
fn into_bitvec(
bitmap: NonNull<Bitmap>
) -> NonNull<DisplayBitVec> {
let bitmap = unsafe { heap_remove(bitmap) };
heap_move_nonnull(bitmap.into())
}
/// Creates a [BitmapCommand] and immediately turns that into a [Packet].
///
/// The provided [Bitmap] gets consumed.
///
/// Returns NULL in case of an error.
fn into_packet(
bitmap: NonNull<Bitmap>,
x: usize,
y: usize,
compression: CompressionCode,
) -> *mut Packet {
let bitmap = unsafe { heap_remove(bitmap) };
heap_move_ok(Packet::try_from(BitmapCommand {
bitmap,
origin: Origin::new(x, y),
compression,
}))
}
);
wrap_methods!(
sp_bitmap::Bitmap;
/// Gets the current value at the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell to read
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
ref fn get(x: usize, y: usize) -> bool;
/// Sets the value of the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
mut fn set(x: usize, y: usize, value: bool);
/// Sets the state of all pixels in the [Bitmap].
///
/// # Arguments
///
/// - `value`: the value to set all pixels to
mut fn fill(value: bool);
/// Gets the width in pixels.
ref fn width() -> usize;
/// Gets the height in pixels.
ref fn height() -> usize;
/// Gets an unsafe reference to the data of the [Bitmap] instance.
///
/// The returned memory is valid for the lifetime of the bitmap.
mut fn data_ref_mut() -> ByteSlice {
return(slice) { unsafe { ByteSlice::from_slice(slice) } };
};
);

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

@ -0,0 +1,112 @@
use crate::{
containers::ByteSlice,
macros::{wrap_clone, wrap_free, wrap_functions, wrap_methods},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
};
use servicepoint::{
BinaryOperation, BitVecCommand, CompressionCode, DisplayBitVec, Packet,
};
use std::ptr::NonNull;
wrap_functions!(sp_bitvec;
/// 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.
fn 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.
fn load(data: ByteSlice) -> NonNull<DisplayBitVec> {
let data = unsafe { data.as_slice() };
heap_move_nonnull(DisplayBitVec::from_slice(data))
}
/// Creates a [BitVecCommand] and immediately turns that into a [Packet].
///
/// The provided [DisplayBitVec] gets consumed.
///
/// Returns NULL in case of an error.
fn 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,
}))
}
);
wrap_clone!(sp_bitvec::DisplayBitVec);
wrap_free!(sp_bitvec::DisplayBitVec);
wrap_methods!(
sp_bitvec::DisplayBitVec;
/// Gets the value of a bit.
///
/// # 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
ref fn get(index: usize) -> bool {
return(result) { result.map(|x| *x).unwrap_or(false) };
};
/// Sets the value of a bit.
///
/// # Arguments
///
/// - `index`: the bit index to edit
/// - `value`: the value to set the bit to
///
/// # Panics
///
/// - when accessing `index` out of bounds
mut fn set(index: usize, value: bool);
/// Sets the value of all bits.
///
/// # Arguments
///
/// - `value`: the value to set all bits to
mut fn fill(value: bool);
/// Gets the length in bits.
ref fn len() -> usize;
/// Returns true if length is 0.
ref fn is_empty() -> bool;
/// Gets an unsafe reference to the data of the [DisplayBitVec] instance.
///
/// The returned memory is valid for the lifetime of the bitvec.
mut fn as_raw_mut_slice() -> ByteSlice {
return(slice) { unsafe { ByteSlice::from_slice(slice) } };
};
);

View file

@ -0,0 +1,131 @@
use crate::macros::wrap_functions;
use crate::{
containers::ByteSlice,
macros::{wrap_clone, wrap_free, wrap_methods},
mem::{heap_move_nonnull, heap_move_ok, heap_move_some, heap_remove},
};
use servicepoint::{
Brightness, BrightnessGrid, BrightnessGridCommand, ByteGrid, DataRef, Grid,
Origin, Packet,
};
use std::{mem::transmute, ptr::NonNull};
wrap_functions!(sp_brightness_grid;
/// Creates a new [BrightnessGrid] with the specified dimensions.
///
/// returns: [BrightnessGrid] initialized to 0.
///
/// # Examples
/// ```C
/// UdpSocket *connection = sp_udp_open("127.0.0.1:2342");
/// if (connection == NULL)
/// return 1;
///
/// 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);
/// sp_udp_free(connection);
/// ```
fn new(
width: usize,
height: usize,
) -> NonNull<BrightnessGrid> {
heap_move_nonnull(BrightnessGrid::new(width, height))
}
/// Loads a [BrightnessGrid] with the specified dimensions from the provided data.
///
/// Any out of range values will be set to [Brightness::MAX] or [Brightness::MIN].
///
/// returns: new [BrightnessGrid] instance, or NULL in case of an error.
fn load(
width: usize,
height: usize,
data: ByteSlice,
) -> *mut BrightnessGrid {
let data = unsafe { data.as_slice() };
heap_move_some(
ByteGrid::load(width, height, data)
.map(move |grid| grid.map(Brightness::saturating_from)),
)
}
/// Creates a [BrightnessGridCommand] and immediately turns that into a [Packet].
///
/// The provided [BrightnessGrid] gets consumed.
///
/// Returns NULL in case of an error.
fn into_packet(
grid: NonNull<BrightnessGrid>,
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
heap_move_ok(Packet::try_from(BrightnessGridCommand {
grid,
origin: Origin::new(x, y),
}))
}
);
wrap_clone!(sp_brightness_grid::BrightnessGrid);
wrap_free!(sp_brightness_grid::BrightnessGrid);
wrap_methods!(
sp_brightness_grid::BrightnessGrid;
/// Gets the current value at the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell to read
///
/// returns: value at position
///
/// # Panics
/// - When accessing `x` or `y` out of bounds.
ref fn get(x: usize, y: usize) -> Brightness;
/// Sets the value of the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// returns: old value of the cell
///
/// # Panics
///
/// - When accessing `x` or `y` out of bounds.
mut fn set(x: usize, y: usize, value: Brightness);
/// Sets the value of all cells.
///
/// # Arguments
///
/// - `value`: the value to set all cells to
mut fn fill(value: Brightness);
/// Gets the width of the grid.
ref fn width() -> usize;
/// Gets the height of the grid.
ref fn height() -> usize;
/// Gets an unsafe reference to the data of the instance.
///
/// The returned memory is valid for the lifetime of the grid.
mut fn data_ref_mut() -> ByteSlice {
return(br_slice) { unsafe {
//noinspection RsAssertEqual
const _: () = assert!(size_of::<Brightness>() == 1);
ByteSlice::from_slice(transmute::<&mut [Brightness], &mut [u8]>(br_slice))
}};
};
);

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)
}
pub(crate) unsafe fn as_slice_mut(&self) -> &mut [u8] {
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(),
}
}

112
src/containers/char_grid.rs Normal file
View file

@ -0,0 +1,112 @@
use crate::{
containers::ByteSlice,
macros::{wrap_clone, wrap_free, wrap_functions, wrap_methods},
mem::{heap_move_nonnull, heap_move_ok, heap_remove},
};
use servicepoint::{CharGrid, CharGridCommand, Grid, Origin, Packet};
use std::ptr::NonNull;
wrap_functions!(sp_char_grid;
/// Creates a new [CharGrid] with the specified dimensions.
///
/// returns: [CharGrid] initialized to 0.
///
/// # Examples
///
/// ```C
/// CharGrid grid = sp_char_grid_new(4, 3);
/// sp_char_grid_fill(grid, '?');
/// sp_char_grid_set(grid, 0, 0, '!');
/// sp_char_grid_free(grid);
/// ```
fn new(
width: usize,
height: usize,
) -> NonNull<CharGrid> {
heap_move_nonnull(CharGrid::new(width, height))
}
/// Loads a [CharGrid] with the specified dimensions from the provided data.
///
/// returns: new CharGrid or NULL in case of an error
fn load(
width: usize,
height: usize,
data: ByteSlice,
) -> *mut CharGrid {
let data = unsafe { data.as_slice() };
heap_move_ok(CharGrid::load_utf8(width, height, data.to_vec()))
}
/// Creates a [CharGridCommand] and immediately turns that into a [Packet].
///
/// The provided [CharGrid] gets consumed.
///
/// Returns NULL in case of an error.
fn into_packet(
grid: NonNull<CharGrid>,
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
heap_move_ok(Packet::try_from(CharGridCommand {
grid,
origin: Origin::new(x, y),
}))
}
);
wrap_clone!(sp_char_grid::CharGrid);
wrap_free!(sp_char_grid::CharGrid);
wrap_methods!(
sp_char_grid::CharGrid;
/// Returns the current value at the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell to read
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
ref fn get(x: usize, y: usize) -> u32 {
return(char) { char as u32 };
};
/// Sets the value of the specified position in the grid.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// returns: old value of the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
/// - when providing values that cannot be converted to Rust's `char`.
mut fn set(x: usize, y: usize, value: u32) {
prepare(value) { char::from_u32(value).unwrap() };
};
/// Sets the value of all cells in the grid.
///
/// # Arguments
///
/// - `value`: the value to set all cells to
/// - when providing values that cannot be converted to Rust's `char`.
mut fn fill(value: u32) {
prepare(value) { char::from_u32(value).unwrap() };
};
/// Gets the width of the grid.
ref fn width() -> usize;
/// Gets the height of the grid.
ref fn height() -> usize;
);

View file

@ -0,0 +1,103 @@
use crate::macros::wrap_functions;
use crate::{
containers::ByteSlice,
macros::{wrap_clone, wrap_free, wrap_methods},
mem::{heap_move_nonnull, heap_move_ok, heap_move_some, heap_remove},
};
use servicepoint::{
Cp437Grid, Cp437GridCommand, DataRef, Grid, Origin, Packet,
};
use std::ptr::NonNull;
wrap_functions!(sp_cp437_grid;
/// Creates a new [Cp437Grid] with the specified dimensions.
///
/// returns: [Cp437Grid] initialized to 0.
fn new(
width: usize,
height: usize,
) -> NonNull<Cp437Grid> {
heap_move_nonnull(Cp437Grid::new(width, height))
}
/// Loads a [Cp437Grid] with the specified dimensions from the provided data.
fn load(
width: usize,
height: usize,
data: ByteSlice,
) -> *mut Cp437Grid {
let data = unsafe { data.as_slice() };
heap_move_some(Cp437Grid::load(width, height, data))
}
/// Creates a [Cp437GridCommand] and immediately turns that into a [Packet].
///
/// The provided [Cp437Grid] gets consumed.
///
/// Returns NULL in case of an error.
fn into_packet(
grid: NonNull<Cp437Grid>,
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
heap_move_ok(Packet::try_from(Cp437GridCommand {
grid,
origin: Origin::new(x, y),
}))
}
);
wrap_clone!(sp_cp437_grid::Cp437Grid);
wrap_free!(sp_cp437_grid::Cp437Grid);
wrap_methods!(
sp_cp437_grid::Cp437Grid;
/// Gets the current value at the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell to read
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
ref fn get(x: usize, y: usize) -> u8;
/// Sets the value at the specified position.
///
/// # Arguments
///
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// returns: old value of the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
mut fn set(x: usize, y: usize, value: u8);
/// Sets the value of all cells in the grid.
///
/// # Arguments
///
/// - `cp437_grid`: instance to write to
/// - `value`: the value to set all cells to
mut fn fill(value: u8);
/// Gets the width of the grid.
ref fn width() -> usize;
/// Gets the height of the grid.
ref fn height() -> usize;
/// Gets an unsafe reference to the data of the grid.
///
/// The returned memory is valid for the lifetime of the instance.
mut fn data_ref_mut() -> ByteSlice {
return(slice) { unsafe { ByteSlice::from_slice(slice) } };
};
);

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

@ -1,157 +0,0 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice};
use servicepoint::{
Cp437Grid, Cp437GridCommand, DataRef, Grid, Origin, Packet,
};
use std::ptr::NonNull;
/// Creates a new [Cp437Grid] with the specified dimensions.
///
/// returns: [Cp437Grid] initialized to 0.
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_new(
width: usize,
height: usize,
) -> NonNull<Cp437Grid> {
heap_move_nonnull(Cp437Grid::new(width, height))
}
/// Loads a [Cp437Grid] with the specified dimensions from the provided data.
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_load(
width: usize,
height: usize,
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()
}
}
/// Clones a [Cp437Grid].
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_clone(
cp437_grid: NonNull<Cp437Grid>,
) -> NonNull<Cp437Grid> {
heap_move_nonnull(unsafe { cp437_grid.as_ref().clone() })
}
/// Deallocates a [Cp437Grid].
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_free(cp437_grid: NonNull<Cp437Grid>) {
unsafe { heap_drop(cp437_grid) }
}
/// Gets the current value at the specified position.
///
/// # Arguments
///
/// - `cp437_grid`: instance to read from
/// - `x` and `y`: position of the cell to read
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_get(
cp437_grid: NonNull<Cp437Grid>,
x: usize,
y: usize,
) -> u8 {
unsafe { cp437_grid.as_ref().get(x, y) }
}
/// Sets the value of the specified position in the [Cp437Grid].
///
/// # Arguments
///
/// - `cp437_grid`: instance to write to
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// returns: old value of the cell
///
/// # Panics
///
/// - when accessing `x` or `y` out of bounds
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_set(
cp437_grid: NonNull<Cp437Grid>,
x: usize,
y: usize,
value: u8,
) {
unsafe { (*cp437_grid.as_ptr()).set(x, y, value) };
}
/// Sets the value of all cells in the [Cp437Grid].
///
/// # Arguments
///
/// - `cp437_grid`: instance to write to
/// - `value`: the value to set all cells to
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_fill(
cp437_grid: NonNull<Cp437Grid>,
value: u8,
) {
unsafe { (*cp437_grid.as_ptr()).fill(value) };
}
/// Gets the width of the [Cp437Grid] instance.
///
/// # Arguments
///
/// - `cp437_grid`: instance to read from
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_width(
cp437_grid: NonNull<Cp437Grid>,
) -> usize {
unsafe { cp437_grid.as_ref().width() }
}
/// Gets the height of the [Cp437Grid] instance.
///
/// # Arguments
///
/// - `cp437_grid`: instance to read from
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_height(
cp437_grid: NonNull<Cp437Grid>,
) -> usize {
unsafe { cp437_grid.as_ref().height() }
}
/// Gets an unsafe reference to the data of the [Cp437Grid] instance.
///
/// The returned memory is valid for the lifetime of the grid.
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_unsafe_data_ref(
cp437_grid: NonNull<Cp437Grid>,
) -> ByteSlice {
unsafe { ByteSlice::from_slice((*cp437_grid.as_ptr()).data_ref_mut()) }
}
/// Creates a [Cp437GridCommand] and immediately turns that into a [Packet].
///
/// The provided [Cp437Grid] gets consumed.
///
/// Returns NULL in case of an error.
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_into_packet(
grid: NonNull<Cp437Grid>,
x: usize,
y: usize,
) -> *mut Packet {
let grid = unsafe { heap_remove(grid) };
match Packet::try_from(Cp437GridCommand {
grid,
origin: Origin::new(x, y),
}) {
Ok(packet) => heap_move(packet),
Err(_) => std::ptr::null_mut(),
}
}

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,35 @@
//! }
//! ```
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;
mod macros;
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 {
use crate::macros::wrap_functions;
wrap_functions!(sp_envlogger;
/// 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/).
fn init() {
env_logger::init();
}
);
}

239
src/macros.rs Normal file
View file

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

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,128 +1,103 @@
use crate::{heap_drop, heap_move, heap_move_nonnull, heap_remove, ByteSlice};
use servicepoint::{CommandCode, Header, Packet, TypedCommand};
use crate::{
containers::ByteSlice,
macros::{wrap_clone, wrap_fields, wrap_free, wrap_functions},
mem::{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()
wrap_functions!(sp_packet;
/// Tries to load a [Packet] from the passed array with the specified length.
///
/// returns: NULL in case of an error, pointer to the allocated packet otherwise
fn try_load(data: ByteSlice) -> *mut Packet {
let data = unsafe { data.as_slice() };
heap_move_ok(servicepoint::Packet::try_from(data))
}
}
/// 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),
/// Creates a raw [Packet] from parts.
///
/// returns: new instance. Will never return null.
fn from_parts(header: Header, payload: ByteSlice) -> NonNull<Packet> {
let payload = if payload == ByteSlice::INVALID {
None
} else {
Some(Vec::from(unsafe { payload.as_slice() }))
};
heap_move_nonnull(Packet { header, payload })
}
}
/// Creates a raw [Packet] from parts.
///
/// returns: new instance. Will never return null.
#[no_mangle]
pub unsafe extern "C" fn sp_packet_from_parts(
header: Header,
payload: *const ByteSlice,
) -> NonNull<Packet> {
let payload = if payload.is_null() {
vec![]
} else {
let payload = unsafe { (*payload).as_slice() };
Vec::from(payload)
};
heap_move_nonnull(Packet { header, payload })
}
/// Returns a pointer to the header field of the provided packet.
///
/// The returned header can be changed and will be valid for the lifetime of the packet.
#[no_mangle]
pub unsafe extern "C" fn sp_packet_get_header(
packet: NonNull<Packet>,
) -> NonNull<Header> {
NonNull::from(&mut unsafe { (*packet.as_ptr()).header })
}
/// Returns a pointer to the current payload of the provided packet.
///
/// 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) }
}
/// Sets the payload of the provided packet to the provided data.
///
/// This makes previous payload pointers invalid.
#[no_mangle]
pub unsafe extern "C" fn sp_packet_set_payload(
packet: NonNull<Packet>,
data: ByteSlice,
) {
unsafe { (*packet.as_ptr()).payload = data.as_slice().to_vec() }
}
/// Serialize the packet into the provided buffer.
///
/// # Panics
///
/// - if the buffer is not big enough to hold header+payload.
#[no_mangle]
pub unsafe extern "C" fn sp_packet_serialize_to(
packet: NonNull<Packet>,
mut buffer: ByteSlice,
) {
unsafe {
packet.as_ref().serialize_to(buffer.as_slice_mut());
}
}
/// Clones a [Packet].
#[no_mangle]
pub unsafe extern "C" fn sp_packet_clone(
packet: NonNull<Packet>,
) -> NonNull<Packet> {
heap_move_nonnull(unsafe { packet.as_ref().clone() })
}
/// Deallocates a [Packet].
#[no_mangle]
pub unsafe extern "C" fn sp_packet_free(packet: NonNull<Packet>) {
unsafe { heap_drop(packet) }
}
/// Converts u16 into [CommandCode].
///
/// If the provided value is not valid, false is returned and result is not changed.
#[no_mangle]
pub unsafe extern "C" fn sp_u16_to_command_code(
code: u16,
result: *mut CommandCode,
) -> bool {
match CommandCode::try_from(code) {
Ok(code) => {
unsafe {
*result = code;
/// 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.
fn get_payload(packet: NonNull<Packet>) -> ByteSlice {
unsafe {
match &mut (*packet.as_ptr()).payload {
None => ByteSlice::INVALID,
Some(payload) => ByteSlice::from_slice(payload),
}
true
}
Err(_) => false,
}
}
/// Sets the payload of the provided packet to the provided data.
///
/// This makes previous payload pointers invalid.
fn set_payload(packet: NonNull<Packet>, data: ByteSlice) {
unsafe {
(*packet.as_ptr()).payload = if data == ByteSlice::INVALID {
None
} else {
Some(data.as_slice().to_vec())
}
}
}
/// Serialize the packet into the provided buffer.
///
/// # Panics
///
/// - if the buffer is not big enough to hold header+payload.
fn serialize_to(packet: NonNull<Packet>, buffer: ByteSlice) -> usize {
unsafe {
packet.as_ref().serialize_to(buffer.as_slice_mut()).unwrap_or(0)
}
}
);
wrap_clone!(sp_packet::Packet);
wrap_free!(sp_packet::Packet);
wrap_fields!(
sp_packet::Packet;
prop header: Header {
get();
mut get();
set(value);
};
);
wrap_functions!(sp;
/// Converts u16 into [CommandCode].
///
/// If the provided value is not valid, false is returned and result is not changed.
fn u16_to_command_code(
code: u16,
result: *mut CommandCode,
) -> bool {
match CommandCode::try_from(code) {
Ok(code) => {
unsafe {
*result = code;
}
true
}
Err(_) => false,
}
}
);

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,119 +1,131 @@
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},
macros::{wrap_free, wrap_functions},
mem::{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].
///
/// returns: NULL if connection fails, or connected instance
///
/// # Examples
///
/// ```C
/// UdpConnection connection = sp_udp_open("172.23.42.29:2342");
/// if (connection != NULL)
/// sp_udp_send_command(connection, sp_command_clear());
/// ```
#[no_mangle]
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,
};
wrap_free!(sp_udp::UdpSocket);
heap_move(connection)
}
wrap_functions!(sp_udp;
/// Creates a new instance of [UdpConnection].
///
/// returns: NULL if connection fails, or connected instance
///
/// # Examples
///
/// ```C
/// UdpConnection connection = sp_udp_open_ipv4(172, 23, 42, 29, 2342);
/// if (connection != NULL)
/// sp_udp_send_command(connection, sp_command_clear());
/// ```
#[no_mangle]
pub unsafe extern "C" fn sp_udp_open_ipv4(
ip1: u8,
ip2: u8,
ip3: u8,
ip4: u8,
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)
}
/// Creates a new instance of [UdpSocket].
///
/// returns: NULL if connection fails, or connected instance
///
/// # Examples
///
/// ```C
/// UdpSocket connection = sp_udp_open("172.23.42.29:2342");
/// if (connection != NULL)
/// sp_udp_send_command(connection, sp_command_clear());
/// ```
fn open(host: NonNull<c_char>) -> *mut UdpSocket {
let host = unsafe { CStr::from_ptr(host.as_ptr()) }
.to_str()
.expect("Bad encoding");
/// Sends a [Packet] to the display using the [UdpConnection].
///
/// The passed `packet` gets consumed.
///
/// returns: true in case of success
#[no_mangle]
pub unsafe extern "C" fn sp_udp_send_packet(
connection: NonNull<UdpSocket>,
packet: NonNull<Packet>,
) -> bool {
let packet = unsafe { heap_remove(packet) };
unsafe { connection.as_ref().send(&Vec::from(packet)) }.is_ok()
}
heap_move_ok(UdpSocket::bind_connect(host))
}
/// Sends a [TypedCommand] to the display using the [UdpConnection].
///
/// The passed `command` gets consumed.
///
/// returns: true in case of success
///
/// # Examples
///
/// ```C
/// sp_udp_send_command(connection, sp_command_brightness(5));
/// ```
#[no_mangle]
pub unsafe extern "C" fn sp_udp_send_command(
connection: NonNull<UdpSocket>,
command: NonNull<TypedCommand>,
) -> bool {
let command = unsafe { heap_remove(command) };
unsafe { connection.as_ref().send_command(command) }.is_some()
}
/// Creates a new instance of [UdpSocket].
///
/// returns: NULL if connection fails, or connected instance
///
/// # Examples
///
/// ```C
/// UdpSocket connection = sp_udp_open_ipv4(172, 23, 42, 29, 2342);
/// if (connection != NULL)
/// sp_udp_send_command(connection, sp_command_clear());
/// ```
fn open_ipv4(ip1: u8, ip2: u8, ip3: u8, ip4: u8, port: u16) -> *mut UdpSocket {
let addr = SocketAddrV4::new(Ipv4Addr::from([ip1, ip2, ip3, ip4]), port);
heap_move_ok(UdpSocket::bind_connect(addr))
}
/// Sends a [Header] to the display using the [UdpConnection].
///
/// returns: true in case of success
///
/// # Examples
///
/// ```C
/// sp_udp_send_header(connection, sp_command_brightness(5));
/// ```
#[no_mangle]
pub unsafe extern "C" fn sp_udp_send_header(
udp_connection: NonNull<UdpSocket>,
header: Header,
) -> bool {
let packet = Packet {
header,
payload: vec![],
};
unsafe { udp_connection.as_ref() }
.send(&Vec::from(packet))
.is_ok()
}
/// Sends a [Packet] to the display using the [UdpSocket].
///
/// The passed `packet` gets consumed.
///
/// returns: true in case of success
fn send_packet(connection: NonNull<UdpSocket>, packet: NonNull<Packet>) -> bool {
let packet = unsafe { heap_remove(packet) };
unsafe { connection.as_ref().send(&Vec::from(packet)) }.is_ok()
}
/// Closes and deallocates a [UdpConnection].
#[no_mangle]
pub unsafe extern "C" fn sp_udp_free(connection: NonNull<UdpSocket>) {
unsafe { heap_drop(connection) }
}
/// Sends a [SPCommand] to the display using the [UdpSocket].
///
/// The passed `command` gets consumed.
///
/// returns: true in case of success
///
/// # Examples
///
/// ```C
/// sp_udp_send_command(connection, sp_command_brightness(5));
/// ```
fn send_command(connection: NonNull<UdpSocket>, command: SPCommand) -> bool {
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 [UdpSocket].
///
/// returns: true in case of success
///
/// # Examples
///
/// ```C
/// sp_udp_send_header(connection, sp_command_brightness(5));
/// ```
fn send_header(udp_connection: NonNull<UdpSocket>, header: Header) -> bool {
let packet = Packet {
header,
payload: None,
};
unsafe { udp_connection.as_ref() }
.send(&Vec::from(packet))
.is_ok()
}
);