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