plasma-prp 0.1.0

Read, write, inspect, and manipulate Plasma engine PRP files used by Myst Online: Uru Live
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
//! SDL binary record parser — decode plStateDataRecord from network wire format.
//!
//! C++ ref: plSDL/plStateDataRecord.cpp, plSDL/plStateVariable.cpp
//! Wire format:
//!   StreamHeader: u16 savFlags | SafeString(name) | u16 version | optional UOID
//!   plStateDataRecord::Read: u16 flags | u8 ioVersion(=6) | vars... | sdvars...
//!   plSimpleStateVariable::ReadData: base(u8 saveFlags + notif) | u8 saveFlags | optional timestamp | data
//!   plSDStateVariable::ReadData: base(u8 saveFlags + notif) | u8 saveFlags | optional varlen count | dirty count | data records...

use anyhow::{Result, bail};
use std::io::{Cursor, Read};

use super::descriptor::{SdlManager, SdlType, StateDescriptor, VarDescriptor};

/// Contents/save flags for SDL stream header and variables.
/// C++ ref: plSDL::ContentsFlags
#[allow(dead_code)]
mod sdl_flags {
    pub const HAS_UOID: u16 = 0x1;
    pub const HAS_NOTIFICATION_INFO: u16 = 0x2;
    pub const HAS_TIMESTAMP: u16 = 0x4;
    pub const SAME_AS_DEFAULT: u16 = 0x8;
    pub const HAS_DIRTY_FLAG: u16 = 0x10;
    pub const WANT_TIMESTAMP: u16 = 0x20;
    pub const ADDED_VAR_LENGTH_IO: u16 = 0x8000;
}

const IO_VERSION: u8 = 6;

/// A parsed SDL state data record from the network.
#[derive(Debug, Clone)]
pub struct SdlRecord {
    pub descriptor_name: String,
    pub descriptor_version: u16,
    pub flags: u16,
    pub variables: Vec<SdlVarValue>,
    pub sd_variables: Vec<SdlNestedRecord>,
}

/// A parsed simple variable value.
#[derive(Debug, Clone)]
pub struct SdlVarValue {
    pub name: String,
    pub var_type: SdlType,
    pub is_dirty: bool,
    pub has_timestamp: bool,
    pub timestamp_secs: u32,
    pub timestamp_micros: u32,
    pub same_as_default: bool,
    pub values: Vec<SdlAtomicValue>,
}

/// A nested state descriptor variable.
#[derive(Debug, Clone)]
pub struct SdlNestedRecord {
    pub name: String,
    pub records: Vec<SdlRecord>,
}

/// Atomic values that can appear in SDL variables.
#[derive(Debug, Clone)]
pub enum SdlAtomicValue {
    Int(i32),
    Float(f32),
    Bool(bool),
    String(String),
    Double(f64),
    Byte(u8),
    Short(i16),
    Time { secs: u32, micros: u32 },
    /// Raw UOID bytes for plKey type
    Key(Vec<u8>),
    /// Creatable: class_index + raw data
    Creatable { class_index: u16, data: Vec<u8> },
    /// AgeTimeOfDay is computed, no data read
    AgeTimeOfDay,
}

/// Parse an SDL stream (the decompressed stream_data from SdlStateUpdate).
/// This is the full blob: StreamHeader + plStateDataRecord.
pub fn parse_sdl_record(data: &[u8], sdl_mgr: &SdlManager) -> Result<SdlRecord> {
    let mut cursor = Cursor::new(data);

    // 1. Read stream header
    let (name, version) = read_stream_header(&mut cursor)?;

    // 2. Find descriptor
    let desc = sdl_mgr.find(&name, version as u32)
        .or_else(|| sdl_mgr.find(&name, 0)); // fall back to latest

    // 3. Read the state data record
    read_state_data_record(&mut cursor, &name, version, desc)
}

/// Read just the stream header. Returns (descriptor_name, version).
/// C++ ref: plStateDataRecord::ReadStreamHeader
pub fn read_stream_header(cursor: &mut Cursor<&[u8]>) -> Result<(String, u16)> {
    let sav_flags = read_u16(cursor)?;
    if sav_flags & sdl_flags::ADDED_VAR_LENGTH_IO == 0 {
        bail!("SDL stream header missing kAddedVarLengthIO flag");
    }

    let name = read_safe_string(cursor)?;
    let version = read_u16(cursor)?;

    // Optional UOID
    if sav_flags & sdl_flags::HAS_UOID != 0 {
        skip_uoid(cursor)?;
    }

    Ok((name, version))
}

/// Read a plStateDataRecord body (after the stream header).
/// C++ ref: plStateDataRecord::Read
fn read_state_data_record(
    cursor: &mut Cursor<&[u8]>,
    desc_name: &str,
    desc_version: u16,
    desc: Option<&StateDescriptor>,
) -> Result<SdlRecord> {
    let flags = read_u16(cursor)?;
    let io_version = read_u8(cursor)?;
    if io_version != IO_VERSION {
        bail!("SDL IO version mismatch: expected {}, got {}", IO_VERSION, io_version);
    }

    // Separate simple vars and SD vars from the descriptor
    let (simple_descs, sd_descs) = if let Some(d) = desc {
        let mut simple = Vec::new();
        let mut nested = Vec::new();
        for v in &d.variables {
            if v.var_type == SdlType::StateDescriptor {
                nested.push(v);
            } else {
                simple.push(v);
            }
        }
        (simple, nested)
    } else {
        (Vec::new(), Vec::new())
    };

    let total_vars = if let Some(d) = desc { d.variables.len() } else { 256 };

    // Read simple variables
    let num_simple = variable_length_read(cursor, total_vars)?;
    let all_simple = num_simple == simple_descs.len();

    let mut variables = Vec::with_capacity(num_simple);
    for i in 0..num_simple {
        let idx = if !all_simple {
            variable_length_read(cursor, total_vars)?
        } else {
            i
        };

        let var_desc = simple_descs.get(idx);
        let var = read_simple_var(cursor, var_desc.copied())?;
        variables.push(var);
    }

    // Read nested SD variables
    let num_sd = variable_length_read(cursor, total_vars)?;
    let all_sd = num_sd == sd_descs.len();

    let mut sd_variables = Vec::with_capacity(num_sd);
    for i in 0..num_sd {
        let idx = if !all_sd {
            variable_length_read(cursor, total_vars)?
        } else {
            i
        };

        let sd_desc = sd_descs.get(idx);
        let sd_var = read_sd_var(cursor, sd_desc.copied(), desc_name)?;
        sd_variables.push(sd_var);
    }

    Ok(SdlRecord {
        descriptor_name: desc_name.to_string(),
        descriptor_version: desc_version,
        flags,
        variables,
        sd_variables,
    })
}

/// Read a plSimpleStateVariable from the stream.
/// C++ ref: plSimpleStateVariable::ReadData (calls base plStateVariable::ReadData first)
fn read_simple_var(cursor: &mut Cursor<&[u8]>, desc: Option<&VarDescriptor>) -> Result<SdlVarValue> {
    let name = desc.map(|d| d.name.clone()).unwrap_or_default();
    let var_type = desc.map(|d| d.var_type).unwrap_or(SdlType::Int);

    // 1. plStateVariable::ReadData — base class
    let base_save_flags = read_u8(cursor)?;
    if base_save_flags as u16 & sdl_flags::HAS_NOTIFICATION_INFO != 0 {
        read_notification_info(cursor)?;
    }

    // 2. plSimpleStateVariable-specific save flags
    let save_flags = read_u8(cursor)?;
    let is_dirty = save_flags as u16 & sdl_flags::HAS_DIRTY_FLAG != 0;
    let same_as_default = save_flags as u16 & sdl_flags::SAME_AS_DEFAULT != 0;
    let has_timestamp = save_flags as u16 & sdl_flags::HAS_TIMESTAMP != 0;

    let mut timestamp_secs = 0u32;
    let mut timestamp_micros = 0u32;
    if has_timestamp {
        // plUnifiedTime: u32 secs + u32 micros
        timestamp_secs = read_u32(cursor)?;
        timestamp_micros = read_u32(cursor)?;
    }

    let mut values = Vec::new();

    if !same_as_default {
        // Variable-length list: read count
        let count = if desc.map(|d| d.count == 0).unwrap_or(false) {
            // Variable length
            read_u32(cursor)? as usize
        } else {
            desc.map(|d| d.count).unwrap_or(1)
        };

        // Read each element
        let atomic_count = get_atomic_count(var_type);
        for _i in 0..count {
            let atom_values = read_atomic_values(cursor, var_type, atomic_count)?;
            values.extend(atom_values);
        }
    }

    Ok(SdlVarValue {
        name,
        var_type,
        is_dirty,
        has_timestamp,
        timestamp_secs,
        timestamp_micros,
        same_as_default,
        values,
    })
}

/// Read a plSDStateVariable (nested state descriptor variable).
/// C++ ref: plSDStateVariable::ReadData
fn read_sd_var(
    cursor: &mut Cursor<&[u8]>,
    desc: Option<&VarDescriptor>,
    _parent_desc_name: &str,
) -> Result<SdlNestedRecord> {
    let name = desc.map(|d| d.name.clone()).unwrap_or_default();

    // 1. plStateVariable::ReadData — base class
    let base_save_flags = read_u8(cursor)?;
    if base_save_flags as u16 & sdl_flags::HAS_NOTIFICATION_INFO != 0 {
        read_notification_info(cursor)?;
    }

    // 2. plSDStateVariable-specific
    let _save_flags = read_u8(cursor)?; // unused in C++

    let is_variable_length = desc.map(|d| d.count == 0).unwrap_or(false);
    let total_count = if is_variable_length {
        read_u32(cursor)? as usize
    } else {
        desc.map(|d| d.count).unwrap_or(1)
    };

    // Read dirty/used count
    let size_for_vl = if is_variable_length { 0xFFFF_FFFF_usize } else { total_count };
    let cnt = variable_length_read(cursor, size_for_vl)?;
    let all = cnt == total_count;

    let mut records = Vec::with_capacity(cnt);
    for i in 0..cnt {
        let _idx = if !all {
            variable_length_read(cursor, size_for_vl)?
        } else {
            i
        };

        // Each nested record is a full plStateDataRecord::Read
        // We don't have the nested descriptor easily, so parse with None
        let record = read_state_data_record(cursor, &name, 0, None)?;
        records.push(record);
    }

    Ok(SdlNestedRecord { name, records })
}

/// Read a SafeString. C++ ref: hsStream::ReadSafeString
fn read_safe_string(cursor: &mut Cursor<&[u8]>) -> Result<String> {
    let raw_len = read_u16(cursor)?;
    let num_chars = (raw_len & 0x0FFF) as usize;

    if num_chars == 0 {
        return Ok(String::new());
    }

    let mut buf = vec![0u8; num_chars];
    cursor.read_exact(&mut buf)?;

    // If high bit of first byte set, each byte is bitwise NOT'd
    if buf[0] & 0x80 != 0 {
        for b in &mut buf {
            *b = !*b;
        }
    }

    Ok(String::from_utf8_lossy(&buf).into_owned())
}

/// Read plStateVarNotificationInfo. C++ ref: plStateVarNotificationInfo::Read
fn read_notification_info(cursor: &mut Cursor<&[u8]>) -> Result<()> {
    let _save_flags = read_u8(cursor)?; // unused
    let _hint = read_safe_string(cursor)?;
    Ok(())
}

/// Skip a UOID in the stream (same format as in state.rs).
fn skip_uoid(cursor: &mut Cursor<&[u8]>) -> Result<()> {
    let contents = read_u8(cursor)?;
    let _seq = read_u32(cursor)?;
    let _loc_flags = read_u16(cursor)?;
    if contents & 0x02 != 0 {
        let _quality = read_u8(cursor)?;
        let _cap = read_u8(cursor)?;
    }
    let _class_type = read_u16(cursor)?;
    let _obj_id = read_u32(cursor)?;
    let name_len = read_u16(cursor)? as usize;
    let mut name_buf = vec![0u8; name_len];
    cursor.read_exact(&mut name_buf)?;
    if contents & 0x01 != 0 {
        let _clone_id = read_u32(cursor)?;
        let _clone_player_id = read_u32(cursor)?;
    }
    Ok(())
}

/// VariableLengthRead — reads u8, u16, or u32 depending on `size`.
/// C++ ref: plSDL::VariableLengthRead
fn variable_length_read(cursor: &mut Cursor<&[u8]>, size: usize) -> Result<usize> {
    if size < 256 {
        Ok(read_u8(cursor)? as usize)
    } else if size < 65536 {
        Ok(read_u16(cursor)? as usize)
    } else {
        Ok(read_u32(cursor)? as usize)
    }
}

/// Get the atomic count for a type (how many atomic values per element).
/// C++ ref: plSimpleVarDescriptor::SetType
fn get_atomic_count(var_type: SdlType) -> usize {
    match var_type {
        SdlType::Vector3 | SdlType::Point3 | SdlType::Rgb | SdlType::Rgb8 => 3,
        SdlType::Rgba | SdlType::Quaternion => 4,
        _ => 1,
    }
}

/// Get the atomic type for a compound type.
fn get_atomic_type(var_type: SdlType) -> SdlType {
    match var_type {
        SdlType::Vector3 | SdlType::Point3 | SdlType::Rgb | SdlType::Rgba
        | SdlType::Quaternion => SdlType::Float,
        SdlType::Rgb8 => SdlType::Byte,
        _ => var_type,
    }
}

/// Read atomic values for one element of a variable.
/// C++ ref: plSimpleStateVariable::IReadData
fn read_atomic_values(cursor: &mut Cursor<&[u8]>, var_type: SdlType, atomic_count: usize) -> Result<Vec<SdlAtomicValue>> {
    let atomic_type = get_atomic_type(var_type);
    let mut values = Vec::with_capacity(atomic_count);

    match atomic_type {
        SdlType::AgeTimeOfDay => {
            // No data read — computed on the fly
            values.push(SdlAtomicValue::AgeTimeOfDay);
        }
        SdlType::Int => {
            for _ in 0..atomic_count {
                values.push(SdlAtomicValue::Int(read_i32(cursor)?));
            }
        }
        SdlType::Short => {
            for _ in 0..atomic_count {
                values.push(SdlAtomicValue::Short(read_i16(cursor)?));
            }
        }
        SdlType::Byte => {
            for _ in 0..atomic_count {
                values.push(SdlAtomicValue::Byte(read_u8(cursor)?));
            }
        }
        SdlType::Float => {
            for _ in 0..atomic_count {
                values.push(SdlAtomicValue::Float(read_f32(cursor)?));
            }
        }
        SdlType::Double => {
            for _ in 0..atomic_count {
                values.push(SdlAtomicValue::Double(read_f64(cursor)?));
            }
        }
        SdlType::Bool => {
            for _ in 0..atomic_count {
                values.push(SdlAtomicValue::Bool(read_u8(cursor)? != 0));
            }
        }
        SdlType::Time => {
            for _ in 0..atomic_count {
                let secs = read_u32(cursor)?;
                let micros = read_u32(cursor)?;
                values.push(SdlAtomicValue::Time { secs, micros });
            }
        }
        SdlType::Key => {
            for _ in 0..atomic_count {
                let start = cursor.position() as usize;
                skip_uoid(cursor)?;
                let end = cursor.position() as usize;
                let data = cursor.get_ref()[start..end].to_vec();
                values.push(SdlAtomicValue::Key(data));
            }
        }
        SdlType::String32 => {
            for _ in 0..atomic_count {
                let mut buf = [0u8; 32];
                cursor.read_exact(&mut buf)?;
                let s = std::str::from_utf8(&buf)
                    .unwrap_or("")
                    .trim_end_matches('\0')
                    .to_string();
                values.push(SdlAtomicValue::String(s));
            }
        }
        SdlType::Creatable => {
            // Only 1 atomic per creatable
            let class_index = read_u16(cursor)?;
            if class_index != 0x8000 {
                let len = read_u32(cursor)? as usize;
                let mut data = vec![0u8; len];
                cursor.read_exact(&mut data)?;
                values.push(SdlAtomicValue::Creatable { class_index, data });
            }
        }
        SdlType::Matrix44 => {
            // 16 floats = 64 bytes, stored as float atomic
            for _ in 0..16 {
                values.push(SdlAtomicValue::Float(read_f32(cursor)?));
            }
        }
        _ => {
            bail!("Unsupported SDL atomic type: {:?}", atomic_type);
        }
    }

    Ok(values)
}

// ---- Primitive readers ----

fn read_u8(cursor: &mut Cursor<&[u8]>) -> Result<u8> {
    let mut buf = [0u8; 1];
    cursor.read_exact(&mut buf)?;
    Ok(buf[0])
}

fn read_u16(cursor: &mut Cursor<&[u8]>) -> Result<u16> {
    let mut buf = [0u8; 2];
    cursor.read_exact(&mut buf)?;
    Ok(u16::from_le_bytes(buf))
}

fn read_u32(cursor: &mut Cursor<&[u8]>) -> Result<u32> {
    let mut buf = [0u8; 4];
    cursor.read_exact(&mut buf)?;
    Ok(u32::from_le_bytes(buf))
}

fn read_i32(cursor: &mut Cursor<&[u8]>) -> Result<i32> {
    let mut buf = [0u8; 4];
    cursor.read_exact(&mut buf)?;
    Ok(i32::from_le_bytes(buf))
}

fn read_i16(cursor: &mut Cursor<&[u8]>) -> Result<i16> {
    let mut buf = [0u8; 2];
    cursor.read_exact(&mut buf)?;
    Ok(i16::from_le_bytes(buf))
}

fn read_f32(cursor: &mut Cursor<&[u8]>) -> Result<f32> {
    let mut buf = [0u8; 4];
    cursor.read_exact(&mut buf)?;
    Ok(f32::from_le_bytes(buf))
}

fn read_f64(cursor: &mut Cursor<&[u8]>) -> Result<f64> {
    let mut buf = [0u8; 8];
    cursor.read_exact(&mut buf)?;
    Ok(f64::from_le_bytes(buf))
}

/// Write an SDL record to bytes (StreamHeader + StateDataRecord).
/// Used for sending SDL state back to the server.
pub fn write_sdl_record(record: &SdlRecord, desc: Option<&StateDescriptor>) -> Vec<u8> {
    let mut buf = Vec::with_capacity(256);

    // 1. Stream header
    let sav_flags: u16 = sdl_flags::ADDED_VAR_LENGTH_IO;
    buf.extend_from_slice(&sav_flags.to_le_bytes());
    write_safe_string(&mut buf, &record.descriptor_name);
    buf.extend_from_slice(&record.descriptor_version.to_le_bytes());

    // 2. StateDataRecord body
    buf.extend_from_slice(&record.flags.to_le_bytes());
    buf.push(IO_VERSION);

    let total_vars = desc.map(|d| d.variables.len()).unwrap_or(256);

    // Simple vars
    let num_simple = record.variables.len();
    variable_length_write(&mut buf, total_vars, num_simple);
    // Write all = (num == total simple vars in desc)
    let simple_count_in_desc = desc.map(|d| {
        d.variables.iter().filter(|v| v.var_type != SdlType::StateDescriptor).count()
    }).unwrap_or(0);
    let all_simple = num_simple == simple_count_in_desc;

    for (i, var) in record.variables.iter().enumerate() {
        if !all_simple {
            variable_length_write(&mut buf, total_vars, i);
        }
        write_simple_var(&mut buf, var);
    }

    // SD vars
    let num_sd = record.sd_variables.len();
    variable_length_write(&mut buf, total_vars, num_sd);
    // For now, we skip writing nested SD vars (uncommon in practice)

    buf
}

fn write_safe_string(buf: &mut Vec<u8>, s: &str) {
    let bytes = s.as_bytes();
    let len_with_flag = (bytes.len() as u16) | 0xF000;
    buf.extend_from_slice(&len_with_flag.to_le_bytes());
    for &b in bytes {
        buf.push(!b);
    }
}

fn variable_length_write(buf: &mut Vec<u8>, size: usize, val: usize) {
    if size < 256 {
        buf.push(val as u8);
    } else if size < 65536 {
        buf.extend_from_slice(&(val as u16).to_le_bytes());
    } else {
        buf.extend_from_slice(&(val as u32).to_le_bytes());
    }
}

fn write_simple_var(buf: &mut Vec<u8>, var: &SdlVarValue) {
    // Base class: no notification info
    buf.push(0);

    // Save flags
    let mut save_flags: u8 = 0;
    if var.is_dirty { save_flags |= sdl_flags::HAS_DIRTY_FLAG as u8; }
    if var.same_as_default { save_flags |= sdl_flags::SAME_AS_DEFAULT as u8; }
    if var.has_timestamp { save_flags |= sdl_flags::HAS_TIMESTAMP as u8; }
    buf.push(save_flags);

    if var.has_timestamp {
        buf.extend_from_slice(&var.timestamp_secs.to_le_bytes());
        buf.extend_from_slice(&var.timestamp_micros.to_le_bytes());
    }

    if !var.same_as_default {
        for val in &var.values {
            write_atomic_value(buf, val);
        }
    }
}

fn write_atomic_value(buf: &mut Vec<u8>, val: &SdlAtomicValue) {
    match val {
        SdlAtomicValue::Int(v) => buf.extend_from_slice(&v.to_le_bytes()),
        SdlAtomicValue::Float(v) => buf.extend_from_slice(&v.to_le_bytes()),
        SdlAtomicValue::Bool(v) => buf.push(*v as u8),
        SdlAtomicValue::Double(v) => buf.extend_from_slice(&v.to_le_bytes()),
        SdlAtomicValue::Byte(v) => buf.push(*v),
        SdlAtomicValue::Short(v) => buf.extend_from_slice(&v.to_le_bytes()),
        SdlAtomicValue::Time { secs, micros } => {
            buf.extend_from_slice(&secs.to_le_bytes());
            buf.extend_from_slice(&micros.to_le_bytes());
        }
        SdlAtomicValue::String(s) => {
            let mut fixed = [0u8; 32];
            let bytes = s.as_bytes();
            let len = bytes.len().min(31);
            fixed[..len].copy_from_slice(&bytes[..len]);
            buf.extend_from_slice(&fixed);
        }
        SdlAtomicValue::Key(data) => buf.extend_from_slice(data),
        SdlAtomicValue::Creatable { class_index, data } => {
            buf.extend_from_slice(&class_index.to_le_bytes());
            buf.extend_from_slice(&(data.len() as u32).to_le_bytes());
            buf.extend_from_slice(data);
        }
        SdlAtomicValue::AgeTimeOfDay => {} // no data
    }
}

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

    /// Build a minimal SDL stream for testing: header + record with one bool var.
    fn build_test_sdl_stream(name: &str, version: u16, var_value: bool) -> Vec<u8> {
        let mut buf = Vec::new();

        // Stream header
        let sav_flags: u16 = sdl_flags::ADDED_VAR_LENGTH_IO;
        buf.extend_from_slice(&sav_flags.to_le_bytes());

        // SafeString: name
        let name_bytes = name.as_bytes();
        let len_with_flag = (name_bytes.len() as u16) | 0xF000;
        buf.extend_from_slice(&len_with_flag.to_le_bytes());
        for &b in name_bytes {
            buf.push(!b); // XOR with 0xFF
        }

        // Version
        buf.extend_from_slice(&version.to_le_bytes());

        // plStateDataRecord::Write
        let rec_flags: u16 = 0; // no kVolatile
        buf.extend_from_slice(&rec_flags.to_le_bytes());
        buf.push(IO_VERSION);

        // Num simple vars = 1 (total vars in descriptor < 256, so u8)
        buf.push(1);
        // Since num != total_in_desc, we need to write index too
        // But we write "all" = (num == simple_descs.len()), which is 1 == 1 = true
        // So no index needed

        // plSimpleStateVariable::WriteData
        // Base class saveFlags (no notification info)
        buf.push(0);
        // Simple var saveFlags (not same as default, no timestamp, has dirty flag)
        buf.push(sdl_flags::HAS_DIRTY_FLAG as u8);
        // Data: bool
        buf.push(var_value as u8);

        // Num SD vars = 0
        buf.push(0);

        buf
    }

    #[test]
    fn test_read_safe_string() {
        // Build a safe string for "Cleft"
        let name = "Cleft";
        let mut buf = Vec::new();
        let len_with_flag = (name.len() as u16) | 0xF000;
        buf.extend_from_slice(&len_with_flag.to_le_bytes());
        for &b in name.as_bytes() {
            buf.push(!b);
        }

        let mut cursor = Cursor::new(buf.as_slice());
        let result = read_safe_string(&mut cursor).unwrap();
        assert_eq!(result, "Cleft");
    }

    #[test]
    fn test_variable_length_read() {
        // size < 256: reads u8
        let data = [42u8];
        let mut cursor = Cursor::new(data.as_slice());
        assert_eq!(variable_length_read(&mut cursor, 100).unwrap(), 42);

        // size < 65536: reads u16
        let data = 300u16.to_le_bytes();
        let mut cursor = Cursor::new(data.as_slice());
        assert_eq!(variable_length_read(&mut cursor, 500).unwrap(), 300);

        // size >= 65536: reads u32
        let data = 70000u32.to_le_bytes();
        let mut cursor = Cursor::new(data.as_slice());
        assert_eq!(variable_length_read(&mut cursor, 100_000).unwrap(), 70000);
    }

    #[test]
    fn test_parse_minimal_sdl() {
        // Create a descriptor with one bool variable
        let mut mgr = SdlManager::new();
        let content = "STATEDESC TestSDL\n{\nVERSION 1\nVAR BOOL testVar[1] DEFAULT=0\n}\n";
        let descs = super::super::descriptor::parse_sdl_for_test(content).unwrap();
        for d in descs {
            mgr.add_descriptor(d);
        }

        let stream = build_test_sdl_stream("TestSDL", 1, true);
        let record = parse_sdl_record(&stream, &mgr).unwrap();

        assert_eq!(record.descriptor_name, "TestSDL");
        assert_eq!(record.descriptor_version, 1);
        assert_eq!(record.variables.len(), 1);
        assert_eq!(record.variables[0].name, "testVar");
        assert!(record.variables[0].is_dirty);
        assert!(!record.variables[0].same_as_default);
        assert_eq!(record.variables[0].values.len(), 1);
        assert!(matches!(record.variables[0].values[0], SdlAtomicValue::Bool(true)));
    }

    #[test]
    fn test_write_read_roundtrip() {
        let mut mgr = SdlManager::new();
        let content = "STATEDESC RoundTrip\n{\nVERSION 2\nVAR INT myInt[1] DEFAULT=0\nVAR BOOL myBool[1] DEFAULT=0\n}\n";
        let descs = super::super::descriptor::parse_sdl_for_test(content).unwrap();
        for d in descs {
            mgr.add_descriptor(d);
        }

        let record = SdlRecord {
            descriptor_name: "RoundTrip".to_string(),
            descriptor_version: 2,
            flags: 0,
            variables: vec![
                SdlVarValue {
                    name: "myInt".to_string(),
                    var_type: SdlType::Int,
                    is_dirty: true,
                    has_timestamp: false,
                    timestamp_secs: 0,
                    timestamp_micros: 0,
                    same_as_default: false,
                    values: vec![SdlAtomicValue::Int(42)],
                },
                SdlVarValue {
                    name: "myBool".to_string(),
                    var_type: SdlType::Bool,
                    is_dirty: true,
                    has_timestamp: false,
                    timestamp_secs: 0,
                    timestamp_micros: 0,
                    same_as_default: false,
                    values: vec![SdlAtomicValue::Bool(true)],
                },
            ],
            sd_variables: vec![],
        };

        let desc = mgr.find("RoundTrip", 2).unwrap();
        let bytes = write_sdl_record(&record, Some(desc));
        let parsed = parse_sdl_record(&bytes, &mgr).unwrap();

        assert_eq!(parsed.descriptor_name, "RoundTrip");
        assert_eq!(parsed.descriptor_version, 2);
        assert_eq!(parsed.variables.len(), 2);
        assert!(matches!(parsed.variables[0].values[0], SdlAtomicValue::Int(42)));
        assert!(matches!(parsed.variables[1].values[0], SdlAtomicValue::Bool(true)));
    }

    #[test]
    fn test_stream_header_roundtrip() {
        let mut buf = Vec::new();

        // Write header
        let sav_flags: u16 = sdl_flags::ADDED_VAR_LENGTH_IO;
        buf.extend_from_slice(&sav_flags.to_le_bytes());
        let name = "Neighborhood";
        let len_with_flag = (name.len() as u16) | 0xF000;
        buf.extend_from_slice(&len_with_flag.to_le_bytes());
        for &b in name.as_bytes() {
            buf.push(!b);
        }
        buf.extend_from_slice(&42u16.to_le_bytes()); // version

        let mut cursor = Cursor::new(buf.as_slice());
        let (parsed_name, parsed_version) = read_stream_header(&mut cursor).unwrap();
        assert_eq!(parsed_name, "Neighborhood");
        assert_eq!(parsed_version, 42);
    }
}