Crate jomini[][src]

A low level, performance oriented parser for EU4 save files and other PDS developed titles.

Jomini is the cornerstone of the Rakaly, an EU4 achievement leaderboard and save file analyzer. This library is also used in the Paradox Game Converters project to parse ironman EU4, CK3, and Imperator saves.

Features

  • ✔ Versatile: Handle both plaintext and binary encoded data
  • ✔ Fast: Parse data at 1 GB/s
  • ✔ Small: Compile with zero dependencies
  • ✔ Safe: Extensively fuzzed against potential malicious input
  • ✔ Ergonomic: Use serde-like macros to have parsing logic automatically implemented
  • ✔ Embeddable: Cross platform native apps, statically compiled services, or in the browser via WASM
  • ✔ Agnostic: Parse EU4, HOI4, Imperator, CK3, and Vic2 save and game files

Quick Start

Below is a demonstration on parsing plaintext data using jomini tools.

use jomini::{JominiDeserialize, TextDeserializer};

#[derive(JominiDeserialize, PartialEq, Debug)]
pub struct Model {
    human: bool,
    first: Option<u16>,
    #[jomini(alias = "forth")]
    fourth: u16,
    #[jomini(alias = "core", duplicated)]
    cores: Vec<String>,
    names: Vec<String>,
}

let data = br#"
    human = yes
    forth = 10
    core = "HAB"
    names = { "Johan" "Frederick" }
    core = FRA
"#;

let expected = Model {
    human: true,
    first: None,
    fourth: 10,
    cores: vec!["HAB".to_string(), "FRA".to_string()],
    names: vec!["Johan".to_string(), "Frederick".to_string()],
};

let actual: Model = TextDeserializer::from_windows1252_slice(data)?;
assert_eq!(actual, expected);

Binary Parsing

Parsing data encoded in the binary format is done in a similar fashion but with an extra step. Tokens can be encoded into 16 integers, and so one must provide a map from these integers to their textual representations

use jomini::{JominiDeserialize, BinaryDeserializer};
use std::collections::HashMap;

#[derive(JominiDeserialize, PartialEq, Debug)]
struct MyStruct {
    field1: String,
}

let data = [ 0x82, 0x2d, 0x01, 0x00, 0x0f, 0x00, 0x03, 0x00, 0x45, 0x4e, 0x47 ];

let mut map = HashMap::new();
map.insert(0x2d82, "field1");

let actual: MyStruct = BinaryDeserializer::from_eu4(&data[..], &map)?;
assert_eq!(actual, MyStruct { field1: "ENG".to_string() });

When done correctly, one can use the same structure to represent both the plaintext and binary data without any duplication.

One can configure the behavior when a token is unknown (ie: fail immediately or try to continue).

Caveats

Caller is responsible for:

  • Determining the correct format (text or binary) ahead of time
  • Stripping off any header that may be present (eg: EU4txt / EU4bin)
  • Providing the token resolver for the binary format
  • Providing the conversion to reconcile how, for example, a date may be encoded as an integer in the binary format, but as a string when in plaintext.

The Mid-level API

If the automatic deserialization via JominiDeserialize is too high level, there is a mid-level api where one can easily iterate through the parsed document and interrogate fields for their information.

use jomini::TextTape;

let data = b"name=aaa name=bbb core=123 name=ccc name=ddd";
let tape = TextTape::from_slice(data).unwrap();
let mut reader = tape.windows1252_reader();

while let Some((key, _op, value)) = reader.next_field() {
    println!("{:?}={:?}", key.read_str(), value.read_str().unwrap());
}

One Level Lower

At the lowest layer, one can interact with the raw data directly via TextTape and BinaryTape.

use jomini::{TextTape, TextToken, Scalar};

let data = b"foo=bar";

assert_eq!(
    TextTape::from_slice(&data[..])?.tokens(),
    &[
        TextToken::Unquoted(Scalar::new(b"foo")),
        TextToken::Unquoted(Scalar::new(b"bar")),
    ]
);

If one will only use TextTape and BinaryTape then jomini can be compiled without default features, resulting in a build without dependencies.

Modules

common

Common data structures used across games

Structs

ArrayReader

A text reader that advances through a sequence of values

BinaryDeserializer

A structure to deserialize binary data into Rust values.

BinaryDeserializerBuilder

Build a tweaked binary deserializer

BinaryTape

Houses the tape of tokens that is extracted from binary data

BinaryTapeParser

Customizes how the binary tape is parsed from data

Ck3Flavor

The ck3 binary flavor

DeserializeError

A Serde deserialization error.

Error

An error that can occur when processing data

Eu4Flavor

The eu4 binary flavor

ObjectReader

A reader that will advance through an object

Rgb

Extracted color info

Scalar

A byte slice that represents a single value.

ScalarReader

A text reader that wraps an underlying scalar value

TextDeserializer

A structure to deserialize text data into Rust values.

TextTape

Houses the tape of tokens that is extracted from plaintext data

Utf8Encoding

Decodes bytes according to the utf8 standard

ValueReader

A text reader for a text value

Windows1252Encoding

Decodes bytes according to the windows1252 code page

Enums

BinaryToken

Represents any valid binary value

DeserializeErrorKind

The type of a Serde deserialization error.

ErrorKind

Specific type of error

FailedResolveStrategy

Customize how the deserializer reacts when a token can’t be resolved

Operator

An operator token

Reader

All possible text reader variants

ScalarError

An error that can occur when converting a scalar into the requested type.

TextToken

Represents a valid text value

Traits

BinaryFlavor

Trait customizing decoding values from binary data

Encoding

An encoding for interpretting byte data as text

TokenResolver

Resolves binary 16bit tokens to field names

Derive Macros

JominiDeserialize

Creates a serde compatible Deserialize implementation