• Stars
    star
    336
  • Rank 125,564 (Top 3 %)
  • Language
    Rust
  • License
    Other
  • Created over 2 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Müsli is a flexible and generic binary serialization framework

musli

github crates.io docs.rs build status

Excellent performance, no compromises1!

Müsli is a flexible, fast, and generic binary serialization framework for Rust, in the same vein as serde.

It provides a set of formats, each with its own well-documented set of features and tradeoffs. Every byte-oriented serialization method (including musli-json) has full #[no_std] support with or without alloc.


Quick guide


Usage

Add the following to your Cargo.toml using the format you want to use:

musli = "0.0.49"
musli-wire = "0.0.49"

Design

The heavy lifting in user code is done through the Encode and Decode derives which are thoroughly documented in the derives module. Müsli primarily operates based on the schema types which implement these traits imply, but self-descriptive formats are also possible (see Formats below).

use musli::{Encode, Decode};

#[derive(Encode, Decode)]
struct Person {
    /* .. fields .. */
}

Note by default a field is identified by its numerical index which would change if they are re-ordered. Renaming fields and setting a default naming policy can be done by configuring the derives.

The binary serialization formats provided aim to efficiently and accurately encode every type and data structure available in Rust. Each format comes with well-documented tradeoffs and aim to be fully memory safe to use.

Internally we use the terms "encoding", "encode", and "decode" because it's distinct from serde's use of "serialization", "serialize", and "deserialize" allowing for the ease of using both libraries side by side if desired.

Müsli is designed on similar principles as serde. Relying on Rust's powerful trait system to generate code which can largely be optimized away. The end result should be very similar to handwritten highly optimized code.

As an example of this, these two functions both produce the same assembly on my machine (built with --release):

const ENCODING: Encoding<DefaultMode, Fixed<NativeEndian>, Variable> =
    Encoding::new().with_fixed_integers_endian();

#[derive(Encode, Decode)]
#[musli(packed)]
pub struct Storage {
    left: u32,
    right: u32,
}

fn with_musli(storage: &Storage) -> Result<[u8; 8]> {
    let mut array = [0; 8];
    ENCODING.encode(&mut array[..], storage)?;
    Ok(array)
}

fn without_musli(storage: &Storage) -> Result<[u8; 8]> {
    let mut array = [0; 8];
    array[..4].copy_from_slice(&storage.left.to_ne_bytes());
    array[4..].copy_from_slice(&storage.right.to_ne_bytes());
    Ok(array)
}

Where Müsli differs in design philosophy is twofold:

We make use of GATs to provide tighter abstractions, which should be easier for Rust to optimize.

We make less use of the Visitor pattern in certain instances where it's deemed unnecessary, such as when decoding collections. The result is usually cleaner decode implementations, as shown here:

use musli::Context;
use musli::de::{Decode, Decoder, SequenceDecoder};
use musli::mode::Mode;

struct MyType {
    data: Vec<String>,
}

impl<'de, M> Decode<'de, M> for MyType where M: Mode {
    fn decode<'buf, C, D>(cx: &mut C, decoder: D) -> Result<Self, C::Error>
    where
        C: Context<'buf, Input = D::Error>,
        D: Decoder<'de>,
    {
        let mut seq = decoder.decode_sequence(cx)?;
        let mut data = Vec::with_capacity(seq.size_hint().or_default());

        while let Some(decoder) = seq.next(cx)? {
            data.push(Decode::<M>::decode(cx, decoder)?);
        }

        seq.end(cx)?;

        Ok(Self {
            data
        })
    }
}

Another major aspect where Müsli differs is in the concept of modes (note the M parameter above). Since this is a parameter of the Encode and Decode traits it allows for the same data model to be serialized in many different ways. This is a larger topic and is covered further down.


Formats

Formats are currently distinguished by supporting various degrees of upgrade stability. A fully upgrade stable encoding format must tolerate that one model can add fields that an older version of the model should be capable of ignoring.

Partial upgrade stability can still be useful as is the case of the musli-storage format below, because reading from storage only requires decoding to be upgrade stable. So if correctly managed with #[musli(default)] this will never result in any readers seeing unknown fields.

The available formats and their capabilities are:

reorder missing unknown self
musli-storage #[musli(packed)]
musli-storage
musli-wire
musli-descriptive
musli-json2

reorder determines whether fields must occur in exactly the order in which they are specified in their type. Reordering fields in such a type would cause unknown but safe behavior of some kind. This is only suitable for byte-oriented IPC where the data models of each client are are strictly synchronized.

missing determines if reading can handle missing fields through something like Option<T>. This is suitable for on-disk storage, because it means that new optional fields can be added as the schema evolves.

unknown determines if the format can skip over unknown fields. This is suitable for network communication. At this point you've reached upgrade stability. Some level of introspection is possible here, because the serialized format must contain enough information about fields to know what to skip which usually allows for reasoning about basic types.

self determines if the format is self-descriptive. Allowing the structure of the data to be fully reconstructed from its serialized state. These formats do not require models to decode, and can be converted to and from dynamic containers such as musli-value for introspection.

For every feature you drop, the format becomes more compact and efficient. musli-storage using #[musli(packed)] for example is roughly as compact as bincode while musli-wire is comparable in size to something like protobuf. All formats are primarily byte-oriented, but some might perform bit packing if the benefits are obvious.


Upgrade stability

The following is an example of full upgrade stability using musli-wire. Note how Version1 can be decoded from an instance of Version2 because it understands how to skip fields which are part of Version2. We're also explicitly #[musli(rename = ..)] the fields to ensure that they don't change in case they are re-ordered.

use musli::{Encode, Decode};

#[derive(Debug, PartialEq, Encode, Decode)]
struct Version1 {
    #[musli(rename = 0)]
    name: String,
}

#[derive(Debug, PartialEq, Encode, Decode)]
struct Version2 {
    #[musli(rename = 0)]
    name: String,
    #[musli(default, rename = 1)]
    age: Option<u32>,
}

let version2 = musli_wire::to_vec(&Version2 {
    name: String::from("Aristotle"),
    age: Some(62),
})?;

let version1: Version1 = musli_wire::decode(version2.as_slice())?;

The following is an example of partial upgrade stability using musli-storage on the same data models. Note how Version2 can be decoded from Version1 but not the other way around. That's why it's suitable for on-disk storage the schema can evolve from older to newer versions.

let version2 = musli_storage::to_vec(&Version2 {
    name: String::from("Aristotle"),
    age: Some(62),
})?;

assert!(musli_storage::decode::<_, Version1>(version2.as_slice()).is_err());

let version1 = musli_storage::to_vec(&Version1 {
    name: String::from("Aristotle"),
})?;

let version2: Version2 = musli_storage::decode(version1.as_slice())?;

Modes

In Müsli the same model can be serialized in different ways. Instead of requiring the use of distinct models we support implementing different modes for a single model.

A mode allows for different encoding attributes to apply depending on which mode an encoder is configured to use. A mode can apply to any musli parameter giving you a lot of flexibility.

If a mode is not specified, an implementation will apply to all modes (M: Mode), if at least one mode is specified it will be implemented for all modes which are present in a model and DefaultMode. This way, an encoding which uses DefaultMode (which it does by default) should always work.

For more information on how to configure modes, see the derives module. Below is a simple example of how we can use two modes to provide two different kinds of serialization to a single struct.

use musli::mode::{DefaultMode, Mode};
use musli::{Decode, Encode};
use musli_json::Encoding;

enum Alt {}
impl Mode for Alt {}

#[derive(Decode, Encode)]
#[musli(mode = Alt, packed)]
#[musli(default_field_name = "name")]
struct Word<'a> {
    text: &'a str,
    teineigo: bool,
}

let CONFIG: Encoding<DefaultMode> = Encoding::new();
let ALT_CONFIG: Encoding<Alt> = Encoding::new().with_mode();

let word = Word {
    text: "あります",
    teineigo: true,
};

let out = CONFIG.to_string(&word)?;
assert_eq!(out, r#"{"text":"あります","teineigo":true}"#);

let out = ALT_CONFIG.to_string(&word)?;
assert_eq!(out, r#"["あります",true]"#);

Unsafety

This is a non-exhaustive list of unsafe use in this crate, and why they are used:

  • A mem::transcode in Tag::kind. Which guarantees that converting into the Kind enum which is #[repr(u8)] is as efficient as possible.

  • A largely unsafe SliceReader which provides more efficient reading than the default Reader impl for &[u8] does. Since it can perform most of the necessary comparisons directly on the pointers.

  • Some unsafety related to UTF-8 handling in musli_json, because we check UTF-8 validity internally ourselves (like serde_json).

  • FixedBytes<N> is a stack-based container that can operate over uninitialized data. Its implementation is largely unsafe. With it stack-based serialization can be performed which is useful in no-std environments.

  • Some unsafe is used for owned String decoding in all binary formats to support faster string processing using simdutf8. Disabling the simdutf8 feature (enabled by default) removes the use of this unsafe.

To ensure this library is correctly implemented with regards to memory safety, extensive testing is performed using miri. For more information on this, see musli-tests for more information on this.


Performance

The following are the results of preliminary benchmarking and should be taken with a big grain of 🧂.

The two benchmark suites portrayed are:

  • rt-prim - which is a small object containing one of each primitive type and a string and a byte array.
  • rt-lg - which is roundtrip encoding of a large object, containing vectors and maps of other objects.

Roundtrip of a large object

Roundtrip of a small object


Size comparisons

This is not yet an area which has received much focus, but because people are bound to ask the following section performs a raw size comparison between different formats.

Each test suite serializes a collection of values, which have all been randomly populated.

  • A struct containing one of every primitive value (prim).
  • A really big struct (lg).
  • A structure containing fairly sizable, allocated fields (allocated).
  • A moderately sized enum with many field variations (medium_enum).

Note so far these are all synthetic examples. Real world data is rarely this random. But hopefully it should give an idea of the extreme ranges.

framework prim lg allocated medium_enum
derive_bitcode3 54.94 ± 0.25 9442.00 ± 2786.37 552.50 ± 312.94 104.28 ± 223.41
musli_descriptive 95.06 ± 1.31 12995.40 ± 3802.46 636.98 ± 317.05 111.17 ± 222.81
musli_json4 180.78 ± 2.29 19913.10 ± 6081.87 703.58 ± 322.02 133.13 ± 225.23
musli_storage 61.74 ± 0.44 10433.10 ± 3070.87 547.48 ± 312.98 101.10 ± 222.83
musli_storage_packed 48.74 ± 0.44 9604.90 ± 2811.17 544.48 ± 312.98 99.26 ± 223.07
musli_wire 81.50 ± 1.40 12041.30 ± 3470.11 592.87 ± 314.66 107.70 ± 222.80
rkyv4 56.00 ± 0.00 13239.20 ± 3425.15 562.04 ± 312.82 158.03 ± 226.79
serde_bincode 54.94 ± 0.25 9821.70 ± 2853.71 564.66 ± 312.73 108.52 ± 225.24
serde_bitcode3 54.94 ± 0.25 9449.50 ± 2786.20 552.50 ± 312.94 104.27 ± 223.40
serde_cbor3 174.08 ± 0.79 18810.50 ± 5987.69 612.80 ± 315.17 136.06 ± 224.74
serde_dlhn3 55.05 ± 0.92 10078.10 ± 2926.49 544.48 ± 312.98 99.53 ± 223.13
serde_json4 266.78 ± 2.29 26306.80 ± 8600.79 712.58 ± 322.02 159.36 ± 232.86
serde_rmp 61.02 ± 1.08 11477.60 ± 3136.97 577.12 ± 314.19 117.70 ± 222.53

Footnotes

  1. As in Müsli should be able to do everything you need and more.

  2. This is strictly not a binary serialization, but it was implemented as a litmus test to ensure that Müsli has the necessary framework features to support it. Luckily, the implementation is also quite good!

  3. Lacks 128-bit support. 2 3 4

  4. These formats do not support a wide range of Rust types. Exact level of support varies. But from a size perspective it makes size comparisons either unfair or simply an esoteric exercise since they can (or cannot) make stricter assumptions as a result. 2 3

More Repositories

1

c10t

A minecraft cartography tool
C++
225
star
2

genco

A whitespace-aware quasiquoter for beautiful code generation.
Rust
176
star
3

OxidizeBot

High performance Twitch bot in Rust
Rust
151
star
4

relative-path

Portable relative UTF-8 paths for Rust.
Rust
92
star
5

leaky-bucket

A token-based rate limiter based on the leaky bucket algorithm.
Rust
88
star
6

unicycle

A futures abstraction that runs a set of futures which may complete in any order.
Rust
88
star
7

audio

A crate for working with audio in Rust
Rust
75
star
8

bittle

Zero-cost bitsets over native Rust types
Rust
72
star
9

borrowme

The missing compound borrowing for Rust.
Rust
56
star
10

checkers

A sanity checker for global allocations in Rust
Rust
48
star
11

syntree

A memory efficient syntax tree for language developers
Rust
44
star
12

fixed-map

A map implementation that relies on fixed-size storage derived by a procedural macro
Rust
42
star
13

kernelstats

Calculate Statistics about the Linux Kernel
Jupyter Notebook
40
star
14

async-injector

Reactive dependency injection for Rust.
Rust
40
star
15

asteroids-amethyst

An asteroids clone written in the Amethyst Game Engine
Rust
26
star
16

winctx

A minimal window context for Rust on Windows.
Rust
20
star
17

ontv

A rich desktop application for tracking tv shows
Rust
19
star
18

ptscan

A pointer scanner for Windows written in Rust
Rust
18
star
19

async-oauth2

A simple async OAuth 2.0 library for Rust
Rust
18
star
20

quickcfg

Apply a base system configuration, quickly!
Rust
16
star
21

fixed-vec-deque

A fixed-size, zero-allocation circular buffer for Rust
Rust
15
star
22

tiny-async-java

A tiny async library for Java
Java
14
star
23

tigertree

A C port of the Tiger Tree hash implementation used at dcplusplus.sf.net
C
12
star
24

anything

Rust
12
star
25

codeviz

Flexible code generator for Rust
Rust
11
star
26

pusher

Simple project for handling application deployment to many servers
Python
11
star
27

aoc2022

My own personal overengineered helpers to solve AoC problems in Rust
Rust
10
star
28

gabriel

Gabriel, the Process Guardian Angel
Haskell
10
star
29

nondestructive

Nondestructive editing of various formats
Rust
9
star
30

futures-cache

Futures-aware cache backed by sled
Rust
9
star
31

serde-hashkey

Space efficient, in-memory serde serialization which supports hashing.
Rust
9
star
32

cr

A simple challenge response tool (or sign-verify) using openssl.
C
8
star
33

cartography

A cartography rewrite for minecraft devinf (map generator)
C++
7
star
34

unc

A lightweight c++ unicode library
C++
7
star
35

bgrep2

An alternative binary grep utility.
C
7
star
36

uniset

A hierarchical growable bitset which supports in-place atomic operations
Rust
6
star
37

unsync

Unsynchronized synchronization primitives for async Rust
Rust
6
star
38

argwerk

Rust
6
star
39

jpv

My personal Japanese dictionary based on JMdict
Rust
6
star
40

hodoku

A simple set of macros to aid testing with try operations
Rust
5
star
41

patterns

Showcasing simple programming patterns in Rust
LLVM
5
star
42

3dge

Game Experiment to learn Vulkan on Rust
Rust
4
star
43

ChaosMod

ChaosMod for GTA V
C#
4
star
44

c10t-swt

Native SWT Java Gui for c10t
Java
4
star
45

elfdb

Help save Christmas with ELFDB - the interactive debugger for ELF code.
Rust
4
star
46

python-adc

A python implementation for the ADC (Advanced Direct Connect) protocol
Python
4
star
47

async-fuse

Extension traits for dealing with optional futures and streams
Rust
4
star
48

gta-v-scripts

Scripts imported for the latest version available on https://www.gta5-mods.com/tools/decompiled-scripts-b757
C
4
star
49

musync

Music Syncronizing Tool
Python
4
star
50

unlock

Instrumented synchronization primitives helping you to unlock performance issues
Rust
4
star
51

tiny-serializer-java

A tiny serialization framework for Java
Java
4
star
52

rust-advent-of-code-2017

Rust solutions to Advent of Code 2017
Rust
3
star
53

svz

Supervizor Written in C which easilly does checks for running pids and is able to respond to logical statements.
C
3
star
54

tessie

An ffmpeg transcoding wrapper
Rust
3
star
55

aiocp

Rust
3
star
56

rust-advent-of-code-2018

Solutions to Advent of Code 2018 in Rust
Rust
3
star
57

selectme

A fast and fair select! macro for async Rust.
Rust
3
star
58

dotfiles

Dot files for personal stuff
Vim Script
3
star
59

trunk-action

Github action to install and run a custom trunk command
TypeScript
2
star
60

firewall

Bash scripts for setting up your firewall
Shell
2
star
61

udoprog-heroic-datasource

Heroic Datasource for Grafana
TypeScript
2
star
62

packeteer

Simple C program to inject frames directly into a Linux interface.
C
2
star
63

dclite

A simple direct connect client based on python-adc
Python
2
star
64

bsa

Offline unit testing for BIND
Python
2
star
65

bits

Meta-package management
Ruby
2
star
66

momd

Modular media daemon in c++11
C++
2
star
67

pytermcaps

Python terminal capabilities OO wrapper
Python
2
star
68

c-whisper

A C implementation of the whisper database format.
C
2
star
69

idalloc

A library for different methods of allocating unique identifiers efficiently.
Rust
2
star
70

tl

A small script to calculate time left for a flow of many unit types to fill a »bucket«
Python
2
star
71

requests-lb

A load-balancing wrapper around requests
Python
2
star
72

metap2p

A P2P Framework for sharing information.
Python
1
star
73

thenetwork

A hacker oriented strategy game
Lua
1
star
74

evedb

Eve online database conversion tool
Python
1
star
75

fosslint

A linting tool for open source projects
Python
1
star
76

upload-app

Python
1
star
77

GTAV-SpeedPractice

Speedrun Practice mod for GTA V
C++
1
star
78

kick

The omnibus project management tool
Rust
1
star
79

metalang

Language neutral message generator
Python
1
star
80

dsh

distributed sharing protocol
Python
1
star
81

udoprog.github.io

https://udoprog.github.io
HTML
1
star
82

exposr

Dirt simple build and deployment system.
Java
1
star
83

blog

Code samples used at my blog
C
1
star
84

battleplan

Eve Intelligence Hub
Python
1
star
85

aoc2019

Solutions to Advent of Code 2019 in Rust
Rust
1
star
86

localbackup

A set of small and easily configurable local backup scripts implemented in bash using rsync
Shell
1
star
87

ratewatch

A buffer program like 'pv' to measure throughput, using it to check user bandwidth on sftp
C
1
star
88

tiny-rs

A tiny restful compiler for Java
Java
1
star
89

gorilla

Gorilla Time Series Compression
Rust
1
star
90

forkexec

A development tool to tame wild processes
Python
1
star
91

aoc2020

Solutions to Advent of Code 2020 in the Rune programming language
Rust
1
star
92

hashparity

Bash script which recursively checks directory for integrity
1
star
93

rubycss

A small and pure ruby css generator with advanced features
Ruby
1
star
94

dctools

DC++ Auxilliary Tools
Python
1
star
95

spp

C++
1
star
96

dynlib

A C library for creating continous (fast) dynamically growing space for alot of small objects. Focus on usability, not conformity.
C
1
star
97

iplook

Simple IP->Host lookup utility, useful when there is a lack of reverse DNS:es.
Python
1
star