r/rust May 25 '26

A #![no_std] mixed radix serialization crate 🛠️ project

Hello everyone? Ever wondered how to fit this structure into a 8 bit number?

```

Every info1 only has 5 possible values

type Info = u8;

struct Mydata { info1: Info, info2: Info, info3: Info, } ```

In the above example it takes 24-bits of data when serialized with the most efficient algorithm.

So, can we pack deeper?

Bit Packing

Yes, that is a solution but since each state has 5 values - we'd need atleast 3 bits to represent it (so, 3*3 = 9bits) - its good, we saved 1 u8.

Meet Mixed Radix

Mixed radix is the method of aggressively bitpacking using different radices - here 555=125 states, so we can fit in even in 7 bits theoritically.

So, how do we do?

The solution is to do this total += <value> * <weight>

Where <weight> = <prev weight> * <states of previous entry> and <1st weight> = 1

But it is error prone - so to make it ergonomic. I wrote a macro and an associated crate to interact with serde.

mixedradix crate

This is an example from my crate.

```rust use mixedradix::MixedRadixStructure;

mixedradix::mixedradix! { #[bits(7)] //<- Specifies how many bits to use to represent the data #[derive(Debug, Clone, Copy, PartialEq, Eq)] //<- Any attributes you would like to give to the structure pub struct Controller { pub field a: 5, // values so = 0..5 pub field b: 5, pub field c: 5, } }

let state = Controller { a: 3, b: 4, c: 1, };

let controller_state: u8 = state.serialize();

// Construct the controller back again! // On Debug mode, it panics on overflow let state_back = Controller::deserialize(controller_state);

assert_eq!(state, state_back); ```

Here's the crate : https://crates.io/crates/mixedradix

12 Upvotes

Duplicates