Compare commits

...
Author SHA1 Message Date
Vinzenz Schroeter
613f21310e fix rebase
Some checks failed
Rust / build (pull_request) Failing after 1m23s
2025-04-12 16:33:39 +02:00
Vinzenz Schroeter
7c8ede61b0 move generic safety information into README 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
0c3bc0b004 wip fix documentation 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
cf2c72de7c use brightness type from base crate 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
30bec50f7c use NotNull for parameters 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
b443adc3ab add /*notnull*/ comments in header 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
24ff341f9d re-export constants from base lib 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
35cb42df48 wip remove newtypes 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
5120e220ec functions for manipulating packets 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
d1ecd21114 wip remove newtypes 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
2ab80d395e cargo fmt 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
69bed7c665 wip 80k example 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
57d9e90b0f wip update to next servicepoint version 2025-04-12 16:25:20 +02:00
Vinzenz Schroeter
3c8eafecfb fix example path 2025-04-12 16:25:17 +02:00
Vinzenz Schroeter
65a26a9110 remove redundant infos
All checks were successful
Rust / build (push) Successful in 3m8s
2025-02-16 18:27:50 +01:00
Vinzenz Schroeter
ed8e362574 extend installation instructions, fix perm
All checks were successful
Rust / build (push) Successful in 3m8s
2025-02-16 18:17:08 +01:00
Vinzenz Schroeter
77a8a242bf simplify example
Some checks failed
Rust / build (push) Failing after 1m21s
2025-02-16 18:06:19 +01:00
30 changed files with 1967 additions and 3609 deletions

View file

@ -25,10 +25,20 @@ jobs:
- name: Install rust toolchain
run: sudo apt-get install -qy cargo rust-clippy
- name: install lzma
run: sudo apt-get update && sudo apt-get install -y liblzma-dev
run: sudo apt-get install -qy liblzma-dev
- name: install gcc
run: sudo apt-get install -qy gcc make
- name: Run Clippy
run: cargo clippy
- name: generate bindings
run: ./generate-binding.sh
- name: check that generated files did not change
run: output=$(git status --porcelain) && [ -z "$output" ]
- name: build
run: cargo build
- name: build example
run: cd example && make

View file

@ -1,31 +0,0 @@
# Contributing
Contributions are accepted in any form (issues, documentation, feature requests, code, review, ...).
All creatures welcome.
If you have access, please contribute on the [CCCB Forgejo](https://git.berlin.ccc.de/servicepoint/servicepoint).
Contributions on GitHub will be copied over and merged there.
## Pull requests
Feel free to create a PR, even if your change is not done yet.
Mark your PR as a draft as long as you do not want it to be merged.
The main branch is supposed to be a working version, including language bindings,
which means sometimes your PR may be merged into a temporary development branch.
Unit tests and documentation are required for the core library.
## Language bindings
Pull requests for your preferred language will be accepted.
If there is no code generator, it should call the C ABI methods provided by `servicepoint_binding_c`.
It should be able to send most of the basic commands in a way the simulator accepts, receiving is
not required for the merge.
It is okay for the feature set of a language binding to lag behind the one of the rust crate.
This also means you do not have to expose a feature to all the language bindings when adding something to the core.
If your change may break other language bindings, please note that in your PR description so someone can check them.

11
Cargo.lock generated
View file

@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "adler2"
@ -98,9 +98,9 @@ dependencies = [
[[package]]
name = "cbindgen"
version = "0.27.0"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fce8dd7fcfcbf3a0a87d8f515194b49d6135acab73e18bd380d1d93bb1a15eb"
checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff"
dependencies = [
"clap",
"heck",
@ -407,9 +407,8 @@ dependencies = [
[[package]]
name = "servicepoint"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93b52049be55a15fe37c13249d7f96aa8a5de56e1a41838e74a822ee8316a0c4"
version = "0.13.2"
source = "git+https://git.berlin.ccc.de/servicepoint/servicepoint/?branch=next#971bee5065139f220022e8108cfaa9c263b8a8a0"
dependencies = [
"bitvec",
"bzip2",

View file

@ -15,14 +15,31 @@ keywords = ["cccb", "cccb-servicepoint", "cbindgen"]
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
cbindgen = "0.27.0"
cbindgen = "0.28.0"
[dependencies.servicepoint]
version = "0.13.1"
features = ["all_compressions"]
package = "servicepoint"
version = "0.13.2"
default-features = false
features = ["protocol_udp"]
git = "https://git.berlin.ccc.de/servicepoint/servicepoint/"
branch = "next"
[features]
full = ["servicepoint/all_compressions", "servicepoint/default"]
default = ["full"]
[lints.rust]
missing-docs = "warn"
unsafe_op_in_unsafe_fn = "warn"
[package.metadata.docs.rs]
all-features = true
[profile.size-optimized]
inherits = "release"
opt-level = 'z' # Optimize for size
lto = true # Enable link-time optimization
codegen-units = 1 # Reduce number of codegen units to increase optimizations
panic = 'abort' # Abort on panic
strip = true # Strip symbols from binary

View file

@ -3,12 +3,12 @@
[![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)
[![GPLv3 licensed](https://img.shields.io/crates/l/servicepoint_binding_c)](./LICENSE)
In [CCCB](https://berlin.ccc.de/), there is a big pixel matrix hanging on the wall.
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".
This crate contains C bindings for the `servicepoint` library, enabling users to parse, encode and send packets to this display via UDP.
This crate contains C bindings for the [servicepoint](https://git.berlin.ccc.de/servicepoint/servicepoint) library, enabling users to parse, encode and send packets to this display via UDP.
## Examples
@ -43,21 +43,61 @@ Please specify the full version including patch in your Cargo.toml until 1.0 is
## Installation
Copy the header to your project and compile against.
1. Add this repo as a submodule:
```bash
git submodule add https://git.berlin.ccc.de/servicepoint/servicepoint-binding-c.git
git commit -m "add servicepoint-binding-c submodule"
```
2. Add a build step for the servicepoint library. If you use make, this could look something like this:
```
dependencies: FORCE
cargo build --manifest-path=servicepoint-binding-c/Cargo.toml --release
FORCE: ;
```
3. Link against the library. If you are on linux and linking statically:
```
${CC} main.c \
-I servicepoint-binding-c/include \
-L servicepoint-binding-c/target/release \
-Wl,-Bstatic -lservicepoint_binding_c \
-Wl,-Bdynamic -llzma \
-o out/example
```
You have the choice of linking statically (recommended) or dynamically.
- The C example shows how to link statically against the `staticlib` variant.
- When linked dynamically, you have to provide the `cdylib` at runtime in the _same_ version, as there are no API/ABI guarantees yet.
- When linked dynamically, you have to provide the `cdylib` at runtime in the _same_ version, as there are no API/ABI
guarantees yet.
## Notes on differences to rust library
- function names are: `sp_` \<struct_name\> \<rust name\>.
- Instances get consumed in the same way they do when writing rust code. Do not use an instance after an (implicit!) free.
- Instances get consumed in the same way they do when writing rust code. Do not use an instance after an (implicit!)
free.
- Option<T> or Result<T, E> turn into nullable return values - check for NULL!
- There are no specifics for C++ here yet. You might get a nicer header when generating directly for C++, but it should be usable.
- There are no specifics for C++ here yet. You might get a nicer header when generating directly for C++, but it should
be usable.
- Reading and writing to instances concurrently is not safe. Only reading concurrently is safe.
- documentation is included in the header and available [online](https://docs.rs/servicepoint_binding_c/latest/servicepoint_binding_c/)
- documentation is included in the header and
available [online](https://docs.rs/servicepoint_binding_c/latest/servicepoint_binding_c/)
## Safety
Functions expect that C code honors NonNull annotations.
Any created instances have to be freed in some way.
Pointers to those instances cannot be used anymore after that.
Instances cannot be shared between threads and need to be locked in the using code.
Enum values have to be used as-is. Do not pass values that are not part of the enum.
UTF-8 or UTF-32 encoding has to be used properly.
Brightness values provided as u8 parameters must be in range.
## Everything else
Look at the main project [README](https://git.berlin.ccc.de/servicepoint/servicepoint/src/branch/main/README.md) for further information.
Look at the main project [README](https://git.berlin.ccc.de/servicepoint/servicepoint/src/branch/main/README.md) for
further information.

View file

@ -1,41 +0,0 @@
# About the display
- Resolution: 352x160=56,320 pixels
- Pixels are grouped into 44x20=880 tiles (8x8=64 pixels each)
- Smallest addressable unit: row of pixels inside of a tile (8 pixels = 1 byte)
- The brightness can only be set per tile
- Screen content can be changed using a simple UDP protocol
- Between each row of tiles, there is a gap of around 4 pixels size. This gap changes the aspect ratio of the display.
### Binary format
A UDP package sent to the display has a header size of 10 bytes.
Each header value has a size of two bytes (unsigned 16 bit integer).
Depending on the command, there can be a payload following the header.
To change screen contents, these commands are the most relevant:
1. Clear screen
- command: `0x0002`
- (rest does not matter)
2. Send CP437 data: render specified text into rectangular region
- command: `0x0003`
- top left tile x
- top left tile y
- width in tiles
- height in tiles
- payload: (width in tiles * height in tiles) bytes
- 1 byte = 1 character
- each character is rendered into one tile (mono-spaced)
- characters are encoded using code page 437
3. Send bitmap window: set pixel states for a rectangular region
- command: `0x0013`
- top left tile x
- top left _pixel_ y
- width in tiles
- height in _pixels_
- payload: (width in tiles * height in pixels) bytes
- network byte order
- 1 bit = 1 pixel
There are other commands implemented as well, e.g. for changing the brightness.

View file

@ -6,28 +6,30 @@
use std::{env, fs::copy};
use cbindgen::{generate_with_config, Config};
fn main() {
let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
println!("cargo::rerun-if-changed={crate_dir}");
let config =
Config::from_file(crate_dir.clone() + "/cbindgen.toml").unwrap();
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";
generate_with_config(crate_dir, config)
.unwrap()
.write_to_file(&header_file);
println!("cargo:include={output_dir}");
if let Ok(bindings) = cbindgen::generate_with_config(crate_dir, config) {
bindings.write_to_file(&header_file);
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}");
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

@ -19,18 +19,27 @@ line_endings = "LF"
style = "type"
usize_is_size_t = true
# this is needed because otherwise the order in the C# bindings is different on different machines
# this is needed because otherwise the order in the C bindings is different on different machines
sort_by = "Name"
[parse]
parse_deps = false
parse_deps = true
include = ["servicepoint"]
extra_bindings = ["servicepoint"]
[parse.expand]
all_features = true
features = ["full"]
[export]
include = []
exclude = []
[export.rename]
"SpBitVec" = "BitVec"
"SpByteSlice" = "ByteSlice"
[enum]
rename_variants = "QualifiedScreamingSnakeCase"
[ptr]
non_null_attribute = "/*notnull*/"

73
example/Makefile Normal file
View file

@ -0,0 +1,73 @@
CC := gcc
CARGO := rustup run nightly cargo
THIS_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
REPO_ROOT := $(THIS_DIR)/..
RUST_TARGET_DIR := $(REPO_ROOT)/target/x86_64-unknown-linux-musl/size-optimized
RUSTFLAGS := -Zlocation-detail=none \
-Zfmt-debug=none \
-C linker=musl-gcc \
-C link-arg=-s \
-C link-arg=--gc-sections \
-C link-arg=-z,norelro \
-C link-arg=--hash-style=gnu \
--crate-type=staticlib \
-C panic=abort
CARGOFLAGS := --manifest-path=$(REPO_ROOT)/Cargo.toml \
--profile=size-optimized \
--no-default-features \
--target=x86_64-unknown-linux-musl \
-Zbuild-std="core,std,alloc,proc_macro,panic_abort" \
-Zbuild-std-features="panic_immediate_abort" \
CCFLAGS := -static -Os \
-ffunction-sections -fdata-sections \
-fwrapv -fomit-frame-pointer -fno-stack-protector\
-fwhole-program \
-nodefaultlibs -lservicepoint_binding_c -lc \
-Wl,--gc-sections \
-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
#-fuse-ld=gold \
-fno-exceptions
#-Wl,--icf=all \
export SERVICEPOINT_HEADER_OUT := $(REPO_ROOT)/include
build: out/example
clean:
rm -r out || true
rm include/servicepoint.h || true
cargo clean
run: out/example
out/example
PHONY: build clean dependencies run
out/example_unstripped: dependencies main.c
mkdir -p out || true
${CC} main.c \
-I $(SERVICEPOINT_HEADER_OUT) \
-L $(RUST_TARGET_DIR)\
$(CCFLAGS) \
-o out/example_unstripped
out/example: out/example_unstripped
strip -s -R .comment -R .gnu.version --strip-unneeded out/example_unstripped -o out/example
#strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag
dependencies: FORCE
mkdir -p include || true
# generate servicepoint header and binary to link against
${CARGO} rustc $(CARGOFLAGS) -- $(RUSTFLAGS)
FORCE: ;

28
example/main.c Normal file
View file

@ -0,0 +1,28 @@
#include <stdio.h>
#include "servicepoint.h"
int main(void) {
UdpConnection *connection = sp_connection_open("localhost:2342");
if (connection == NULL)
return 1;
Bitmap *pixels = sp_bitmap_new(PIXEL_WIDTH, PIXEL_HEIGHT);
if (pixels == NULL)
return 1;
sp_bitmap_fill(pixels, true);
TypedCommand *command = sp_command_bitmap_linear_win(0, 0, pixels, COMPRESSION_CODE_UNCOMPRESSED);
if (command == NULL)
return 1;
Packet *packet = sp_packet_from_command(command);
Header *header = sp_packet_get_header(packet);
printf("[%d, %d, %d, %d, %d]\n", header->command_code, header->a, header->b, header->c, header->d);
sp_connection_send_packet(connection, packet);
sp_connection_free(connection);
return 0;
}

View file

@ -1,14 +0,0 @@
[package]
name = "lang_c"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
test = false
[build-dependencies]
cc = "1.2"
[dependencies]
servicepoint_binding_c = { path = "../.." }

View file

@ -1,34 +0,0 @@
CC := gcc
THIS_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
REPO_ROOT := $(THIS_DIR)/../../../..
build: out/lang_c
clean:
rm -r out || true
rm include/servicepoint.h || true
cargo clean
run: out/lang_c
out/lang_c
PHONY: build clean dependencies run
out/lang_c: dependencies src/main.c
mkdir -p out || true
${CC} src/main.c \
-I include \
-L $(REPO_ROOT)/target/release \
-Wl,-Bstatic -lservicepoint_binding_c \
-Wl,-Bdynamic -llzma \
-o out/lang_c
dependencies: FORCE
mkdir -p include || true
# generate servicepoint header and binary to link against
SERVICEPOINT_HEADER_OUT=$(THIS_DIR)/include cargo build \
--manifest-path=$(REPO_ROOT)/crates/servicepoint_binding_c/Cargo.toml \
--release
FORCE: ;

View file

@ -1,17 +0,0 @@
const SP_INCLUDE: &str = "DEP_SERVICEPOINT_INCLUDE";
fn main() {
println!("cargo::rerun-if-changed=src/main.c");
println!("cargo::rerun-if-changed=build.rs");
println!("cargo::rerun-if-env-changed={SP_INCLUDE}");
let sp_include =
std::env::var_os(SP_INCLUDE).unwrap().into_string().unwrap();
// this builds a lib, this is only to check that the example compiles
let mut cc = cc::Build::new();
cc.file("src/main.c");
cc.include(&sp_include);
cc.opt_level(2);
cc.compile("lang_c");
}

File diff suppressed because it is too large Load diff

View file

@ -1 +0,0 @@

View file

@ -1,17 +0,0 @@
#include <stdio.h>
#include "servicepoint.h"
int main(void) {
SPConnection *connection = sp_connection_open("localhost:2342");
if (connection == NULL)
return 1;
SPBitmap *pixels = sp_bitmap_new(SP_PIXEL_WIDTH, SP_PIXEL_HEIGHT);
sp_bitmap_fill(pixels, true);
SPCommand *command = sp_command_bitmap_linear_win(0, 0, pixels, SP_COMPRESSION_CODE_UNCOMPRESSED);
sp_connection_send_command(connection, command);
sp_connection_free(connection);
return 0;
}

View file

@ -33,25 +33,35 @@
{ pkgs, system }:
{
default = pkgs.mkShell rec {
packages = with pkgs; [
buildInputs = with pkgs;[
xe
xz
libgcc
#glibc.static
musl
libunwind
];
nativeBuildInputs = with pkgs;[
(pkgs.symlinkJoin {
name = "rust-toolchain";
paths = with pkgs; [
rustc
cargo
rustPlatform.rustcSrc
rustfmt
clippy
#rustc
#cargo
#rustPlatform.rustcSrc
#rustfmt
#clippy
cargo-expand
cargo-tarpaulin
rustup
];
})
gcc
gnumake
xe
xz
pkg-config
];
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
};
}

6
generate-binding.sh Executable file
View file

@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -e
SCRIPT_PATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
SERVICEPOINT_HEADER_OUT="$SCRIPT_PATH/include" cargo build --release

1174
include/servicepoint.h Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,13 +1,22 @@
//! C functions for interacting with [SPBitmap]s
//!
//! prefix `sp_bitmap_`
use servicepoint::{DataRef, Grid};
use servicepoint::{Bitmap, DataRef, Grid};
use std::ptr::NonNull;
use crate::byte_slice::SPByteSlice;
use crate::byte_slice::ByteSlice;
/// A grid of pixels.
/// 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
///
@ -17,135 +26,65 @@ use crate::byte_slice::SPByteSlice;
/// sp_bitmap_set(grid, 0, 0, false);
/// sp_bitmap_free(grid);
/// ```
pub struct SPBitmap(pub(crate) servicepoint::Bitmap);
/// Creates a new [SPBitmap] with the specified dimensions.
///
/// # Arguments
///
/// - `width`: size in pixels in x-direction
/// - `height`: size in pixels in y-direction
///
/// returns: [SPBitmap] initialized to all pixels off. Will never return NULL.
///
/// # Panics
///
/// - when the width is not dividable by 8
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - the returned instance is freed in some way, either by using a consuming function or
/// by explicitly calling `sp_bitmap_free`.
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_new(
width: usize,
height: usize,
) -> NonNull<SPBitmap> {
let result = Box::new(SPBitmap(servicepoint::Bitmap::new(width, height)));
NonNull::from(Box::leak(result))
) -> *mut Bitmap {
if let Some(bitmap) = Bitmap::new(width, height) {
Box::leak(Box::new(bitmap))
} else {
std::ptr::null_mut()
}
}
/// Creates a new [SPBitmap] with a size matching the screen.
/// Creates a new [Bitmap] with a size matching the screen.
///
/// returns: [SPBitmap] initialized to all pixels off. Will never return NULL.
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - the returned instance is freed in some way, either by using a consuming function or
/// by explicitly calling [sp_bitmap_free].
/// returns: [Bitmap] initialized to all pixels off.
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_new_screen_sized() -> NonNull<SPBitmap> {
let result = Box::new(SPBitmap(servicepoint::Bitmap::max_sized()));
pub unsafe extern "C" fn sp_bitmap_new_screen_sized() -> NonNull<Bitmap> {
let result = Box::new(Bitmap::max_sized());
NonNull::from(Box::leak(result))
}
/// Loads a [SPBitmap] with the specified dimensions from the provided data.
/// 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: [SPBitmap] that contains a copy of the provided data. Will never return NULL.
///
/// # Panics
///
/// - when `data` is NULL
/// - when the dimensions and data size do not match exactly.
/// - when the width is not dividable by 8
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - `data` points to a valid memory location of at least `data_length` bytes in size.
/// - the returned instance is freed in some way, either by using a consuming function or
/// by explicitly calling `sp_bitmap_free`.
/// 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: *const u8,
data_length: usize,
) -> NonNull<SPBitmap> {
assert!(!data.is_null());
let data = std::slice::from_raw_parts(data, data_length);
let result =
Box::new(SPBitmap(servicepoint::Bitmap::load(width, height, data)));
NonNull::from(Box::leak(result))
data: ByteSlice,
) -> *mut Bitmap {
let data = unsafe { data.as_slice() };
if let Ok(bitmap) = Bitmap::load(width, height, data) {
Box::leak(Box::new(bitmap))
} else {
std::ptr::null_mut()
}
}
/// Clones a [SPBitmap].
///
/// Will never return NULL.
///
/// # Panics
///
/// - when `bitmap` is NULL
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - `bitmap` points to a valid [SPBitmap]
/// - `bitmap` is not written to concurrently
/// - the returned instance is freed in some way, either by using a consuming function or
/// by explicitly calling `sp_bitmap_free`.
/// Clones a [Bitmap].
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_clone(
bitmap: *const SPBitmap,
) -> NonNull<SPBitmap> {
assert!(!bitmap.is_null());
let result = Box::new(SPBitmap((*bitmap).0.clone()));
bitmap: NonNull<Bitmap>,
) -> NonNull<Bitmap> {
let result = Box::new(unsafe { bitmap.as_ref().clone() });
NonNull::from(Box::leak(result))
}
/// Deallocates a [SPBitmap].
///
/// # Panics
///
/// - when `bitmap` is NULL
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - `bitmap` points to a valid [SPBitmap]
/// - `bitmap` is not used concurrently or after bitmap call
/// - `bitmap` was not passed to another consuming function, e.g. to create a [SPCommand]
///
/// [SPCommand]: [crate::SPCommand]
/// Deallocates a [Bitmap].
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_free(bitmap: *mut SPBitmap) {
assert!(!bitmap.is_null());
_ = Box::from_raw(bitmap);
pub unsafe extern "C" fn sp_bitmap_free(bitmap: NonNull<Bitmap>) {
_ = unsafe { Box::from_raw(bitmap.as_ptr()) };
}
/// Gets the current value at the specified position in the [SPBitmap].
/// Gets the current value at the specified position in the [Bitmap].
///
/// # Arguments
///
@ -154,26 +93,17 @@ pub unsafe extern "C" fn sp_bitmap_free(bitmap: *mut SPBitmap) {
///
/// # Panics
///
/// - when `bitmap` is NULL
/// - when accessing `x` or `y` out of bounds
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - `bitmap` points to a valid [SPBitmap]
/// - `bitmap` is not written to concurrently
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_get(
bitmap: *const SPBitmap,
bitmap: NonNull<Bitmap>,
x: usize,
y: usize,
) -> bool {
assert!(!bitmap.is_null());
(*bitmap).0.get(x, y)
unsafe { bitmap.as_ref().get(x, y) }
}
/// Sets the value of the specified position in the [SPBitmap].
/// Sets the value of the specified position in the [Bitmap].
///
/// # Arguments
///
@ -181,54 +111,31 @@ pub unsafe extern "C" fn sp_bitmap_get(
/// - `x` and `y`: position of the cell
/// - `value`: the value to write to the cell
///
/// returns: old value of the cell
///
/// # Panics
///
/// - when `bitmap` is NULL
/// - when accessing `x` or `y` out of bounds
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - `bitmap` points to a valid [SPBitmap]
/// - `bitmap` is not written to or read from concurrently
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_set(
bitmap: *mut SPBitmap,
bitmap: NonNull<Bitmap>,
x: usize,
y: usize,
value: bool,
) {
assert!(!bitmap.is_null());
(*bitmap).0.set(x, y, value);
unsafe { (*bitmap.as_ptr()).set(x, y, value) };
}
/// Sets the state of all pixels in the [SPBitmap].
/// Sets the state of all pixels in the [Bitmap].
///
/// # Arguments
///
/// - `bitmap`: instance to write to
/// - `value`: the value to set all pixels to
///
/// # Panics
///
/// - when `bitmap` is NULL
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - `bitmap` points to a valid [SPBitmap]
/// - `bitmap` is not written to or read from concurrently
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_fill(bitmap: *mut SPBitmap, value: bool) {
assert!(!bitmap.is_null());
(*bitmap).0.fill(value);
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 [SPBitmap] instance.
/// Gets the width in pixels of the [Bitmap] instance.
///
/// # Arguments
///
@ -242,55 +149,28 @@ pub unsafe extern "C" fn sp_bitmap_fill(bitmap: *mut SPBitmap, value: bool) {
///
/// The caller has to make sure that:
///
/// - `bitmap` points to a valid [SPBitmap]
/// - `bitmap` points to a valid [Bitmap]
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_width(bitmap: *const SPBitmap) -> usize {
assert!(!bitmap.is_null());
(*bitmap).0.width()
pub unsafe extern "C" fn sp_bitmap_width(bitmap: NonNull<Bitmap>) -> usize {
unsafe { bitmap.as_ref().width() }
}
/// Gets the height in pixels of the [SPBitmap] instance.
/// Gets the height 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 [SPBitmap]
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_height(bitmap: *const SPBitmap) -> usize {
assert!(!bitmap.is_null());
(*bitmap).0.height()
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 [SPBitmap] instance.
/// Gets an unsafe reference to the data of the [Bitmap] instance.
///
/// # Panics
///
/// - when `bitmap` is NULL
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - `bitmap` points to a valid [SPBitmap]
/// - the returned memory range is never accessed after the passed [SPBitmap] has been freed
/// - the returned memory range is never accessed concurrently, either via the [SPBitmap] or directly
/// The returned memory is valid for the lifetime of the bitmap.
#[no_mangle]
pub unsafe extern "C" fn sp_bitmap_unsafe_data_ref(
bitmap: *mut SPBitmap,
) -> SPByteSlice {
assert!(!bitmap.is_null());
let data = (*bitmap).0.data_ref_mut();
SPByteSlice {
start: NonNull::new(data.as_mut_ptr_range().start).unwrap(),
length: data.len(),
}
mut bitmap: NonNull<Bitmap>,
) -> ByteSlice {
unsafe { ByteSlice::from_slice(bitmap.as_mut().data_ref_mut()) }
}

Some files were not shown because too many files have changed in this diff Show more