Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions crates/ltk_inibin/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "ltk_inibin"
version = "0.1.0"
edition = "2021"
description = "Inibin (INIBIN v1/v2) parser and writer for League Toolkit"
license = "MIT OR Apache-2.0"
readme = "../../README.md"

[features]
serde = ["dep:serde", "indexmap/serde"]

[dependencies]
thiserror = { workspace = true }
byteorder = { workspace = true }
num_enum = { workspace = true }
miette = { workspace = true }
indexmap = { workspace = true }
serde = { workspace = true, optional = true }
19 changes: 19 additions & 0 deletions crates/ltk_inibin/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use crate::types::InibinFlags;

#[derive(Debug, thiserror::Error, miette::Diagnostic)]
pub enum InibinError {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),

#[error("Empty inibin data")]
Empty,

#[error("Unknown inibin version: {0}")]
UnknownVersion(u8),

#[error("Cannot write v1 (old format) entries to binary — convert to v2 storage types first")]
V1WriteNotSupported,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an obsolete error as we don't really care about v1 writing. We should write "v2" by default.


#[error("Invalid storage type: {0}")]
InvalidStorageType(#[from] num_enum::TryFromPrimitiveError<InibinFlags>),
}
39 changes: 39 additions & 0 deletions crates/ltk_inibin/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//! `ltk_inibin` — Inibin (INIBIN v1/v2) parser and writer for League Toolkit.
//!
//! Handles `.inibin`, `.troybin`, and `.cfgbin` files — all share the same
//! binary format. Values are stored in typed buckets ([`InibinSet`]) grouped
//! by storage type ([`InibinFlags`]).
//!
//! # Quick start
//!
//! ```no_run
//! let data = std::fs::read("particle.troybin").unwrap();
//! let file = ltk_inibin::from_slice(&data).unwrap();
//!
//! // Look up a value by hash
//! if let Some(val) = file.get(0xDEADBEEF) {
//! println!("{val:?}");
//! }
//!
//! // Write back to binary (v2)
//! let mut output = Vec::new();
//! ltk_inibin::write(&mut output, &file).unwrap();
//! ```

mod error;
mod reader;
mod types;
mod writer;

pub use error::InibinError;
pub use types::{InibinFile, InibinFlags, InibinSet, InibinValue};

/// Read an inibin binary from a byte slice.
pub fn from_slice(data: &[u8]) -> Result<InibinFile, InibinError> {
reader::from_slice(data)
}

/// Write an [`InibinFile`] to binary v2 format.
pub fn write<W: std::io::Write>(w: &mut W, file: &InibinFile) -> Result<(), InibinError> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function should be implemented directly on top of an Inibin struct.
Additionally it would be good to rename InibinFile to just Inibin for brewity.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All structs should have the Inibin prefix removed, besides the actual Inibin struct

writer::write(w, file)
}
217 changes: 217 additions & 0 deletions crates/ltk_inibin/src/reader.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
//! Binary reader for INIBIN v1 and v2 files.

use std::io::{Cursor, Read};

use byteorder::{ReadBytesExt, LE};
use indexmap::IndexMap;

use crate::error::InibinError;
use crate::types::{InibinFile, InibinFlags, InibinSet, InibinValue};

// ── V1 reader ───────────────────────────────────────────────────────────

fn sanitize_str(s: &str) -> InibinValue {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should probably just be a FromStr impl on InibinValue

if s == "true" {
return InibinValue::Bool(true);
}
if s == "false" {
return InibinValue::Bool(false);
}

if let Ok(v) = s.parse::<i32>() {
if !s.contains('.') && !s.contains('e') && !s.contains('E') {
return InibinValue::I32(v);
}
}

if let Ok(v) = s.parse::<f32>() {
return InibinValue::F32(v);
}

InibinValue::String(s.to_string())
}

fn read_v1<R: Read>(r: &mut R) -> Result<InibinFile, InibinError> {
let mut skip_buf = [0u8; 3];
r.read_exact(&mut skip_buf)?;
let entry_count = r.read_u32::<LE>()? as usize;
let data_count = r.read_u32::<LE>()? as usize;

let mut offsets = Vec::with_capacity(entry_count);
for _ in 0..entry_count {
let h = r.read_u32::<LE>()?;
let o = r.read_u32::<LE>()? as usize;
offsets.push((h, o));
}

let mut data = vec![0u8; data_count];
r.read_exact(&mut data)?;

let mut properties = IndexMap::new();
for &(hash, offset) in &offsets {
let mut o = offset;
let mut s = String::new();
while o < data.len() && data[o] != 0 {
s.push(data[o] as char);
o += 1;
}
properties.insert(hash, sanitize_str(&s));
}

let set = InibinSet::with_properties(InibinFlags::OldFormat, properties);
let mut file = InibinFile::new();
file.set_version(1);
file.insert_set(set);
Ok(file)
}

// ── V2 readers ──────────────────────────────────────────────────────────

fn read_bools<R: Read>(r: &mut R) -> Result<InibinSet, InibinError> {
let num = r.read_u16::<LE>()? as usize;
let mut keys = Vec::with_capacity(num);
for _ in 0..num {
keys.push(r.read_u32::<LE>()?);
}
let bytes_count = num.div_ceil(8);
let mut bools = vec![0u8; bytes_count];
r.read_exact(&mut bools)?;

let mut properties = IndexMap::with_capacity(num);
for (j, &key) in keys.iter().enumerate() {
let bit = (bools[j / 8] >> (j % 8)) & 1;
properties.insert(key, InibinValue::Bool(bit != 0));
}
Ok(InibinSet::with_properties(InibinFlags::BitList, properties))
}

fn read_numbers<R: Read>(r: &mut R, flags: InibinFlags) -> Result<InibinSet, InibinError> {
let num = r.read_u16::<LE>()? as usize;
let keys = (0..num).map(|_| r.read_u32::<LE>()).collect::<Vec<_>>(); // untested

let mut properties = IndexMap::with_capacity(num);
for &key in &keys {
let value = match flags {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can this be extracted to a method like from_reader on InibinValue?

InibinFlags::Int32List | InibinFlags::Int32LongList => {
InibinValue::I32(r.read_i32::<LE>()?)
}
InibinFlags::Float32List => InibinValue::F32(r.read_f32::<LE>()?),
InibinFlags::FixedPointFloatList => {
InibinValue::FixedPointFloat(r.read_u8()? as f64 * 0.1)
}
InibinFlags::Int16List => InibinValue::I16(r.read_i16::<LE>()?),
InibinFlags::Int8List => InibinValue::U8(r.read_u8()?),
InibinFlags::FixedPointFloatListVec3 => {
let a = r.read_u8()? as f64 * 0.1;
let b = r.read_u8()? as f64 * 0.1;
let c = r.read_u8()? as f64 * 0.1;
InibinValue::FixedPointVec3([a, b, c])
}
InibinFlags::Float32ListVec3 => {
let a = r.read_f32::<LE>()?;
let b = r.read_f32::<LE>()?;
let c = r.read_f32::<LE>()?;
InibinValue::F32Vec3([a, b, c])
}
InibinFlags::FixedPointFloatListVec2 => {
let a = r.read_u8()? as f64 * 0.1;
let b = r.read_u8()? as f64 * 0.1;
InibinValue::FixedPointVec2([a, b])
}
InibinFlags::Float32ListVec2 => {
let a = r.read_f32::<LE>()?;
let b = r.read_f32::<LE>()?;
InibinValue::F32Vec2([a, b])
}
InibinFlags::FixedPointFloatListVec4 => {
let a = r.read_u8()? as f64 * 0.1;
let b = r.read_u8()? as f64 * 0.1;
let c = r.read_u8()? as f64 * 0.1;
let d = r.read_u8()? as f64 * 0.1;
InibinValue::FixedPointVec4([a, b, c, d])
}
InibinFlags::Float32ListVec4 => {
let a = r.read_f32::<LE>()?;
let b = r.read_f32::<LE>()?;
let c = r.read_f32::<LE>()?;
let d = r.read_f32::<LE>()?;
InibinValue::F32Vec4([a, b, c, d])
}
_ => unreachable!(),
};
properties.insert(key, value);
}
Ok(InibinSet::with_properties(flags, properties))
}

fn read_strings<R: Read>(r: &mut R, strings_length: usize) -> Result<InibinSet, InibinError> {
let num = r.read_u16::<LE>()? as usize;
let mut keys = Vec::with_capacity(num);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you change these to iterators as well

for _ in 0..num {
keys.push(r.read_u32::<LE>()?);
}
let mut offsets = Vec::with_capacity(num);
for _ in 0..num {
offsets.push(r.read_u16::<LE>()? as usize);
}
let mut data = vec![0u8; strings_length];
r.read_exact(&mut data)?;

let mut properties = IndexMap::with_capacity(num);
for i in 0..num {
let mut o = offsets[i];
let mut s = String::new();
while o < data.len() && data[o] != 0 {
s.push(data[o] as char);
o += 1;
}
properties.insert(keys[i], InibinValue::String(s));
}
Ok(InibinSet::with_properties(
InibinFlags::StringList,
properties,
))
}

fn read_v2<R: Read>(r: &mut R) -> Result<InibinFile, InibinError> {
let strings_length = r.read_u16::<LE>()? as usize;
let mut flags = r.read_u16::<LE>()?;
if flags == 0 {
flags = r.read_u16::<LE>()?;
}

let mut file = InibinFile::new();

for i in 0u8..14 {
if flags & (1 << i) == 0 {
continue;
}
let set = match i {
5 => read_bools(r)?,
12 => read_strings(r, strings_length)?,
_ => {
let inibin_flags = InibinFlags::try_from(i)?;
read_numbers(r, inibin_flags)?
}
};
file.insert_set(set);
}

Ok(file)
}

/// Read an inibin binary from a byte slice.
pub fn from_slice(data: &[u8]) -> Result<InibinFile, InibinError> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be a from_reader method on InibinFile, with an additional from_slice helper method

if data.is_empty() {
return Err(InibinError::Empty);
}

let mut cursor = Cursor::new(data);
let version = cursor.read_u8()?;

match version {
2 => read_v2(&mut cursor),
1 => read_v1(&mut cursor),
_ => Err(InibinError::UnknownVersion(version)),
}
}
Loading
Loading