yog-storage 0.1.1

Yog persistent key-value storage for mod data.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Scoped, typed, auto-flushing persistent key-value storage for Yog mods.
//!
//! # Quick start
//! ```no_run
//! use yog_storage::{Storage, Value};
//!
//! // Global store — one file per mod
//! let mut store = Storage::open("/path/to/game", "mymod");
//! store.set("motd", "Hello!");
//! store.set("spawn_x", 0i64);
//!
//! // Per-player store — one file per UUID
//! let mut ps = Storage::open_player("/path/to/game", "mymod", "player-uuid");
//! ps.set("coins", 100i64);
//! let coins = ps.get_int("coins").unwrap_or(0);
//!
//! // Auto-flushed on drop.  Call flush() explicitly for earlier persistence.
//! ```
//!
//! # File layout
//! ```text
//! <game_dir>/yog-data/<mod_id>/global.kv
//! <game_dir>/yog-data/<mod_id>/player/<uuid>.kv
//! <game_dir>/yog-data/<mod_id>/world/<dim_safe>.kv
//! <game_dir>/yog-data/<mod_id>/entity/<uuid>.kv
//! <game_dir>/yog-data/<mod_id>/chunk/<dim_safe>_<cx>_<cz>.kv
//! ```
//!
//! # File format
//! Plain text, one entry per line: `key\ttype\tvalue`.  Human-readable and
//! diff-friendly.  Lines starting with `#` are comments.  Writes are atomic
//! (write to `.kv.tmp`, then rename) so a crash mid-save leaves old data intact.

use std::collections::BTreeMap;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};

// ── StorageScope ──────────────────────────────────────────────────────────────

/// Determines which backing file a [`Storage`] uses.
#[derive(Debug, Clone, Copy)]
pub enum StorageScope<'a> {
    /// One store shared across the entire server (the default).
    Global,
    /// Per-player store, keyed by UUID string.
    Player(&'a str),
    /// Per-dimension store, keyed by dimension id (e.g. `"minecraft:overworld"`).
    World(&'a str),
    /// Per-entity store, keyed by UUID string.
    Entity(&'a str),
    /// Per-chunk store, keyed by dimension + chunk coordinates.
    Chunk(&'a str, i32, i32),
}

// ── Value ─────────────────────────────────────────────────────────────────────

/// A typed storage value.
///
/// [`From`] is implemented for `String`, `&str`, `i64`, `i32`, `u32`, `u64`,
/// `usize`, `f64`, `f32`, `bool`, and `Vec<u8>`, so `store.set("k", 42i64)`
/// works without an explicit constructor.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Str(String),
    Int(i64),
    Float(f64),
    Bool(bool),
    /// Raw byte sequence; stored as lowercase hex on disk.
    Bytes(Vec<u8>),
}

impl Value {
    pub fn as_str(&self) -> Option<&str> {
        if let Value::Str(s) = self {
            Some(s)
        } else {
            None
        }
    }

    /// Returns the integer value.  A `Float` is truncated to `i64`.
    pub fn as_int(&self) -> Option<i64> {
        match self {
            Value::Int(n) => Some(*n),
            Value::Float(f) => Some(*f as i64),
            _ => None,
        }
    }

    /// Returns the float value.  An `Int` is widened to `f64`.
    pub fn as_float(&self) -> Option<f64> {
        match self {
            Value::Float(f) => Some(*f),
            Value::Int(n) => Some(*n as f64),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        if let Value::Bool(b) = self {
            Some(*b)
        } else {
            None
        }
    }

    pub fn as_bytes(&self) -> Option<&[u8]> {
        if let Value::Bytes(b) = self {
            Some(b)
        } else {
            None
        }
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Value::Str(s)
    }
}
impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Value::Str(s.to_string())
    }
}
impl From<i64> for Value {
    fn from(n: i64) -> Self {
        Value::Int(n)
    }
}
impl From<i32> for Value {
    fn from(n: i32) -> Self {
        Value::Int(n as i64)
    }
}
impl From<u32> for Value {
    fn from(n: u32) -> Self {
        Value::Int(n as i64)
    }
}
impl From<u64> for Value {
    fn from(n: u64) -> Self {
        Value::Int(n as i64)
    }
}
impl From<usize> for Value {
    fn from(n: usize) -> Self {
        Value::Int(n as i64)
    }
}
impl From<f64> for Value {
    fn from(f: f64) -> Self {
        Value::Float(f)
    }
}
impl From<f32> for Value {
    fn from(f: f32) -> Self {
        Value::Float(f as f64)
    }
}
impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Value::Bool(b)
    }
}
impl From<Vec<u8>> for Value {
    fn from(b: Vec<u8>) -> Self {
        Value::Bytes(b)
    }
}

// ── Storage ───────────────────────────────────────────────────────────────────

/// Typed, scoped persistent key-value store.
///
/// Mutations are buffered in memory.  The store is auto-flushed on [`Drop`]
/// if any key was mutated.  Call [`flush`](Self::flush) explicitly when you
/// need the data on disk immediately (e.g. end of a critical event handler).
pub struct Storage {
    path: PathBuf,
    data: BTreeMap<String, Value>,
    dirty: bool,
}

impl Storage {
    // ── constructors ─────────────────────────────────────────────────────────

    /// Open the **global** store for `mod_id`.
    pub fn open(game_dir: &str, mod_id: &str) -> Self {
        Self::from_path(scope_path(game_dir, mod_id, StorageScope::Global))
    }

    /// Open a store with an explicit [`StorageScope`].
    pub fn open_scoped(game_dir: &str, mod_id: &str, scope: StorageScope<'_>) -> Self {
        Self::from_path(scope_path(game_dir, mod_id, scope))
    }

    /// Open a **per-player** store (keyed by player UUID).
    pub fn open_player(game_dir: &str, mod_id: &str, player_uuid: &str) -> Self {
        Self::from_path(scope_path(
            game_dir,
            mod_id,
            StorageScope::Player(player_uuid),
        ))
    }

    /// Open a **per-dimension** store.
    pub fn open_world(game_dir: &str, mod_id: &str, dimension: &str) -> Self {
        Self::from_path(scope_path(game_dir, mod_id, StorageScope::World(dimension)))
    }

    /// Open a **per-entity** store (keyed by entity UUID).
    pub fn open_entity(game_dir: &str, mod_id: &str, entity_uuid: &str) -> Self {
        Self::from_path(scope_path(
            game_dir,
            mod_id,
            StorageScope::Entity(entity_uuid),
        ))
    }

    /// Open a **per-chunk** store.
    pub fn open_chunk(game_dir: &str, mod_id: &str, dimension: &str, cx: i32, cz: i32) -> Self {
        Self::from_path(scope_path(
            game_dir,
            mod_id,
            StorageScope::Chunk(dimension, cx, cz),
        ))
    }

    fn from_path(path: PathBuf) -> Self {
        let data = load_file(&path);
        Self {
            path,
            data,
            dirty: false,
        }
    }

    // ── read ─────────────────────────────────────────────────────────────────

    pub fn get(&self, key: &str) -> Option<&Value> {
        self.data.get(key)
    }

    pub fn get_str(&self, key: &str) -> Option<&str> {
        self.data.get(key)?.as_str()
    }

    pub fn get_int(&self, key: &str) -> Option<i64> {
        self.data.get(key)?.as_int()
    }

    pub fn get_float(&self, key: &str) -> Option<f64> {
        self.data.get(key)?.as_float()
    }

    pub fn get_bool(&self, key: &str) -> Option<bool> {
        self.data.get(key)?.as_bool()
    }

    pub fn get_bytes(&self, key: &str) -> Option<&[u8]> {
        self.data.get(key)?.as_bytes()
    }

    pub fn contains(&self, key: &str) -> bool {
        self.data.contains_key(key)
    }

    // ── write ─────────────────────────────────────────────────────────────────

    /// Insert or replace a value.
    ///
    /// Accepts any type that implements `Into<Value>` — `i64`, `f64`, `bool`,
    /// `&str`, `String`, `Vec<u8>`, etc.
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<Value>) {
        self.data.insert(key.into(), value.into());
        self.dirty = true;
    }

    pub fn remove(&mut self, key: &str) -> Option<Value> {
        let v = self.data.remove(key);
        if v.is_some() {
            self.dirty = true;
        }
        v
    }

    pub fn clear(&mut self) {
        if !self.data.is_empty() {
            self.data.clear();
            self.dirty = true;
        }
    }

    // ── meta ─────────────────────────────────────────────────────────────────

    pub fn len(&self) -> usize {
        self.data.len()
    }
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
        self.data.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// Absolute path of the backing file.
    pub fn path(&self) -> &Path {
        &self.path
    }

    // ── persistence ──────────────────────────────────────────────────────────

    /// Atomically write all data to disk.
    ///
    /// Writes to `<path>.kv.tmp` first, then renames it over `<path>`.
    /// A crash mid-write leaves the previous on-disk state intact.
    pub fn flush(&mut self) -> io::Result<()> {
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let tmp = self.path.with_extension("kv.tmp");
        {
            let mut f = std::fs::File::create(&tmp)?;
            writeln!(f, "# yog-storage v2")?;
            for (k, v) in &self.data {
                let (typ, enc) = encode_value(v);
                writeln!(f, "{}\t{}\t{}", str_escape(k), typ, enc)?;
            }
            f.flush()?;
        }
        std::fs::rename(&tmp, &self.path)?;
        self.dirty = false;
        Ok(())
    }
}

impl Drop for Storage {
    fn drop(&mut self) {
        if self.dirty {
            let _ = self.flush();
        }
    }
}

// ── internal helpers ──────────────────────────────────────────────────────────

fn scope_path(game_dir: &str, mod_id: &str, scope: StorageScope<'_>) -> PathBuf {
    let safe_mod = mod_id.replace([':', '/'], "_");
    let base = Path::new(game_dir).join("yog-data").join(safe_mod);
    match scope {
        StorageScope::Global => base.join("global.kv"),
        StorageScope::Player(uuid) => base.join("player").join(format!("{uuid}.kv")),
        StorageScope::World(dim) => base.join("world").join(format!("{}.kv", dim_safe(dim))),
        StorageScope::Entity(uuid) => base.join("entity").join(format!("{uuid}.kv")),
        StorageScope::Chunk(dim, x, z) => base
            .join("chunk")
            .join(format!("{}_{x}_{z}.kv", dim_safe(dim))),
    }
}

fn dim_safe(dim: &str) -> String {
    dim.replace([':', '/'], "_")
}

fn load_file(path: &Path) -> BTreeMap<String, Value> {
    let file = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(_) => return BTreeMap::new(),
    };
    let mut map = BTreeMap::new();
    for line in io::BufReader::new(file).lines() {
        let Ok(line) = line else { continue };
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut cols = line.splitn(3, '\t');
        let (Some(raw_k), Some(typ), Some(raw_v)) = (cols.next(), cols.next(), cols.next()) else {
            continue;
        };
        if let Some(v) = parse_value(typ, raw_v) {
            map.insert(str_unescape(raw_k), v);
        }
    }
    map
}

fn parse_value(typ: &str, raw: &str) -> Option<Value> {
    match typ {
        "s" => Some(Value::Str(str_unescape(raw))),
        "i" => raw.parse::<i64>().ok().map(Value::Int),
        "f" => raw.parse::<f64>().ok().map(Value::Float),
        "b" => Some(Value::Bool(raw == "1")),
        "x" => Some(Value::Bytes(hex_decode(raw))),
        _ => None,
    }
}

fn encode_value(v: &Value) -> (&'static str, String) {
    match v {
        Value::Str(s) => ("s", str_escape(s)),
        Value::Int(n) => ("i", n.to_string()),
        Value::Float(f) => ("f", f.to_string()),
        Value::Bool(b) => ("b", if *b { "1" } else { "0" }.to_string()),
        Value::Bytes(b) => ("x", hex_encode(b)),
    }
}

fn str_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 4);
    for c in s.chars() {
        match c {
            '\\' => out.push_str(r"\\"),
            '\t' => out.push_str(r"\t"),
            '\n' => out.push_str(r"\n"),
            '\r' => out.push_str(r"\r"),
            c => out.push(c),
        }
    }
    out
}

fn str_unescape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('\\') => out.push('\\'),
                Some('t') => out.push('\t'),
                Some('n') => out.push('\n'),
                Some('r') => out.push('\r'),
                Some(c) => {
                    out.push('\\');
                    out.push(c);
                }
                None => out.push('\\'),
            }
        } else {
            out.push(c);
        }
    }
    out
}

fn hex_encode(b: &[u8]) -> String {
    use std::fmt::Write as FmtWrite;
    b.iter()
        .fold(String::with_capacity(b.len() * 2), |mut s, byte| {
            let _ = write!(s, "{byte:02x}");
            s
        })
}

fn hex_decode(s: &str) -> Vec<u8> {
    (0..s.len())
        .step_by(2)
        .filter_map(|i| s.get(i..i + 2))
        .filter_map(|h| u8::from_str_radix(h, 16).ok())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn game_dir(name: &str) -> String {
        let d = std::env::temp_dir().join(format!("yog-storage-test-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        d.to_string_lossy().into_owned()
    }

    #[test]
    fn every_value_comes_back_after_a_flush() {
        let dir = game_dir("roundtrip");
        let odd = "tab\there\nnew line \\ backslash";
        {
            let mut s = Storage::open(&dir, "mymod");
            s.set("text", odd);
            s.set("int", -42i64);
            s.set("float", 2.5f64);
            s.set("yes", true);
            s.set("bytes", vec![0u8, 9, 10, 255]);
            assert!(s.is_dirty());
            s.flush().unwrap();
            assert!(!s.is_dirty());
        }
        let s = Storage::open(&dir, "mymod");
        assert_eq!(s.get_str("text"), Some(odd), "tabs and newlines survive");
        assert_eq!(s.get_int("int"), Some(-42));
        assert_eq!(s.get_float("float"), Some(2.5));
        assert_eq!(s.get_bool("yes"), Some(true));
        assert_eq!(s.get_bytes("bytes"), Some(&[0u8, 9, 10, 255][..]));
        assert_eq!(s.len(), 5);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn dropping_saves_and_scopes_keep_apart() {
        let dir = game_dir("scopes");
        {
            let mut p = Storage::open_player(&dir, "mymod", "uuid-1");
            p.set("coins", 7i64);
            let mut c = Storage::open_chunk(&dir, "mymod", "minecraft:overworld", -1, 2);
            c.set("ore", "copper");
        }
        assert_eq!(Storage::open_player(&dir, "mymod", "uuid-1").get_int("coins"), Some(7), "saved on drop");
        assert_eq!(Storage::open_player(&dir, "mymod", "uuid-2").get_int("coins"), None);
        assert_eq!(Storage::open_chunk(&dir, "mymod", "minecraft:overworld", -1, 2).get_str("ore"), Some("copper"));
        assert!(Storage::open(&dir, "mymod").is_empty(), "the global store is its own");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn values_convert() {
        assert_eq!(Value::from(3u32).as_int(), Some(3));
        assert_eq!(Value::from("x").as_str(), Some("x"));
        assert_eq!(Value::from(true).as_int(), None);
    }
}