diff --git a/CHANGELOG.md b/CHANGELOG.md index f5a5c5c..f979ccf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,14 +8,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed -- Rejected NaN on scaled pack paths with `-PPACK_ERR_INVALARG`. Previously a NaN source value (or a NaN scaled result from the scale/offset arithmetic) reached a float-to-integer cast, which is undefined behaviour; ±infinity continues to saturate to the clamp bounds. Locked down with dedicated non-finite tests for every scaled type. +- Return `-PPACK_ERR_INVALARG` when a scaled field produces a NaN result during packing. A NaN source value or a NaN from the scale/offset calculation previously reached a float-to-integer cast. That is undefined behaviour. Positive and negative infinity saturate to the clamp bounds as before. + +Added non-finite tests for every scaled type. ### Changed -- Resolved the required MISRA C:2023 violations for Rules 10.4, 10.7 and 10.8 through unsigned suffixes and temporary variables for composite expressions. -- Centralised the type-erased struct-member copies in internal `ppack_member_write` / `ppack_member_read` helpers; Rule 21.15 is now deviated at exactly three documented sites (the two helpers and the deliberate F32 `float`/`uint32_t` pun) rather than silenced per call site. -- Resolved advisory Rule 12.1 findings by making operator precedence explicit with parentheses. -- Moved `PPACK_PAYLOAD_UNITS` from `ppack_platform.h` to `ppack.h` to explicitly surface it as part of the public API. Include `ppack.h` (the documented entry point) rather than `ppack_platform.h` directly. +- Fixed MISRA C:2023 Rule 10.4, 10.7, and 10.8 violations with unsigned suffixes and temporary variables in composite expressions. +- Moved the type-erased struct-member copies into internal `ppack_member_write` and `ppack_member_read` helper functions. + +Rule 21.15 deviations are now at exactly three documented sites: the two helpers and the deliberate F32 `float`/`uint32_t` pun. The library no longer suppresses this rule per call site. +- Made operator precedence explicit with parentheses to resolve advisory MISRA C:2023 Rule 12.1 findings. +- Moved `PPACK_PAYLOAD_UNITS` from `ppack_platform.h` to `ppack.h`. This macro is part of the public API. + +Include `ppack.h` in your code. Do not include `ppack_platform.h` directly. - Updated `README.md` and `CONTRIBUTING.md` to describe the tool-driven MISRA workflow. ### Removed @@ -24,21 +30,36 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added -- Adopted `misch` (cppcheck-backed MISRA C:2023 analysis) via `misra.toml`. The audit is clean; all deviations (advisory Rules 2.5, 8.7, 11.5, 15.5, 18.4 and required Rule 21.15) are justified at point of use with `cppcheck-suppress` `@deviation` comments or project-wide in `misra-deviations.txt`. -- Added a compile-time guard that `float` is exactly 32 bits (`PPACK_TYPE_F32` wire-format prerequisite). -- Added `-fsanitize=float-cast-overflow` to the CI sanitizer jobs: GCC does not include the float-to-integer conversion check in `-fsanitize=undefined`, leaving the Linux jobs blind to that UB class. -- Raised the CI coverage gate from 80% line / 70% branch to 100% / 100%, matching what the suite achieves. -- Documented error-path semantics for `ppack_pack` / `ppack_unpack` (destination contents are unspecified after a non-zero return) and clarified the 16-bit MAU `PPACK_TYPE_UINT8` storage contract (unpack zeroes the upper 8 bits of the member's storage unit). +- Added `misch` (cppcheck-backed MISRA C:2023 analysis) via `misra.toml`. + +The audit reports zero findings. All deviations (advisory Rules 2.5, 8.7, 11.5, 15.5, 18.4 and required Rule 21.15) are justified at point of use with `cppcheck-suppress` and `@deviation` comments or project-wide in `misra-deviations.txt`. +- Added a compile-time check that `float` is 32 bits. This is required for the `PPACK_TYPE_F32` wire format. +- Added `-fsanitize=float-cast-overflow` to the CI sanitizer jobs. + +GCC does not check float-to-integer conversions with `-fsanitize=undefined`. This flag covers that undefined behaviour class on Linux. +- Raised the CI coverage gate from 80% line and 70% branch to 100% for both metrics. The test suite meets this level already. +- Added documentation for the `ppack_pack` and `ppack_unpack` error paths. + +The destination buffer contains unspecified data after a non-zero return. + +Clarified the 16-bit MAU `PPACK_TYPE_UINT8` storage contract. +The unpack function zeroes the upper 8 bits of the member's storage unit. ## [2.3.0] - 2026-06-19 ### Changed -- Aligned the memory layout on 16-bit MAU platforms to one octet per addressable unit to ensure seamless interoperability with the `ucrc` CRC library. -- Decoupled logical payload units from physical MAU size, ensuring `PPACK_ADDR_UNIT_BITS` is always 8. -- Updated documentation to use generic "16-bit MAU" terminology instead of vendor-specific references. -- Changed the default `build_tests` Meson option to `false`; CI continues to opt into tests explicitly with `-Dbuild_tests=true`. -- Adjusted the CI coverage gate to the shared primitive baseline of 80% line / 70% branch coverage. +- Changed the memory layout on 16-bit MAU platforms to one octet per addressable unit. + +The ppack wire format matches the ucrc CRC library. +- Separated logical payload units from physical MAU size. + +`PPACK_ADDR_UNIT_BITS` is always 8. +- Replaced vendor-specific platform names with "16-bit MAU" in the documentation. +- Changed the default `build_tests` Meson option to `false`. + +CI enables tests explicitly with `-Dbuild_tests=true`. +- Set the CI coverage gate to 80% line and 70% branch coverage. This matches the shared baseline for all primitives in this repository. ## [2.2.0] - 2026-04-28 @@ -56,10 +77,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed -- Renamed `enum ppack_type` constants from `S*` / `U*` names to ``-style `INT*` / `UINT*` names. This is a source-compatibility break only; the wire format is unchanged. +- Renamed the `enum ppack_type` constants from `S*` and `U*` style to `` style (`INT*` and `UINT*`). + +This breaks source compatibility. The wire format does not change. ## [1.4.1] - 2026-04-25 ### Added -- First public release with `ppack_pack` / `ppack_unpack`, fixed-size 64-bit payload serialisation, bit-aligned field definitions, raw and scaled modes, 8-bit / 16-bit addressable-unit support, MISRA deviation documentation, and CI coverage gates. +- First public release. + +Initial features: `ppack_pack`, `ppack_unpack`, fixed-size 64-bit payloads, bit-aligned field definitions, raw and scaled modes, 8-bit and 16-bit addressable-unit support, MISRA deviation documentation, and CI coverage gates. diff --git a/README.md b/README.md index 7c9b36a..72c0f26 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,18 @@ [![CI](https://github.com/aajll/ppack/actions/workflows/ci.yml/badge.svg)](https://github.com/aajll/ppack/actions/workflows/ci.yml) -A generic payload serialisation library for bit-aligned data fields in C. +ppack packs and unpacks structures into bit-aligned payloads of up to 512 bits. ## Features -- **Bit-aligned fields** - Fields can start at any bit position and span arbitrary bit ranges -- **Variable payload size** - Caller supplies the payload size in bits (multiple of 8, up to 512); supports CAN classic (64) and CAN-FD (up to 512) -- **No dynamic memory** - Fixed-size operations, no `malloc` / `free` -- **Deterministic WCET** - All operations have bounded execution time -- **Scaled fields** - Linear scale/offset transformations for physical-unit encoding -- **Multiple types** - Supports `u8`, `u16`, `i16`, `u32`, `i32`, `f32`, and raw bitfields -- **Cross-platform** - Works on any C11 target with an 8-bit or 16-bit minimum addressable unit; auto-detected from `` with no chip-specific code paths -- **Error codes** - All APIs return explicit error codes; no `errno`, no exceptions +- **Bit-aligned fields** — Place each field at any bit position in the payload. +- **Variable payload size** — Pass the payload size in bits (multiple of 8, up to 512). Covers CAN classic (64) and CAN-FD (up to 512). +- **No dynamic memory** — All operations use fixed-size buffers. The library does not call `malloc` or `free`. +- **Bounded execution time** — Execution time is deterministic when field descriptors are `static const`. +- **Scaled fields** — Apply linear scale/offset transformations for physical-unit encoding. +- **Multiple types** — Supports `uint8_t`, `uint16_t`, `int16_t`, `uint32_t`, `int32_t`, `float`, and raw bitfields. +- **Cross-platform** — Runs on any C11 target with an 8-bit or 16-bit minimum addressable unit. The library detects the platform from ``. There are no chip-specific code paths. +- **Error codes** — All functions return explicit error codes. The library does not use `errno` or exceptions. ## Requirements @@ -100,9 +100,9 @@ int main(void) engine_data_t tx = {.rpm = 3000, .temperature = -10, .voltage = 12.5f}; engine_data_t rx = {0}; - /* Pack structure into a 64-bit payload (CAN classic). The third - * argument is the payload size in bits — pass 128, 256, 512, - * etc. for CAN-FD or other larger frames. */ + /* Pack the structure into a 64-bit payload (CAN classic). + * The third argument is the payload size in bits. + * Pass 128, 256, or 512 for CAN-FD frames. */ int ret = ppack_pack(&tx, payload, 64, fields, 3); if (ret != PPACK_SUCCESS) { return ret; @@ -115,7 +115,7 @@ int main(void) } ``` -`ppack_byte_t[PPACK_PAYLOAD_UNITS]` defaults to a 64-bit payload (`uint8_t[8]` on byte-addressable targets, `uint16_t[8]` on 16-bit MAU targets) and is intended as a convenience for the common case. For non-default sizes, override `PPACK_PAYLOAD_BITS` at the toolchain level (e.g. `-DPPACK_PAYLOAD_BITS=512`) or size the buffer manually as `ppack_byte_t payload[N / PPACK_ADDR_UNIT_BITS]`. The wire format is identical across MAU sizes. +`ppack_byte_t[PPACK_PAYLOAD_UNITS]` declares a 64-bit payload by default (`uint8_t[8]` on byte-addressable targets, `uint16_t[8]` on 16-bit MAU targets). Override `PPACK_PAYLOAD_BITS` at the toolchain level (for example, `-DPPACK_PAYLOAD_BITS=512`) or size the buffer manually as `ppack_byte_t payload[N / PPACK_ADDR_UNIT_BITS]`. The wire format is identical across MAU sizes. ### CAN-FD (512-bit) example @@ -183,7 +183,7 @@ meson compile -C build meson test -C build --verbose ``` -The test target runs twice: once natively (8-bit MAU) and once with `-DPPACK_SIMULATE_16BIT_MAU` to exercise the word-addressable code path that runs on 16-bit MAU platforms. +The test target runs twice. It runs once natively (8-bit MAU) and once with `-DPPACK_SIMULATE_16BIT_MAU` to exercise the 16-bit MAU code path. ### Code coverage @@ -198,7 +198,7 @@ gcovr --root . --filter 'src/' --filter 'include/' --print-summary gcovr --root . --filter 'src/' --filter 'include/' --html-details build_cov/coverage.html ``` -CI gates on 100% line and 100% branch coverage. The library's safety case depends on every reachable code path being exercised by an explicit test; any drop from this baseline is a deliberate decision that must be approved alongside a justification for the new gap. +CI requires 100% line coverage and 100% branch coverage. Every reachable code path has an explicit test. A drop below this baseline requires approval and a justification. ## API Reference @@ -258,12 +258,12 @@ Functions return the negated error code on failure (e.g. `-PPACK_ERR_NULLPTR`). The payload is `payload_bits` bits long (a multiple of 8, between 8 and 512), addressed as `payload_bits / 8` logical bytes numbered 0 to `payload_bits / 8 - 1`. -- **Bit numbering**: payload bit `N` lives in logical byte `N / 8`, at position `N mod 8` within that byte. -- **Within a byte**: bit 0 is the least significant bit. -- **Multi-byte fields**: little-endian (Intel ordering, equivalent to DBC `byte_order=1`). A field at `start_bit=0`, `bit_length=16` with value `0x1234` produces `0x34` in byte 0 and `0x12` in byte 1. +- **Bit numbering**: payload bit `N` is in logical byte `N / 8`. The bit position inside that byte is `N mod 8`. +- **Bit order within a byte**: bit 0 is the least significant bit. +- **Multi-byte fields**: little-endian byte order. This matches DBC `byte_order=1`. A 16-bit field at `start_bit=0` with value `0x1234` writes `0x34` to byte 0 and `0x12` to byte 1. - **Cross-platform**: the format is identical on byte-addressable and 16-bit-MAU hosts. Two nodes using ppack interoperate regardless of their addressable-unit size, provided they agree on `payload_bits`. -`PPACK_TYPE_F32` is a raw 32-bit IEEE-754 bit copy. The wire bytes are the host's `uint32_t` byte order. This is interoperable between any two little-endian hosts (e.g. x86_64, ARM Cortex-M, AArch64 in default mode, 16-bit MAU platforms) but NOT between a little-endian and a big-endian host without explicit byte swapping in user code. +`PPACK_TYPE_F32` copies 32 IEEE-754 bits directly. The wire bytes follow the host `uint32_t` byte order. Any two little-endian hosts interoperate (for example, x86_64, ARM Cortex-M, AArch64, 16-bit MAU platforms). Little-endian and big-endian hosts do not interoperate without explicit byte swapping in user code. ## Scaled Fields @@ -274,29 +274,31 @@ raw = (physical - offset) / scale /* pack: float -> integer */ physical = (float)raw * scale + offset /* unpack: integer -> float */ ``` -This encodes floating-point physical values into compact integer fields, e.g. voltage in 0.01 V/LSB or temperature with -40 °C offset and 0.25 °C resolution. +This encodes a floating-point physical value into a compact integer field. Examples include voltage at 0.01 V/LSB and temperature with a -40 °C offset and 0.25 °C resolution. ### Saturation -Pack silently clamps the integer value to the destination type's representable range. For example, `PPACK_TYPE_UINT16` clamps to `0..65535` and `PPACK_TYPE_INT16` clamps to `-32768..32767`. Out-of-range physical inputs do NOT produce an error. +ppack_pack clamps the raw integer value to the destination type's range. `PPACK_TYPE_UINT16` clamps to `0..65535`. `PPACK_TYPE_INT16` clamps to `-32768..32767`. Out-of-range inputs do not return an error. -For `PPACK_TYPE_UINT32` and `PPACK_TYPE_INT32` scaled fields, the float clamp uses `4294967040` (largest float exactly representable below `UINT32_MAX`) and `2147483520` (largest float below `INT32_MAX`). The true type maxima `UINT32_MAX` and `INT32_MAX` round up to `2^32` / `2^31` as 32-bit floats and would overflow the destination cast. +For `PPACK_TYPE_UINT32` scaled fields, ppack_pack clamps to `4294967040`. This is the largest float value that fits in a `uint32_t`. For `PPACK_TYPE_INT32`, it clamps to `2147483520`. The values `UINT32_MAX` and `INT32_MAX` round up to `2^32` or `2^31` as 32-bit floats. That would overflow the destination cast. -For safety-critical applications where an out-of-range physical value MUST be detected, validate the input at the call site before calling `ppack_pack`. +Validate the input at the call site if your application must detect out-of-range physical values. ### Non-finite values -Pack rejects a scaled field whose scaled result is NaN (a NaN source value, or a NaN produced by the scale/offset arithmetic) with `-PPACK_ERR_INVALARG`; NaN has no defined integer representation. Positive and negative infinity are treated like any other out-of-range value and saturate to the clamp bounds above. `PPACK_TYPE_F32` fields are a raw bit-copy and carry NaN/infinity payloads unchanged. +ppack_pack rejects a scaled field when the result is NaN. The function returns `-PPACK_ERR_INVALARG`. NaN can come from the source value or the scale/offset calculation. NaN has no valid integer representation. + +Positive and negative infinity saturate to the type's clamp bounds. `PPACK_TYPE_F32` fields copy bits directly. They carry NaN and infinity values unchanged. ### Quantization -The float-to-integer cast in pack truncates toward zero (C standard cast semantics). The maximum round-trip error is one LSB, equal to `scale`. For round-to-nearest behaviour, pre-add `0.5f * scale * sign(physical)` at the call site before pack. +ppack_pack truncates the float-to-integer cast toward zero (standard C cast rules). The maximum round-trip error is one LSB, equal to `scale`. Add `0.5f * scale * sign(physical)` at the call site for round-to-nearest behaviour. ## Platform Support ### Supported architectures -ppack works on any toolchain meeting the requirements below. There are no chip-specific code paths; the library auto-detects the addressing model from the standard library headers. +ppack runs on any toolchain that meets the requirements below. The library detects the addressing model from the standard library headers. There are no chip-specific code paths. | Requirement | Notes | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------ | @@ -305,11 +307,11 @@ ppack works on any toolchain meeting the requirements below. There are no chip-s | Two's-complement signed integers | Required for the documented sign-extension and unsigned-to-signed cast behaviour. Universal on real targets. | | IEEE-754 binary32 `float` | Required for `PPACK_TYPE_F32` and scaled fields. Universal on real targets. | -Targets meeting these requirements are expected to work, including (but not limited to) x86_64, AArch64, ARMv7-M, ARMv8-M, RISC-V, AVR, and 16-bit MAU platforms. +Expected targets include x86_64, AArch64, ARMv7-M, ARMv8-M, RISC-V, AVR, and 16-bit MAU platforms. ### Validated configurations -These configurations are run through the test suite or have been verified on hardware: +The test suite runs these configurations, or they are verified on hardware: | Toolchain | Target | Status | | -------------------------------------------- | ------------------------- | ----------------------------------------------------------------- | @@ -317,7 +319,7 @@ These configurations are run through the test suite or have been verified on har | GCC, Clang with `-DPPACK_SIMULATE_16BIT_MAU` | x86_64 Linux | Run in CI (16-bit MAU code path) | | Native Toolchains | 16-bit MAU platforms | Code path covered by host simulation; no live cross-compile in CI | -Other architectures from the supported list above are expected to work but are not yet routinely validated. If you bring up ppack on a new target, please report back so the table can be extended. +Other architectures from the list above should work but are not yet tested routinely. Report results from new targets to extend this table. ### 16-bit-MAU specifics @@ -345,36 +347,38 @@ All public APIs validate arguments at the function boundary. - A `PPACK_BEHAVIOUR_SCALED` request on a `PPACK_TYPE_UINT8` field returns `-PPACK_ERR_INVALARG`. - An unrecognised field type returns `-PPACK_ERR_NOTFOUND`. -`bit_length` is range-checked against the absolute field limit (1..32) and against the runtime payload limit (`bit_length <= payload_bits - start_bit`). It is NOT cross-checked against the natural width of the field's `type`. Declaring a `PPACK_TYPE_UINT16` with `bit_length=24` is accepted by the library; only the low 16 bits are meaningful, with the upper bits zero or sign-extended depending on type. Match `bit_length` to the type's natural width unless you have a specific reason not to. +`bit_length` must be between 1 and 32 and fit within the payload (`bit_length <= payload_bits - start_bit`). The library does not check `bit_length` against the natural width of the field's `type`. A `PPACK_TYPE_UINT16` with `bit_length=24` passes validation. Only the low 16 bits carry data. Match `bit_length` to the type's natural width unless you have a specific reason. ## Use Cases -1. **Protocol Encoding** - Compact data for CAN, I2C, or custom binary protocols -2. **Register Access** - Safe manipulation of peripheral register layouts -3. **Telemetry Frames** - Serialise sensor data into fixed-size telemetry packets -4. **Cross-platform IPC** - Deterministic binary serialisation between heterogeneous targets +1. **Protocol encoding** — Pack data for CAN, I2C, or custom binary protocols. +2. **Register access** — Read and write peripheral register layouts safely. +3. **Telemetry frames** — Encode sensor data into fixed-size telemetry packets. +4. **Cross-platform IPC** — Exchange deterministic binary data between different targets. ## Limitations -ppack is a serialisation primitive only. The following are explicitly out of scope: +ppack packs and unpacks data. It does not perform the tasks below: -- **No integrity checks**: no CRC, checksum, or framing. Caller (or the transport, e.g. the CAN frame CRC) is responsible for detecting bit errors. -- **No schema versioning**: the field-descriptor layout is the schema. Maintain it in shared headers across nodes. -- **Payload size capped at 512 bits**: matches a full CAN-FD frame data field. Larger payloads require multiple ppack calls on chunks. -- **No multi-buffer / streaming API**: a single payload is processed in one call. -- **No runtime endianness adaptation**: the wire format is little-endian. Big-endian hosts would need explicit byte swapping at the boundary (no such host is currently a target). +- **No integrity checks**: ppack does not compute a CRC, checksum, or frame header. The caller detects bit errors. Use the transport layer for error detection (for example, CAN frame CRC). +- **No schema versioning**: the field-descriptor layout is the schema. Store it in shared headers across nodes. +- **Payload size capped at 512 bits**: this matches a full CAN-FD frame data field. Send larger payloads with multiple ppack calls on separate chunks. +- **No multi-buffer API**: ppack processes one payload per call. +- **No runtime endianness adaptation**: the wire format uses little-endian byte order. A big-endian host needs explicit byte swapping at the boundary. ## Notes | Topic | Note | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Memory** | All operations use stack memory; no dynamic allocation | -| **MISRA C:2023** | Audited with `misch` (cppcheck-backed MISRA C:2023 analysis; configuration in `misra.toml`); the audit reports zero findings. Deviations are justified at point of use with `cppcheck-suppress ... @deviation` comments, or project-wide in `misra-deviations.txt`. The only required-rule deviations are three Rule 21.15 sites: the type-erased struct-member copies centralised in two internal helpers, and the deliberate F32 `float`/`uint32_t` pun. Design follows MISRA principles throughout: no dynamic allocation, no UB shifts, explicit error codes, `memcpy`-based type punning. | -| **Payload size** | Caller-supplied via `payload_bits` (multiple of 8, between 8 and 512). 64 matches CAN classic; 512 matches full CAN-FD. | -| **Bit ordering** | LSB-first within each byte; multi-byte fields little-endian; fields may span byte boundaries | +| **Memory** | All operations use stack memory. The library does not allocate memory dynamically. +| **MISRA C:2023** | Audited with `misch` (cppcheck-backed MISRA C:2023 analysis; configuration in `misra.toml`). The audit reports zero findings. + +Deviations are justified at point of use with `cppcheck-suppress ... @deviation` comments or project-wide in `misra-deviations.txt`. The only required-rule deviations are three Rule 21.15 sites: the type-erased struct-member copies in two internal helpers and the deliberate F32 `float`/`uint32_t` pun. Design follows MISRA principles throughout: no dynamic allocation, no UB shifts, explicit error codes, `memcpy`-based type punning. | +| **Payload size** | The caller supplies the payload size via `payload_bits` (multiple of 8, between 8 and 512). A value of 64 matches CAN classic. A value of 512 matches full CAN-FD. +| **Bit ordering** | Bit 0 is the least significant bit within each byte. Multi-byte fields use little-endian order. Fields may span byte boundaries. | **Field size** | 1-32 bits per field | -| **Thread safety** | Not thread-safe; caller must provide mutual exclusion when `base_ptr` or `payload` is shared across threads or ISRs | -| **WCET** | Execution time is bounded and deterministic **when field descriptors are `static const`** (loop bounds are compile-time constants). WCET is not guaranteed if descriptors are constructed at runtime with arbitrary `bit_length` values. | -| **F32 and scaling** | `PPACK_TYPE_F32` always performs a raw 32-bit IEEE 754 bit-copy; `scale`, `offset`, and `behaviour` are ignored for this type. Use a scaled integer type (`UINT16`, `INT16`, `UINT32`, `INT32`) to encode floating-point physical values with a resolution factor. | -| **UINT8 struct member** | `PPACK_TYPE_UINT8` reads and writes a `uint8_t`. On 16-bit MAU platforms, where a `uint8_t` member is backed by 16-bit storage, only the low 8 bits round-trip. | -| **Version header** | `ppack_version.h` is auto-generated by the Meson build and placed in the output build folder | +| **Thread safety** | ppack is not thread-safe. The caller provides mutual exclusion when `base_ptr` or `payload` is shared across threads or ISRs. +| **WCET** | Execution time is bounded and deterministic **when field descriptors are `static const`**. The loop bounds are compile-time constants in that case. WCET is not guaranteed if the caller constructs descriptors at runtime with arbitrary `bit_length` values. +| **F32 and scaling** | `PPACK_TYPE_F32` always copies 32 IEEE-754 bits directly. The library ignores `scale`, `offset`, and `behaviour` for this type. Use a scaled integer type (`UINT16`, `INT16`, `UINT32`, `INT32`) to encode floating-point physical values with a resolution factor. +| **UINT8 struct member** | `PPACK_TYPE_UINT8` reads and writes a `uint8_t`. On 16-bit MAU platforms the member uses 16-bit storage. Only the low 8 bits round-trip through the payload. +| **Version header** | The Meson build generates `ppack_version.h` and places it in the build directory. diff --git a/include/ppack.h b/include/ppack.h index d9faedc..73b7c48 100644 --- a/include/ppack.h +++ b/include/ppack.h @@ -70,29 +70,29 @@ extern "C" { * ## Wire format * * The payload is treated as N bits numbered 0..N-1, where N is the - * @c payload_bits argument. Bit @c K maps to bit @c (K mod 8) of - * logical byte @c (K / 8), where logical byte 0 is the first byte - * on the wire. - * - * Within each logical byte, bit 0 is the least significant bit. - * Multi-byte fields are little-endian (Intel ordering, equivalent - * to DBC @c byte_order=1). A field at @c start_bit=0, @c bit_length=16 - * with value @c 0x1234 produces @c 0x34 in byte 0 and @c 0x12 in byte 1. - * - * @c PPACK_TYPE_F32 is a raw 32-bit IEEE-754 bit-copy. The wire - * representation is host-endian @c uint32_t. This is interoperable - * between any two little-endian IEEE-754 hosts (e.g. x86_64, ARM Cortex-M, - * AArch64, 16-bit MAU platforms). It is NOT safe between a - * little-endian and a big-endian host without explicit byte-swapping - * in user code. - * - * The payload buffer model is portable across MAU sizes: declare it - * as @c ppack_byte_t @c payload[PPACK_PAYLOAD_UNITS]. The - * @c PPACK_PAYLOAD_UNITS macro defaults to a 64-bit payload (8 bytes - * or 4 16-bit words); override @c PPACK_PAYLOAD_BITS at the - * toolchain level for non-default sizes (e.g. - * @c -DPPACK_PAYLOAD_BITS=512). The runtime API takes the size - * explicitly and is independent of this macro. + * @c payload_bits argument. + * Bit @c K is in logical byte @c (K / 8) at position @c (K mod 8). + * Logical byte 0 is the first byte on the wire. + * + * Bit 0 is the least significant bit within each logical byte. + * Multi-byte fields use little-endian order. This matches DBC + * @c byte_order=1. A 16-bit field at @c start_bit=0 with value + * @c 0x1234 writes @c 0x34 to byte 0 and @c 0x12 to byte 1. + * + * @c PPACK_TYPE_F32 copies 32 IEEE-754 bits directly. + * The wire bytes follow the host @c uint32_t byte order. + * Any two little-endian hosts interoperate (for example, + * x86_64, ARM Cortex-M, AArch64, 16-bit MAU platforms). + * Little-endian and big-endian hosts do not interoperate without + * explicit byte swapping in user code. + * + * Declare the payload buffer as @c ppack_byte_t payload[PPACK_PAYLOAD_UNITS]. + * This model works on all MAU sizes. + * The @c PPACK_PAYLOAD_UNITS macro declares a 64-bit payload by default + * (8 bytes or four 16-bit words). + * Override @c PPACK_PAYLOAD_BITS at the toolchain level for other sizes + * (for example, @c -DPPACK_PAYLOAD_BITS=512). + * The runtime API takes the size as an explicit argument. * * ## Scaled-field semantics * @@ -102,44 +102,40 @@ extern "C" { * unpack: physical = (float)raw * scale + offset * @endcode * - * @b Saturation: pack silently clamps the raw integer to the - * destination type's representable range (e.g. 0..65535 for - * @c PPACK_TYPE_UINT16). For safety-critical applications where an - * out-of-range physical value MUST be detected, validate the - * input before calling @c ppack_pack. - * - * @b Quantization: the float-to-integer cast truncates toward - * zero (C standard cast semantics, not round-to-nearest). The - * maximum round-trip error is one LSB (one unit of @c scale). - * For round-to-nearest behaviour, pre-add - * @c 0.5f*scale*sign(physical) at the call site before pack. - * - * @b Float-range clamp: for @c PPACK_TYPE_UINT32 / @c PPACK_TYPE_INT32 - * scaled fields the upper/lower clamp is the largest float that - * is exactly representable AND fits in the destination integer. - * @c UINT32_MAX (4294967295) and @c INT32_MAX (2147483647) round - * UP to @c 2^32 / @c 2^31 as floats, which would overflow the - * destination cast. The library clamps to @c 4294967040 and - * @c 2147483520 respectively (the next representable float - * below the type's true maximum). - * - * @b Non-finite values: pack rejects a SCALED field whose scaled - * result is NaN (a NaN source value, or a NaN produced by the - * scale/offset arithmetic) with @c -PPACK_ERR_INVALARG; NaN has no - * defined integer representation. Positive/negative infinity is - * treated like any other out-of-range value and saturates to the - * destination type's clamp bounds. @c PPACK_TYPE_F32 fields are a - * raw bit-copy and carry NaN/infinity payloads unchanged. + * @b Saturation: ppack_pack clamps the raw integer to the + * destination type's range (for example, 0..65535 for + * @c PPACK_TYPE_UINT16). Validate the input at the call site + * if your application must detect out-of-range physical values. + * + * @b Quantization: ppack_pack truncates the float-to-integer cast + * toward zero (standard C cast rules). The maximum round-trip error + * is one LSB, equal to @c scale. + * Add @c 0.5f*scale*sign(physical) at the call site for + * round-to-nearest behaviour. + * + * @b Float-range clamp: for @c PPACK_TYPE_UINT32 scaled fields, + * ppack_pack clamps to @c 4294967040. This is the largest float + * value that fits in a @c uint32_t. + * For @c PPACK_TYPE_INT32 it clamps to @c 2147483520. + * The values @c UINT32_MAX and @c INT32_MAX round up to + * @c 2^32 or @c 2^31 as 32-bit floats. That overflows the cast. + * + * @b Non-finite values: ppack_pack rejects a SCALED field when + * the result is NaN. The function returns @c -PPACK_ERR_INVALARG. + * NaN can come from the source value or the scale/offset calculation. + * NaN has no valid integer representation. + * Positive and negative infinity saturate to the type's clamp bounds. + * @c PPACK_TYPE_F32 fields copy bits directly. + * They carry NaN and infinity values unchanged. * * ## 16-bit MAU Platform Notes * - * On platforms with a 16-bit minimum addressable unit (MAU) - * (16-bit MAU platforms), @c CHAR_BIT is 16 and any @c uint8_t the - * toolchain provides is backed by 16-bit storage. ppack auto-detects - * this (via @c CHAR_BIT / @c UCHAR_MAX, not @c uint8_t) and selects a 16-bit - * storage unit internally, but maintains a logical 8-bit layout to - * ensure interoperability with other primitives. Two contract points - * specific to this platform: + * On 16-bit MAU platforms, @c CHAR_BIT is 16. + * Any @c uint8_t the toolchain provides uses 16-bit storage. + * ppack detects this from @c CHAR_BIT and @c UCHAR_MAX. + * The library selects a 16-bit storage unit internally. + * It keeps an 8-bit logical layout to match other primitives. + * Two contract points apply on this platform: * * @li A @c PPACK_TYPE_UINT8 field carries only the low 8 bits of its * struct member through the wire. On pack, the upper 8 bits of @@ -216,16 +212,16 @@ enum ppack_behaviour { /** * @brief Describes a field within a payload. * - * @note Set @c bit_length to match the natural width of the @c type - * for predictable behaviour. Values larger than the type's - * natural width are accepted (the validation only enforces - * @c bit_length <= 32 and @c start_bit + bit_length <= payload_bits) - * but only the low bits of the source are meaningful, so the - * upper wire bits will be zero or sign-extended. + * @note Set @c bit_length to match the natural width of @c type. + * The library accepts larger values (it enforces + * @c bit_length <= 32 and + * @c start_bit + bit_length <= payload_bits). + * Only the low bits of the source carry data. + * The upper wire bits are zero or sign-extended. * - * @note @c PPACK_TYPE_F32 always uses raw bit-copy semantics; @c behaviour - * and @c scale / @c offset are ignored. This assumes matching - * IEEE-754 layout and endianness across nodes. + * @note @c PPACK_TYPE_F32 always copies bits directly. + * The library ignores @c behaviour, @c scale, and @c offset for this type. + * This requires matching IEEE-754 layout and endianness on all nodes. * * @note For @c PPACK_BEHAVIOUR_SCALED the struct member must be @c float. * For @c PPACK_BEHAVIOUR_RAW the struct member must match the @@ -253,10 +249,10 @@ struct ppack_field { /** * @brief Pack a payload from given fields into a buffer. * - * Writes a payload of @c payload_bits bits to @c payload by reading - * each field's source value from the @c base_ptr structure, applying - * any scaling, and placing the bits at the field's @c start_bit. Bits - * outside the union of the field ranges are cleared to zero. + * ppack_pack reads each field from the @c base_ptr structure, + * applies any scaling, and writes the bits to @c payload. + * It places each value at the field's @c start_bit position. + * Bits outside all field ranges are set to zero. * * @param[in] base_ptr Pointer to source structure * @param[out] payload Destination buffer of exactly @c payload_bits @@ -273,28 +269,31 @@ struct ppack_field { * * @return PPACK_SUCCESS on success * @return -PPACK_ERR_NULLPTR if @c base_ptr or @c payload is NULL - * @return -PPACK_ERR_INVALARG if @c field_count is 0, @c fields is NULL, - * @c payload_bits is 0, not a multiple of - * @c PPACK_ADDR_UNIT_BITS, or > 512; - * @c bit_length is 0 or > 32; scaling is - * requested for @c PPACK_TYPE_UINT8; or a - * SCALED field's scaled result is NaN - * @return -PPACK_ERR_OVERFLOW if @c start_bit + bit_length exceeds + * @return -PPACK_ERR_INVALARG on invalid arguments. This includes: + * @c field_count is 0, @c fields is NULL, + * @c payload_bits is 0, @c payload_bits is not + * a multiple of @c PPACK_ADDR_UNIT_BITS, + * @c payload_bits exceeds 512, @c bit_length is 0 + * or greater than 32, scaling is set for + * @c PPACK_TYPE_UINT8, or a SCALED field + * produces a NaN result. + * @return -PPACK_ERR_OVERFLOW when @c start_bit plus bit_length exceeds * @c payload_bits, or @c scale is 0.0 on a - * SCALED field + * SCALED field. * @return -PPACK_ERR_NOTFOUND if an unknown field type is encountered * * @note Not thread-safe. Callers sharing @c base_ptr or @c payload * across threads or ISRs must provide their own mutual exclusion. * - * @note Out-of-range scaled values clamp silently to the destination - * type's representable range; NaN is rejected. See "Scaled-field - * semantics" in the file-level docs. + * @note Out-of-range scaled values clamp to the destination type's + * range. The function rejects NaN with @c -PPACK_ERR_INVALARG. + * See the "Scaled-field semantics" section above. * - * @note Not atomic on failure: the payload buffer is zeroed before the - * field descriptors are validated, so on an error return its - * contents are unspecified (zeroed and possibly partially - * written). Do not transmit a payload after a non-zero return. + * @note The function does not roll back on failure. + * ppack_pack clears the payload buffer before it validates the + * field descriptors. On an error return the buffer contains zeroed + * data and possibly partial writes. + * Do not transmit a payload after a non-zero return. */ int ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, const struct ppack_field *fields, size_t field_count); @@ -302,10 +301,9 @@ int ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, /** * @brief Unpack a payload from a buffer into specified field locations. * - * Reads a payload of @c payload_bits bits from @c payload and writes - * each field's decoded value to the corresponding offset within the - * @c base_ptr structure. Existing bytes of struct members not covered - * by any field are left untouched. + * ppack_unpack reads @c payload_bits bits from @c payload. + * It writes each decoded value to the matching offset in @c base_ptr. + * Bytes inside struct members that have no field mapping keep their current values. * * @param[out] base_ptr Pointer to destination structure * @param[in] payload Source buffer of exactly @c payload_bits @@ -322,11 +320,13 @@ int ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, * * @return PPACK_SUCCESS on success * @return -PPACK_ERR_NULLPTR if @c base_ptr or @c payload is NULL - * @return -PPACK_ERR_INVALARG if @c field_count is 0, @c fields is NULL, - * @c payload_bits is 0, not a multiple of - * @c PPACK_ADDR_UNIT_BITS, or > 512; - * @c bit_length is 0 or > 32; or scaling is - * requested for @c PPACK_TYPE_UINT8 + * @return -PPACK_ERR_INVALARG on invalid arguments. This includes: + * @c field_count is 0, @c fields is NULL, + * @c payload_bits is 0, @c payload_bits is not + * a multiple of @c PPACK_ADDR_UNIT_BITS, + * @c payload_bits exceeds 512, @c bit_length is 0 + * or greater than 32, or scaling is set for + * @c PPACK_TYPE_UINT8. * @return -PPACK_ERR_OVERFLOW if @c start_bit + bit_length exceeds * @c payload_bits * @return -PPACK_ERR_NOTFOUND if an unknown field type is encountered @@ -334,11 +334,11 @@ int ppack_pack(const void *base_ptr, void *payload, size_t payload_bits, * @note Not thread-safe. Callers sharing @c base_ptr or @c payload * across threads or ISRs must provide their own mutual exclusion. * - * @note Not atomic on failure: fields are decoded in descriptor order, - * so on an error return the struct members of every field before - * the offending descriptor have already been overwritten. Treat - * the destination structure as unspecified after a non-zero - * return. + * @note The function does not roll back on failure. + * ppack_unpack decodes fields in descriptor order. + * On an error return it has already written all fields before + * the failing descriptor. + * Do not use the destination structure after a non-zero return. */ int ppack_unpack(void *base_ptr, const void *payload, size_t payload_bits, const struct ppack_field *fields, size_t field_count); diff --git a/include/ppack_platform.h b/include/ppack_platform.h index 8be0aed..c551fc4 100644 --- a/include/ppack_platform.h +++ b/include/ppack_platform.h @@ -4,25 +4,26 @@ * @file: ppack_platform.h * * @brief - * Platform abstraction for ppack. Detects whether the target's - * minimum addressable unit (MAU) is 8 or 16 bits and exposes the - * type aliases and compile-time constants the library needs. + * Platform abstraction for ppack. * - * On byte-addressable targets (x86_64, ARM, AArch64, RISC-V, AVR, etc.) + * The library detects the target minimum addressable unit (MAU) + * size (8 or 16 bits). It defines the type aliases and + * compile-time constants the implementation needs. + * + * On byte-addressable targets (x86_64, ARM, AArch64, RISC-V, AVR) * @c ppack_byte_t is @c uint8_t. * - * On word-addressable targets where @c CHAR_BIT is 16 (e.g. 16-bit MAU - * platforms), @c ppack_byte_t is @c uint16_t. Regardless of MAU size, - * ppack treats the payload as a sequence of 8-bit logical units to - * ensure interoperability with other primitives (like @c ucrc). + * On targets where @c CHAR_BIT is 16, @c ppack_byte_t is @c uint16_t. + * ppack uses 8-bit logical units for the payload on all targets. + * This matches other primitives in this project, such as @c ucrc. * - * @c PPACK_PAYLOAD_BITS is a user-overridable convenience macro that - * sizes the @c PPACK_PAYLOAD_UNITS buffer-sizing macro (defined in - * @c ppack.h, the library's public entry point). Define it before - * including the header (e.g. @c -DPPACK_PAYLOAD_BITS=128 or - * @c -DPPACK_PAYLOAD_BITS=512) to change the default. The runtime - * @c ppack_pack / @c ppack_unpack API takes the payload size as an - * explicit argument and does not depend on this macro. + * @c PPACK_PAYLOAD_BITS sets the default payload size for the + * @c PPACK_PAYLOAD_UNITS buffer-sizing macro. + * The @c ppack.h header defines @c PPACK_PAYLOAD_UNITS. + * Override @c PPACK_PAYLOAD_BITS before you include this header + * (for example, @c -DPPACK_PAYLOAD_BITS=128 or + * @c -DPPACK_PAYLOAD_BITS=512). + * The runtime API takes the payload size as an explicit argument. * * The library's wire format is identical across both addressing * models: a sequence of N bits (where N is the @c payload_bits @@ -32,10 +33,9 @@ * full contract. * * Define @c PPACK_SIMULATE_16BIT_MAU at compile time on a byte- - * addressable host to exercise the word-addressable code path - * against host unit tests. This is for library development and - * test infrastructure; production builds should leave it undefined - * and rely on auto-detection. + * addressable host to exercise the 16-bit MAU code path. + * Use this flag for library development and host unit tests only. + * Production builds must leave it undefined. */ #ifndef PPACK_PLATFORM_H_ @@ -65,35 +65,33 @@ typedef uint8_t ppack_byte_t; #endif /** - * @brief Storage type that a user's `uint8_t` struct member resolves - * to on the current target. + * @brief Storage type for a `uint8_t` struct member on this target. * - * On byte-addressable hosts this is @c uint8_t. On a 16-bit MAU target the - * narrowest integer type is 16 bits, so any @c uint8_t the toolchain provides - * is necessarily backed by 16-bit storage; this typedef mirrors that wider - * storage. (@c uint8_t is an optional C type and such an alias is technically - * non-conforming, but it is the de-facto behaviour of these toolchains.) + * On byte-addressable hosts this is @c uint8_t. + * On a 16-bit MAU target the narrowest integer type is 16 bits. + * Any @c uint8_t the toolchain provides uses 16-bit storage. + * This typedef mirrors that wider storage. + * The C standard marks @c uint8_t as optional when it maps to 16-bit + * storage, but these toolchains provide it anyway. * - * @note This is a library-internal alias used by the implementation - * and the unit tests. Application code on real targets should - * continue to declare struct members as @c uint8_t for - * @c PPACK_TYPE_UINT8 fields. @c ppack_u8_t exists so that host - * builds with @c PPACK_SIMULATE_16BIT_MAU faithfully reproduce - * the 16-bit MAU storage layout. + * @note The library implementation and unit tests use this alias. + * Application code must declare struct members as @c uint8_t + * for @c PPACK_TYPE_UINT8 fields on real targets. + * Host builds that define @c PPACK_SIMULATE_16BIT_MAU use + * @c ppack_u8_t to reproduce the 16-bit MAU storage layout. */ typedef ppack_byte_t ppack_u8_t; /** - * @brief Default payload size in bits for the @c PPACK_PAYLOAD_UNITS - * convenience macro (defined in @c ppack.h). + * @brief Default payload size in bits for @c PPACK_PAYLOAD_UNITS + * (defined in @c ppack.h). * - * Override at the toolchain level (e.g. @c -DPPACK_PAYLOAD_BITS=128) - * to size stack buffer declarations to a non-default payload. Must - * be a positive multiple of @c PPACK_ADDR_UNIT_BITS and no greater - * than 512. + * Override at the toolchain level (for example, @c -DPPACK_PAYLOAD_BITS=128) + * to declare stack buffers of a different size. + * The value must be a positive multiple of @c PPACK_ADDR_UNIT_BITS + * and no greater than 512. * - * The runtime @c ppack_pack / @c ppack_unpack API takes the payload - * size as an explicit argument and is independent of this macro. + * The runtime API takes the payload size as an explicit argument. */ #ifndef PPACK_PAYLOAD_BITS #define PPACK_PAYLOAD_BITS 64u