All Projects → rakaly → jomini

rakaly / jomini

Licence: MIT license
Low level, performance oriented parser for save and game files from EU4, CK3, HOI4, Vic3, Imperator, and other PDS titles.

Programming Languages

rust
11053 projects
r
7636 projects

Projects that are alternatives of or similar to jomini

IronyModManager
Mod Manager for Paradox Games. Official Discord: https://discord.gg/t9JmY8KFrV
Stars: ✭ 188 (+370%)
Mutual labels:  paradox, eu4, hoi4, ck3
hookey
Enables all the DLCs. Like Creamapi but just for linux and a subset of Paradox games.
Stars: ✭ 87 (+117.5%)
Mutual labels:  eu4, hoi4
content inspector
Fast inspection of binary buffers to guess/determine the type of content
Stars: ✭ 28 (-30%)
Mutual labels:  binary, text
Render
Go package for easily rendering JSON, XML, binary data, and HTML templates responses.
Stars: ✭ 1,562 (+3805%)
Mutual labels:  binary, text
Translate helper
A Java application to help to translate the localisation files of the Paradox games.
Stars: ✭ 23 (-42.5%)
Mutual labels:  eu4, hoi4
Snodge
Randomly mutate JSON, XML, HTML forms, text and binary data for fuzz testing
Stars: ✭ 121 (+202.5%)
Mutual labels:  binary, text
Txeh
Go library and CLI utilty for /etc/hosts management.
Stars: ✭ 181 (+352.5%)
Mutual labels:  binary
Reverse Engineering Tutorials
Some Reverse Engineering Tutorials for Beginners
Stars: ✭ 217 (+442.5%)
Mutual labels:  binary
Angr Utils
Handy utilities for the angr binary analysis framework, most notably CFG visualization
Stars: ✭ 169 (+322.5%)
Mutual labels:  binary
Ropa
GUI tool to create ROP chains using the ropper API
Stars: ✭ 151 (+277.5%)
Mutual labels:  binary
TextBoxes
TextBoxes: A Fast Text Detector with a Single Deep Neural Network
Stars: ✭ 625 (+1462.5%)
Mutual labels:  text
DotGrok
Parse text with pattern. Inspired by grok filter.
Stars: ✭ 26 (-35%)
Mutual labels:  text
Chronicle Wire
A Java Serialisation Library that supports multiple formats
Stars: ✭ 204 (+410%)
Mutual labels:  binary
Raw Wasm
Raw WebAssembly demos
Stars: ✭ 183 (+357.5%)
Mutual labels:  binary
Android Upload Service
Easily upload files (Multipart/Binary/FTP out of the box) in the background with progress notification. Support for persistent upload requests, customizations and custom plugins.
Stars: ✭ 2,593 (+6382.5%)
Mutual labels:  binary
Karkinos
A thorough library database to assist with binary exploitation tasks.
Stars: ✭ 170 (+325%)
Mutual labels:  binary
J2N
Java-like Components for .NET
Stars: ✭ 37 (-7.5%)
Mutual labels:  text
Cs2cpp
C# to C++ transpiler (Cs2Cpp) (Powered by Roslyn)
Stars: ✭ 155 (+287.5%)
Mutual labels:  binary
Binaryserializer
A declarative serialization framework for controlling formatting of data at the byte and bit level using field bindings, converters, and code.
Stars: ✭ 197 (+392.5%)
Mutual labels:  binary
GPT2-Telegram-Chatbot
GPT-2 Telegram Chat bot
Stars: ✭ 67 (+67.5%)
Mutual labels:  text

ci Version

Jomini

A low level, performance oriented parser for save and game files from Paradox Development Studio titles (eg: Europa Universalis (EU4), Hearts of Iron (HOI4), and Crusader Kings (CK3), Imperator, Stellaris, and Victoria).

For an in-depth look at the Paradox Clausewitz format and the pitfalls that come trying to support all variations, consult the write-up. In short, it's extremely difficult to write a robust and fast parser that abstracts over the format difference between games as well as differences between game patches. Jomini hits the sweet spot between flexibility while still being ergonomic.

Jomini is the cornerstone of the online EU4 save file analyzer. This library also powers the Paradox Game Converters and pdxu.

Features

  • Versatile: Handle both plaintext and binary encoded data
  • Fast: Parse data at over 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

Quick Start

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

use jomini::{
    text::{Operator, Property},
    JominiDeserialize,
};

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

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

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

let actual: Model = jomini::text::de::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 a couple extra steps for the caller to supply:

  • How text should be decoded (typically Windows-1252 or UTF-8)
  • How rational (floating point) numbers are decoded
  • How tokens, which are 16 bit integers that uniquely identify strings, are resolved

Implementors be warned, not only does each Paradox game have a different binary format, but the binary format can vary between patches!

Below is an example that defines a sample binary format and uses a hashmap token lookup.

use jomini::{BinaryDeserializer, Encoding, JominiDeserialize, Windows1252Encoding};
use std::{borrow::Cow, collections::HashMap};

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

#[derive(Debug, Default)]
pub struct BinaryTestFlavor;

impl jomini::binary::BinaryFlavor for BinaryTestFlavor {
    fn visit_f32(&self, data: [u8; 4]) -> f32 {
        f32::from_le_bytes(data)
    }

    fn visit_f64(&self, data: [u8; 8]) -> f64 {
        f64::from_le_bytes(data)
    }
}

impl Encoding for BinaryTestFlavor {
    fn decode<'a>(&self, data: &'a [u8]) -> Cow<'a, str> {
        Windows1252Encoding::decode(data)
    }
}

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::builder_flavor(BinaryTestFlavor)
    .deserialize_slice(&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 reader = tape.windows1252_reader();

for (key, _op, value) in reader.fields() {
    println!("{:?}={:?}", key.read_str(), value.read_str().unwrap());
}

The mid-level API also provides the excellent utility of converting the plaintext Clausewitz format to JSON when the json feature is enabled.

use jomini::TextTape;

let tape = TextTape::from_slice(b"foo=bar")?;
let reader = tape.windows1252_reader();
let actual = reader.json().to_string()?;
assert_eq!(actual, r#"{"foo":"bar"}"#);

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.

Write API

There are two targeted use cases for the write API. One is when a text tape is on hand. This is useful when one needs to reformat a document (note that comments are not preserved):

use jomini::{TextTape, TextWriterBuilder};

let tape = TextTape::from_slice(b"hello   = world")?;
let mut out: Vec<u8> = Vec::new();
let mut writer = TextWriterBuilder::new().from_writer(&mut out);
writer.write_tape(&tape)?;
assert_eq!(&out, b"hello=world");

The writer normalizes any formatting issues. The writer is not able to losslessly write all parsed documents, but these are limited to truly esoteric situations and hope to be resolved in future releases.

The other use case is geared more towards incremental writing that can be found in melters or those crafting documents by hand. These use cases need to manually drive the writer:

use jomini::TextWriterBuilder;
let mut out: Vec<u8> = Vec::new();
let mut writer = TextWriterBuilder::new().from_writer(&mut out);
writer.write_unquoted(b"hello")?;
writer.write_unquoted(b"world")?;
writer.write_unquoted(b"foo")?;
writer.write_unquoted(b"bar")?;
assert_eq!(&out, b"hello=world\nfoo=bar");

Unsupported Syntax

Due to the nature of Clausewitz being closed source, this library can never guarantee compatibility with Clausewitz. There is no specification of what valid input looks like, and we only have examples that have been collected in the wild. From what we do know, Clausewitz is recklessly flexible: allowing each game object to potentially define its own unique syntax.

We can only do our best and add support for new syntax as it is encountered.

Benchmarks

Benchmarks are ran with the following command:

cargo clean
cargo bench -- parse
find ./target -wholename "*/new/raw.csv" -print0 | xargs -0 xsv cat rows > assets/jomini-benchmarks.csv

And can be analyzed with the R script found in the assets directory.

Below is a graph generated from benchmarking on an arbitrary computer.

jomini-bench-throughput.png

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].