OSAL-RS-Serde Derive Macros
Procedural macros for automatic implementation of serialization traits in osal-rs-serde.
Overview
This crate provides #[derive(Serialize, Deserialize)] macros that automatically implement the Serialize and Deserialize traits for your custom types. These macros are the recommended way to use osal-rs-serde.
Usage
Add the derive feature to enable these macros:
[]
= { = "0.3", = ["derive"] }
Then use the macros on your structs:
use ;
Supported Struct Types
Named Fields (Most Common)
Tuple Structs
;
Unit Structs
;
Supported Field Types
The derive macros work with any type that implements Serialize/Deserialize:
Primitives
Arrays
Tuples
Option Types
Nested Structs
Collections (with alloc feature)
Complex Examples
Embedded System Telemetry
use ;
Robot Control
use ;
Configuration with Optional Fields
use ;
Serialization Order
Fields are serialized in the order they are declared in the struct:
This produces the binary layout: [first, second_lo, second_hi, third_0, third_1, third_2, third_3]
Limitations
Enums
Currently, enums are not supported by the derive macro:
// ❌ NOT SUPPORTED YET
For enums, implement the traits manually or use an integer representation:
// ✅ WORKAROUND
Unions
Unions are not supported:
// ❌ NOT SUPPORTED
union Data
Generic Types
Generic types are not yet supported in the current version:
// ❌ NOT SUPPORTED YET
Generated Code
The derive macros generate implementations similar to:
// For this struct:
// The macro generates approximately:
Debugging
To see the generated code, use cargo expand:
Error Messages
Common errors and solutions:
"the trait bound T: Serialize is not satisfied"
Solution: Ensure all field types implement Serialize:
"expected named fields"
Solution: Make sure you're using a supported struct type (named fields, tuple, or unit).
Performance
The derive macros generate efficient code with:
- No runtime overhead compared to manual implementation
- Inlining opportunities for the compiler
- Zero-cost abstractions
- No allocations (except for Vec/String with
allocfeature)
Best Practices
- Always use derive when possible - It's less error-prone than manual implementation
- Keep structs simple - Avoid deeply nested structures when possible
- Consider field order - Put frequently accessed fields first
- Document binary format - Add comments about the serialized format
- Use Option for optional data - Don't use magic values
Examples
See the parent crate's examples/ directory for complete working examples:
with_derive.rs- Basic usagearrays_tuples.rs- Arrays and tuplesnested_structs.rs- Nested structuresoptional_fields.rs- Optional fieldsrobot_control.rs- Complex embedded example
License
LGPL-2.1-or-later - See LICENSE for details.
Author
Antonio Salsi - passy.linux@zresa.it
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.