Skip to main content

Module persistence

Module persistence 

Source
Expand description

Inventory serialisation and deserialisation to/from JSON files on disk.

This module provides two free functions — save_inventory and load_inventory — that convert an crate::items::inventory::Inventory to and from a human-readable JSON file. The format is intentionally simple and hand-editable.

§File format

The JSON file is a single object with two top-level fields:

{
  "capacity": 3,
  "slots": [
    null,
    { "item_byte": 2, "count": 7 },
    null
  ]
}
  • capacity — the maximum slot count of the original inventory.
  • slots — one entry per slot; null for empty slots, or an object with item_byte (the value returned by crate::items::inventory::ItemType::to_byte) and count.

§Save / load contract

  • save_inventory validates the source and decoded byte-alias totals, creates missing parent directories, and replaces the destination with a synced sibling temporary file. Errors before replacement leave an existing save untouched.
  • load_inventory restores the inventory with the same capacity and slot layout. Zero counts and bytes decoded as default/empty become None at the same index; malformed layout or overflowing item totals are rejected.
  • Existing regular-file permissions are preserved. Final symlinks are followed without replacing the link, on both save and load. Follow-through resolves the link manually (see resolved_link_target) instead of letting the kernel open through the reparse point: CI runners whose %TEMP% mixes the 8.3 short name (RUNNER~1) with long names return ERROR_INVALID_NAME (123) exactly when opening through a relative-target link. Dangling links, nonregular/read-only targets, and Unix multiply hard-linked targets are rejected.
  • Replacement provides whole-snapshot visibility, not transaction isolation between writers or universal power-cut durability. Parent directories must be trusted: hostile namespace races and preservation of existing ownership, ACLs, and extended attributes are outside this contract. New Windows files use a protected current-user-only DACL, verified before any JSON write; filesystems without persistent ACL support fail closed.
  • Both functions propagate I/O and JSON errors as Box<dyn std::error::Error>.

Functions§

load_inventory
Reads and deserialises an crate::items::inventory::Inventory from the JSON file at path.
save_inventory
Writes inventory to a pretty-printed JSON file at path.