struct_to_array
Convert between homogeneous structs (all fields the same type) and fixed-size arrays.
Usage
use StructToArray;
let point = Point3D ;
// Convert to array
let arr = point.to_arr;
assert_eq!;
// Convert back from array
let point = from_arr;
assert_eq!;
Features
- Named field structs:
struct Point { x: T, y: T } - Tuple structs:
struct Pair(T, T) - Generic types: Works with any uniform field type
- No
Copyrequired: Value-based conversions work with move-only types - Vec conversion: Optional
StructToVectrait forVecconversions
Requirements
All fields must have identical type tokens. The macro checks this at compile time.
Installation
Add to your Cargo.toml:
[]
= { = "struct_to_array" }
More Examples
Tuple Structs
use StructToArray;
;
let pair = Pair;
let arr = pair.to_arr;
assert_eq!;
let reconstructed = from_arr;
assert_eq!;
assert_eq!;
Generic Types
use StructToArray;
let string_pair = GenericPair ;
let arr = string_pair.to_arr;
assert_eq!;
assert_eq!;
Vec Conversion
use ;
let point = Point2D ;
// Convert to Vec
let vec = point.to_vec;
assert_eq!;
// Convert from Vec
let point2 = from_vec;
assert_eq!;
assert_eq!;
Non-Copy Types
The trait works with move-only types that don't implement Copy:
use StructToArray;
let pair = VecPair ;
let arr = pair.to_arr;
assert_eq!;
assert_eq!;
let reconstructed = from_arr;
assert_eq!;
License
MIT OR Apache-2.0
LLM Notice
This was written to my spec, but entirely by LLM. It could contain errors, but my spec included a mandate for quite a lot of property-based testing. I've only looked through this quickly, but the proptests look good and cover a huge variety of cases, way more than I would have ever had the patience to write myself.
This is good enough for me, perhaps for you too :-)
But if you find any mistakes, please open an issue or PR!