Skip to main content

runec/
writer.rs

1use std::collections::HashMap;
2use std::fs;
3use std::io;
4use std::path::Path;
5
6use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
7use crate::opcodes::is_large_operand;
8use crate::types::Type;
9
10// ── CS2 Neptune binary format constants ────────────────────────────────────
11
12/// Compiler version written into the script.dat header.
13const COMPILER_VERSION: i32 = 27;
14
15/// Map a `Type` to its CS2 type-char byte (as used in ScriptVarType.ts).
16fn type_to_char(t: Type) -> u8 {
17    match t {
18        Type::Int => b'i',
19        Type::String => b's',
20        Type::Boolean => b'1',
21        Type::Coord => b'c',
22        Type::Loc => b'l',
23        Type::Npc => b'n',
24        Type::Obj => b'o',
25        Type::NamedObj => b'O',
26        Type::PlayerUid => b'p',
27        Type::NpcUid => b'u',
28        Type::Seq => b'A',
29        Type::Spotanim => b't',
30        Type::Synth => b'P',
31        Type::Stat => b'S',
32        Type::Component => b'I',
33        Type::Interface | Type::TopLevelInterface | Type::OverlayInterface => b'a',
34        Type::Inv => b'v',
35        Type::Enum => b'g',
36        Type::Struct => b'J',
37        Type::DbRow => 0xD0, // 'Ð' = 208
38        Type::Category => b'y',
39        Type::Varp => b'V',
40        Type::NpcStat => 0xFE, // 'þ' = 254
41        Type::IdKit => b'K',
42        _ => b'i', // default to int for unknown/unrepresented types
43    }
44}
45
46/// Encode a Rust string to RS2 single-byte encoding.
47/// Maps Unicode characters to their RuneScript byte equivalents.
48/// The RuneScript format uses the low byte of certain Unicode code points:
49/// U+2019 (') → 0x19, U+2013 (–) → 0x13, etc.
50fn encode_rs2_string(s: &str) -> Vec<u8> {
51    let mut out = Vec::with_capacity(s.len());
52    for ch in s.chars() {
53        let cp = ch as u32;
54        if cp < 0x80 {
55            out.push(cp as u8);
56        } else if cp < 0x100 {
57            // Latin-1 supplement: pass through as-is
58            out.push(cp as u8);
59        } else if (0x2010..=0x201F).contains(&cp) {
60            // Typographic punctuation: use low byte
61            // U+2013 (–) → 0x13, U+2014 (—) → 0x14
62            // U+2018 (') → 0x18, U+2019 (') → 0x19
63            // U+201C (") → 0x1C, U+201D (") → 0x1D
64            out.push((cp & 0xFF) as u8);
65        } else {
66            // Other Unicode: use low byte as fallback
67            out.push((cp & 0xFF) as u8);
68        }
69    }
70    out
71}
72
73// ── Script binary encoder ───────────────────────────────────────────────────
74
75/// Encode a single compiled script to the CS2 Neptune binary format.
76///
77/// Layout:
78/// ```text
79///   [header]  scriptName\0 + sourceFilePath\0 + lookupKey(i32) +
80///             paramTypeCount(u8) + paramTypes(u8[]) +
81///             lineTableLen(u16) + lineTable(pc+line pairs)
82///   [instrs]  per-instruction: opcode(u16) + operand (variable)
83///   [trailer] _instructions(i32) + intLocals(u16) + strLocals(u16) +
84///             intArgs(u16) + strArgs(u16) + switches(u8) + tables...
85///   [last2]   trailerLen(u16)
86/// ```
87pub fn encode_script(script: &CompiledScript) -> Vec<u8> {
88    if script.instructions.iter().any(|instruction| {
89        matches!(
90            instruction.opcode,
91            Opcode::BranchIfTrue | Opcode::BranchIfFalse
92        )
93    }) {
94        let mut lowered = script.clone();
95        let mut positions = Vec::with_capacity(script.instructions.len() + 1);
96        lowered.instructions.clear();
97        for instruction in &script.instructions {
98            positions.push(lowered.instructions.len());
99            if matches!(
100                instruction.opcode,
101                Opcode::BranchIfTrue | Opcode::BranchIfFalse
102            ) {
103                lowered.instructions.push(Instruction::push_int(i32::from(
104                    instruction.opcode == Opcode::BranchIfTrue,
105                )));
106                lowered.instructions.push(Instruction::new(
107                    Opcode::BranchEquals,
108                    instruction.operand.clone(),
109                ));
110            } else {
111                lowered.instructions.push(instruction.clone());
112            }
113        }
114        positions.push(lowered.instructions.len());
115        for instruction in &mut lowered.instructions {
116            if let Operand::JumpTarget(target) = &mut instruction.operand {
117                *target = positions[*target];
118            }
119        }
120        for table in &mut lowered.switch_tables {
121            for (_, target) in table.iter_mut() {
122                *target = positions[*target];
123            }
124        }
125        return encode_script(&lowered);
126    }
127    // ── collect switch tables and assign indices ────────────────────────────
128    // We scan instructions for SwitchTable operands, extract them, and
129    // replace their operands with the table index.
130    let mut switch_tables: Vec<Vec<(i32, i32)>> = Vec::new(); // (key, relative_offset)
131    // We'll build the final instruction list with resolved operands.
132    // Each entry: (effective_opcode: u16, resolved_operand)
133    enum ResolvedOp {
134        None,
135        Small(u8),
136        Large(i32),
137        Str(Box<str>),
138    }
139    struct FlatInstr {
140        opcode: u16,
141        op: ResolvedOp,
142    }
143
144    // First pass: build flat instruction list, collect switch tables.
145    // Jump targets are stored as absolute indices in Operand::JumpTarget;
146    // we convert them to relative offsets later.
147    let n = script.instructions.len();
148    let mut flat: Vec<FlatInstr> = Vec::with_capacity(n);
149    let mut switch_tbl_idxs: Vec<Option<usize>> = Vec::new(); // per-instruction switch table idx
150    // Line number table: (flat_idx_of_sentinel, line_number)
151    // After orig_to_final is built, flat_idx resolves to the PC of the next real instruction.
152    let mut raw_line_entries: Vec<(usize, i32)> = Vec::new();
153
154    for instr in &script.instructions {
155        // For Command instructions, the "real" opcode is stored in the operand;
156        // we extract it here and will write 0 as the operand value.
157        let is_command = instr.opcode == Opcode::Command;
158
159        // For Command instructions, the actual engine opcode is stored in the
160        // lower 16 bits of the Int operand, and the small operand byte (0 or 1
161        // for primary/secondary active-entity selection) is stored in bits 16-23.
162        let mut cmd_small_operand: u8 = 0;
163        let eff_opcode: u16 = match instr.opcode {
164            Opcode::Command => {
165                match &instr.operand {
166                    Operand::Int(v) => {
167                        cmd_small_operand = ((*v >> 16) & 0xFF) as u8;
168                        (*v & 0xFFFF) as u16
169                    }
170                    Operand::Str(idx) => {
171                        // Unknown command referenced by name – skip with 0
172                        let _ = idx;
173                        0
174                    }
175                    _ => 0,
176                }
177            }
178            Opcode::LineNumber => {
179                // Metadata – record line number and skip (add sentinel to filter).
180                let line = match &instr.operand {
181                    Operand::Int(v) => *v,
182                    _ => 0,
183                };
184                raw_line_entries.push((flat.len(), line));
185                switch_tbl_idxs.push(None);
186                flat.push(FlatInstr {
187                    opcode: 0xFFFF,
188                    op: ResolvedOp::None,
189                }); // sentinel to remove
190                continue;
191            }
192            op => op as u16,
193        };
194
195        // Command instructions: the operand byte encodes which active entity
196        // to use (0 = primary, 1 = secondary/dot-prefix form).
197        if is_command {
198            switch_tbl_idxs.push(None);
199            flat.push(FlatInstr {
200                opcode: eff_opcode,
201                op: ResolvedOp::Small(cmd_small_operand),
202            });
203            continue;
204        }
205
206        let resolved = match &instr.operand {
207            Operand::None => {
208                // No-operand instructions still need a byte written (0) if small.
209                if is_large_operand(eff_opcode) {
210                    ResolvedOp::Large(0)
211                } else {
212                    ResolvedOp::Small(0)
213                }
214            }
215            Operand::Int(v) => {
216                if eff_opcode == 3 {
217                    // PUSH_CONSTANT_STRING uses string operand; Int is a fallback
218                    ResolvedOp::Large(*v)
219                } else if is_large_operand(eff_opcode) {
220                    ResolvedOp::Large(*v)
221                } else {
222                    ResolvedOp::Small(*v as u8)
223                }
224            }
225            Operand::Long(v) => {
226                // Long literal: 4-byte high + 4-byte low encoded as two push instructions.
227                // For now, emit high 32-bits (this is rarely used in 2004scape).
228                ResolvedOp::Large(*v as i32)
229            }
230            Operand::Str(idx) => ResolvedOp::Str(script.strings[*idx as usize].clone()),
231            Operand::JumpTarget(target) => {
232                // Will be resolved to relative offset in second pass.
233                ResolvedOp::Large(*target as i32) // placeholder – absolute index
234            }
235            Operand::SwitchTable(idx) => {
236                // The table lives in the script's pool; the operand is its index.
237                let table = &script.switch_tables[*idx as usize];
238                // Assign a table index and store the table.
239                let tbl_idx = switch_tables.len();
240                // We'll fill in relative offsets in the second pass.
241                // For now, store the table with absolute targets.
242                let raw: Vec<(i32, i32)> = table
243                    .iter()
244                    .map(|(k, abs_target)| (*k, *abs_target as i32))
245                    .collect();
246                switch_tables.push(raw);
247                switch_tbl_idxs.push(Some(tbl_idx));
248                flat.push(FlatInstr {
249                    opcode: eff_opcode,
250                    op: ResolvedOp::Large(tbl_idx as i32),
251                });
252                continue;
253            }
254            Operand::StringCount(c) => {
255                if is_large_operand(eff_opcode) {
256                    ResolvedOp::Large(*c as i32)
257                } else {
258                    ResolvedOp::Small(*c as u8)
259                }
260            }
261            Operand::ArrayDef(var_id, type_char) => {
262                let packed = (*var_id << 16) | (*type_char as i32);
263                if is_large_operand(eff_opcode) {
264                    ResolvedOp::Large(packed)
265                } else {
266                    ResolvedOp::Small(packed as u8)
267                }
268            }
269        };
270
271        switch_tbl_idxs.push(None);
272        flat.push(FlatInstr {
273            opcode: eff_opcode,
274            op: resolved,
275        });
276    }
277
278    // Remove LineNumber sentinel instructions and keep track of index mapping.
279    // Build final instruction vector (without LineNumber instructions).
280    let mut final_instrs: Vec<FlatInstr> = Vec::new();
281    // Map from original index to final index (for resolving jump targets).
282    let mut orig_to_final: Vec<usize> = Vec::new(); // orig_to_final[orig] = final
283    for (i, fi) in flat.into_iter().enumerate() {
284        let _ = i;
285        if fi.opcode == 0xFFFF {
286            // LineNumber sentinel
287            orig_to_final.push(final_instrs.len()); // point to next valid instr
288        } else {
289            orig_to_final.push(final_instrs.len());
290            final_instrs.push(fi);
291        }
292    }
293    // Add sentinel for "one past end"
294    let total = final_instrs.len();
295
296    // Resolve raw_line_entries to (pc, line) pairs using orig_to_final.
297    // Deduplicate: if multiple LineNumber entries map to the same PC, keep the last one.
298    let mut line_table: Vec<(i32, i32)> = Vec::new();
299    for (flat_idx, line) in &raw_line_entries {
300        let pc = if *flat_idx < orig_to_final.len() {
301            orig_to_final[*flat_idx] as i32
302        } else {
303            total as i32
304        };
305        // Deduplicate: skip if same PC (keep last line for that PC) or same line as previous.
306        if let Some(last) = line_table.last_mut() {
307            if last.0 == pc {
308                last.1 = *line;
309                continue;
310            }
311            if last.1 == *line {
312                // Same line number as previous entry — Java compiler skips this.
313                continue;
314            }
315        }
316        line_table.push((pc, *line));
317    }
318
319    // Second pass: convert absolute jump targets to relative offsets.
320    // Relative offset = target_final_idx - (current_final_idx + 1).
321    for (i, fi) in final_instrs.iter_mut().enumerate() {
322        if let ResolvedOp::Large(v) = &fi.op {
323            // Check if this is a branch opcode (jump target stored as absolute idx)
324            let is_branch = matches!(
325                fi.opcode,
326                6 | 7 | 8 | 9 | 10 | 31 | 32 | 68 | 69 | 70 | 71 | 72 | 73 | 86 | 87
327            );
328            if is_branch {
329                let abs_target = *v as usize;
330                let final_target = if abs_target < orig_to_final.len() {
331                    orig_to_final[abs_target]
332                } else {
333                    total // out of bounds → point to end
334                };
335                let relative = final_target as i32 - (i as i32 + 1);
336                fi.op = ResolvedOp::Large(relative);
337            }
338        }
339    }
340
341    // Convert switch table targets to relative offsets.
342    // The switch instruction is at some index `sw_idx`; each case body has an
343    // absolute target. offset = target - (sw_idx + 1).
344    // We need to find where each switch instruction is in the final list to
345    // compute relative offsets.
346    // Re-scan original instructions to find switch instruction positions.
347    let mut sw_instr_positions: HashMap<usize, usize> = HashMap::new(); // tbl_idx -> final_pos
348    {
349        for (orig_idx, orig_instr) in script.instructions.iter().enumerate() {
350            if orig_idx >= orig_to_final.len() {
351                break;
352            }
353            if orig_instr.opcode == Opcode::LineNumber {
354                continue;
355            }
356            let final_pos = orig_to_final[orig_idx];
357            if let Operand::SwitchTable(_) = &orig_instr.operand {
358                // Use orig_idx to correctly index switch_tbl_idxs (which is populated
359                // in parallel with script.instructions, including LineNumber entries).
360                if let Some(tbl_idx) = switch_tbl_idxs.get(orig_idx).and_then(|x| *x) {
361                    sw_instr_positions.insert(tbl_idx, final_pos);
362                }
363            }
364        }
365    }
366
367    // Build relative-offset switch tables.
368    let switch_tables_relative: Vec<Vec<(i32, i32)>> = switch_tables
369        .iter()
370        .enumerate()
371        .map(|(tbl_idx, table)| {
372            let sw_pos = *sw_instr_positions.get(&tbl_idx).unwrap_or(&0);
373            table
374                .iter()
375                .map(|(key, abs_target)| {
376                    let final_target = if (*abs_target as usize) < orig_to_final.len() {
377                        orig_to_final[*abs_target as usize]
378                    } else {
379                        total
380                    };
381                    let rel = final_target as i32 - (sw_pos as i32 + 1);
382                    (*key, rel)
383                })
384                .collect()
385        })
386        .collect();
387
388    // ── build the binary buffer ────────────────────────────────────────────
389    let mut buf: Vec<u8> = Vec::new();
390
391    // Header: scriptName\0
392    buf.extend_from_slice(script.name.as_bytes());
393    buf.push(0);
394
395    // sourceFilePath\0
396    buf.extend_from_slice(script.source_path.as_bytes());
397    buf.push(0);
398
399    // lookupKey: -1 for non-entity scripts, or hash-based key for entity scripts
400    buf.extend_from_slice(&script.lookup_key.to_be_bytes());
401
402    // parameterTypeCount + parameterTypes
403    // The Java compiler only writes param types for debugproc scripts;
404    // all other triggers write 0 here.
405    if script.trigger == "debugproc" {
406        buf.push(script.param_types.len() as u8);
407        for &pt in &script.param_types {
408            buf.push(type_to_char(pt));
409        }
410    } else {
411        buf.push(0);
412    }
413
414    // lineNumberTableLength = count of (pc, line) entries
415    buf.extend_from_slice(&(line_table.len() as u16).to_be_bytes());
416    for (pc, line) in &line_table {
417        buf.extend_from_slice(&pc.to_be_bytes());
418        buf.extend_from_slice(&line.to_be_bytes());
419    }
420
421    // ── instructions ──────────────────────────────────────────────────────
422    for fi in &final_instrs {
423        buf.extend_from_slice(&fi.opcode.to_be_bytes());
424        match &fi.op {
425            ResolvedOp::None => {}
426            ResolvedOp::Small(v) => {
427                buf.push(*v);
428            }
429            ResolvedOp::Large(v) => {
430                buf.extend_from_slice(&v.to_be_bytes());
431            }
432            ResolvedOp::Str(s) => {
433                buf.extend(encode_rs2_string(s));
434                buf.push(0); // null terminator
435            }
436        }
437    }
438
439    // ── trailer ───────────────────────────────────────────────────────────
440    let trailer_start = buf.len();
441
442    // _instructions (instruction count)
443    buf.extend_from_slice(&(final_instrs.len() as i32).to_be_bytes());
444
445    // intLocalCount, stringLocalCount
446    buf.extend_from_slice(&script.int_local_count.to_be_bytes());
447    buf.extend_from_slice(&script.string_local_count.to_be_bytes());
448
449    // intArgCount, stringArgCount
450    buf.extend_from_slice(&script.int_arg_count.to_be_bytes());
451    buf.extend_from_slice(&script.string_arg_count.to_be_bytes());
452
453    // switches byte + switch tables
454    buf.push(switch_tables_relative.len() as u8);
455    for table in &switch_tables_relative {
456        buf.extend_from_slice(&(table.len() as u16).to_be_bytes());
457        for (key, offset) in table {
458            buf.extend_from_slice(&key.to_be_bytes());
459            buf.extend_from_slice(&offset.to_be_bytes());
460        }
461    }
462
463    // trailerLen = switch count byte + switch table data (matching TS: switchOffset + 1)
464    let switch_section_len = buf.len() - trailer_start - 12; // 12 = instrs(4) + locals/params(8)
465    buf.extend_from_slice(&(switch_section_len as u16).to_be_bytes());
466
467    buf
468}
469
470// ── PackedWriter: writes script.dat + script.idx ───────────────────────────
471
472/// Encode the server container without accessing storage. Each entry is a
473/// script ID slot; supply an empty vector for missing IDs.
474pub fn encode_bundle(encoded: &[Vec<u8>]) -> (Vec<u8>, Vec<u8>) {
475    let slot_count = encoded.len();
476
477    let mut dat: Vec<u8> = Vec::new();
478    dat.extend_from_slice(&(slot_count as u32).to_be_bytes());
479    dat.extend_from_slice(&COMPILER_VERSION.to_be_bytes());
480    for bytes in encoded {
481        dat.extend_from_slice(bytes);
482    }
483
484    let mut idx: Vec<u8> = Vec::new();
485    idx.extend_from_slice(&(slot_count as u32).to_be_bytes());
486    for bytes in encoded {
487        idx.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
488    }
489
490    (dat, idx)
491}
492
493/// Writes compiled scripts to script.dat and script.idx in the output directory.
494pub struct ScriptWriter {
495    output_dir: String,
496}
497
498impl ScriptWriter {
499    pub fn new(output_dir: String) -> Self {
500        ScriptWriter { output_dir }
501    }
502
503    /// Write all compiled scripts to script.dat and script.idx.
504    ///
505    /// File layout is **sparse by script.id**: the idx has one entry per
506    /// slot from 0..max_id; slots without a compiled script write length
507    /// 0 and contribute no bytes to the dat. The loader (`rs-engine`)
508    /// mirrors this — empty-length slots become no-op Script stubs so
509    /// the script at array-index N matches compile-time id N.
510    ///
511    /// Packing contiguously (old behaviour) misaligned runtime array
512    /// indices with compile-time ids, so bytecode `GOSUB 2405` (intended
513    /// `chatnpc_page`) resolved to `chatnpc` at runtime — infinite
514    /// recursion.
515    pub fn write_all(&self, scripts: &[CompiledScript]) -> io::Result<()> {
516        fs::create_dir_all(&self.output_dir)?;
517
518        // Max id determines the sparse slot count. Scripts with id < 0
519        // are stray (unresolved) and would collide at slot 0 — drop them
520        // explicitly rather than let them mask a valid id.
521        let max_id = scripts.iter().map(|s| s.id).max().unwrap_or(-1);
522        let slot_count = if max_id < 0 { 0 } else { (max_id + 1) as usize };
523
524        // Index scripts by id. Later writes at the same id overwrite
525        // earlier ones (matches Java compiler's last-wins behaviour when
526        // two declarations share an id — typically a compile-time bug,
527        // but we preserve the shape).
528        let mut by_id: Vec<Option<&CompiledScript>> = vec![None; slot_count];
529        for s in scripts {
530            if s.id >= 0 && (s.id as usize) < slot_count {
531                by_id[s.id as usize] = Some(s);
532            }
533        }
534
535        // Encode each occupied slot once. Empty slots emit zero bytes.
536        // Encoding is independent per slot, so fan it out across threads.
537        let encoded: Vec<Vec<u8>> =
538            crate::parallel_map(&by_id, |opt| opt.map(encode_script).unwrap_or_default());
539
540        self.write_encoded(&encoded)
541    }
542
543    /// Write `script.dat` + `script.idx` from pre-encoded per-slot byte blobs
544    /// (`encoded[slot]` is that script's bytes; empty for unused slots). Lets the
545    /// streaming recompile path produce output without ever holding the full
546    /// `Vec<CompiledScript>` — it encodes each script as it re-compiles, places
547    /// the bytes by id, then calls this. Byte-identical to `write_all`.
548    pub fn write_encoded(&self, encoded: &[Vec<u8>]) -> io::Result<()> {
549        fs::create_dir_all(&self.output_dir)?;
550        let slot_count = encoded.len();
551
552        let dat_path = Path::new(&self.output_dir).join("script.dat");
553        {
554            // Stream the dat to disk so we never hold a second full copy of the
555            // output (encoded blobs + a concatenated buffer). Byte-identical.
556            use std::io::Write;
557            let mut dat = io::BufWriter::new(fs::File::create(&dat_path)?);
558            dat.write_all(&(slot_count as u32).to_be_bytes())?;
559            dat.write_all(&COMPILER_VERSION.to_be_bytes())?;
560            for bytes in encoded {
561                dat.write_all(bytes)?;
562            }
563            dat.flush()?;
564        }
565
566        let idx_path = Path::new(&self.output_dir).join("script.idx");
567        {
568            let mut idx: Vec<u8> = Vec::new();
569            idx.extend_from_slice(&(slot_count as u32).to_be_bytes());
570            for bytes in encoded {
571                idx.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
572            }
573            fs::write(&idx_path, idx)?;
574        }
575
576        Ok(())
577    }
578
579    /// Build `script.dat` + `script.idx` bytes in memory from pre-encoded per-slot
580    /// blobs — the in-memory counterpart of [`ScriptWriter::write_encoded`], used
581    /// by the recompile pipeline's in-memory entry point. Uses the identical
582    /// header + sparse-by-id layout, so it is byte-for-byte equal to `build_all`
583    /// for the same scripts.
584    pub fn build_encoded(&self, encoded: &[Vec<u8>]) -> (Vec<u8>, Vec<u8>) {
585        encode_bundle(encoded)
586    }
587
588    pub fn build_all(&self, scripts: &[CompiledScript]) -> io::Result<(Vec<u8>, Vec<u8>)> {
589        // Max id determines the sparse slot count. Scripts with id < 0
590        // are stray (unresolved) and would collide at slot 0 — drop them
591        // explicitly rather than let them mask a valid id.
592        let max_id = scripts.iter().map(|s| s.id).max().unwrap_or(-1);
593        let slot_count = if max_id < 0 { 0 } else { (max_id + 1) as usize };
594
595        // Index scripts by id. Later writes at the same id overwrite
596        // earlier ones (matches Java compiler's last-wins behaviour when
597        // two declarations share an id — typically a compile-time bug,
598        // but we preserve the shape).
599        let mut by_id: Vec<Option<&CompiledScript>> = vec![None; slot_count];
600        for s in scripts {
601            if s.id >= 0 && (s.id as usize) < slot_count {
602                by_id[s.id as usize] = Some(s);
603            }
604        }
605
606        // Encode each occupied slot once. Empty slots emit zero bytes.
607        // Encoding is independent per slot, so fan it out across threads.
608        let encoded: Vec<Vec<u8>> =
609            crate::parallel_map(&by_id, |opt| opt.map(encode_script).unwrap_or_default());
610
611        let mut dat: Vec<u8> = Vec::new();
612        dat.extend_from_slice(&(slot_count as u32).to_be_bytes());
613        dat.extend_from_slice(&COMPILER_VERSION.to_be_bytes());
614        for bytes in &encoded {
615            dat.extend_from_slice(bytes);
616        }
617
618        let mut idx: Vec<u8> = Vec::new();
619        idx.extend_from_slice(&(slot_count as u32).to_be_bytes());
620        for bytes in &encoded {
621            idx.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
622        }
623
624        // // Build script.dat
625        // let dat_path = Path::new(&self.output_dir).join("script.dat");
626        // {
627        //     let mut dat: Vec<u8> = Vec::new();
628        //     // Header: count (u32) + version (i32)
629        //     dat.extend_from_slice(&(slot_count as u32).to_be_bytes());
630        //     dat.extend_from_slice(&COMPILER_VERSION.to_be_bytes());
631        //     for bytes in &encoded {
632        //         dat.extend_from_slice(bytes);
633        //     }
634        //     fs::write(&dat_path, dat)?;
635        // }
636        //
637        // // Build script.idx
638        // let idx_path = Path::new(&self.output_dir).join("script.idx");
639        // {
640        //     let mut idx: Vec<u8> = Vec::new();
641        //     idx.extend_from_slice(&(slot_count as u32).to_be_bytes());
642        //     for bytes in &encoded {
643        //         idx.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
644        //     }
645        //     fs::write(&idx_path, idx)?;
646        // }
647
648        Ok((dat, idx))
649    }
650}
651
652// ── PackBuffer (in-memory, for testing) ────────────────────────────────────
653
654pub struct PackBuffer {
655    pub scripts: HashMap<String, Vec<u8>>,
656}
657
658impl Default for PackBuffer {
659    fn default() -> Self {
660        Self::new()
661    }
662}
663
664impl PackBuffer {
665    pub fn new() -> Self {
666        PackBuffer {
667            scripts: HashMap::new(),
668        }
669    }
670
671    pub fn add_script(&mut self, script: &CompiledScript) {
672        let bytes = encode_script(script);
673        self.scripts.insert(script.name.clone(), bytes);
674    }
675}