Skip to main content

sheetkit_core/
vba.rs

1//! VBA project extraction from macro-enabled workbooks (.xlsm).
2//!
3//! `.xlsm` files contain a `xl/vbaProject.bin` entry which is an OLE2
4//! Compound Binary File (CFB) holding VBA source code. This module
5//! provides read-only access to the raw binary and to individual VBA
6//! module source code.
7
8use std::io::{Cursor, Read as _};
9
10use crate::error::{Error, Result};
11use crate::resource::{
12    ResourceCategory, ResourceDimension, ResourceLimitError, ResourceOperation, ResourceStage,
13};
14
15const MIB: u64 = 1024 * 1024;
16const MAX_WARNINGS: usize = 32;
17
18/// Finite limits applied to one VBA extraction operation.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct VbaLimits {
21    /// Maximum size of the input CFB container.
22    pub input_bytes: u64,
23    /// Maximum number of streams in the CFB container.
24    pub cfb_stream_count: u64,
25    /// Maximum size declared by one CFB stream.
26    pub cfb_stream_declared_bytes: u64,
27    /// Maximum sum of sizes declared by CFB streams.
28    pub cfb_aggregate_declared_bytes: u64,
29    /// Maximum bytes read from one CFB stream.
30    pub cfb_stream_read_bytes: u64,
31    /// Maximum cumulative bytes read from CFB streams.
32    pub cfb_aggregate_read_bytes: u64,
33    /// Maximum compressed bytes submitted to VBA decompression.
34    pub compressed_bytes: u64,
35    /// Maximum number of VBA modules.
36    pub module_count: u64,
37    /// Maximum number of compressed chunks processed.
38    pub chunk_count: u64,
39    /// Maximum decoded bytes produced by one module or the `dir` stream.
40    pub module_decoded_bytes: u64,
41    /// Maximum cumulative bytes produced by VBA decompression.
42    pub aggregate_decoded_bytes: u64,
43    /// Maximum bytes retained in names, source strings, and warnings.
44    pub retained_bytes: u64,
45    /// Maximum UTF-8 bytes returned in extracted module fields.
46    pub output_bytes: u64,
47}
48
49impl Default for VbaLimits {
50    fn default() -> Self {
51        Self {
52            input_bytes: 64 * MIB,
53            cfb_stream_count: 1_024,
54            cfb_stream_declared_bytes: 32 * MIB,
55            cfb_aggregate_declared_bytes: 64 * MIB,
56            cfb_stream_read_bytes: 32 * MIB,
57            cfb_aggregate_read_bytes: 64 * MIB,
58            compressed_bytes: 64 * MIB,
59            module_count: 1_024,
60            chunk_count: 65_536,
61            module_decoded_bytes: 16 * MIB,
62            aggregate_decoded_bytes: 64 * MIB,
63            retained_bytes: 64 * MIB,
64            output_bytes: 64 * MIB,
65        }
66    }
67}
68
69impl VbaLimits {
70    /// Largest supported finite values. These ceilings cannot be disabled.
71    pub const fn hard_ceiling() -> Self {
72        Self {
73            input_bytes: 1024 * MIB,
74            cfb_stream_count: 65_536,
75            cfb_stream_declared_bytes: 512 * MIB,
76            cfb_aggregate_declared_bytes: 1024 * MIB,
77            cfb_stream_read_bytes: 512 * MIB,
78            cfb_aggregate_read_bytes: 1024 * MIB,
79            compressed_bytes: 1024 * MIB,
80            module_count: 16_384,
81            chunk_count: 1_048_576,
82            module_decoded_bytes: 256 * MIB,
83            aggregate_decoded_bytes: 1024 * MIB,
84            retained_bytes: 1024 * MIB,
85            output_bytes: 1024 * MIB,
86        }
87    }
88
89    fn validate(self) -> Result<Self> {
90        let ceiling = Self::hard_ceiling();
91        for (dimension, value, maximum) in [
92            (
93                ResourceDimension::InputBytes,
94                self.input_bytes,
95                ceiling.input_bytes,
96            ),
97            (
98                ResourceDimension::StreamCount,
99                self.cfb_stream_count,
100                ceiling.cfb_stream_count,
101            ),
102            (
103                ResourceDimension::EntryDeclaredBytes,
104                self.cfb_stream_declared_bytes,
105                ceiling.cfb_stream_declared_bytes,
106            ),
107            (
108                ResourceDimension::AggregateDeclaredBytes,
109                self.cfb_aggregate_declared_bytes,
110                ceiling.cfb_aggregate_declared_bytes,
111            ),
112            (
113                ResourceDimension::EntryActualBytes,
114                self.cfb_stream_read_bytes,
115                ceiling.cfb_stream_read_bytes,
116            ),
117            (
118                ResourceDimension::AggregateActualBytes,
119                self.cfb_aggregate_read_bytes,
120                ceiling.cfb_aggregate_read_bytes,
121            ),
122            (
123                ResourceDimension::InputBytes,
124                self.compressed_bytes,
125                ceiling.compressed_bytes,
126            ),
127            (
128                ResourceDimension::ModuleCount,
129                self.module_count,
130                ceiling.module_count,
131            ),
132            (
133                ResourceDimension::ChunkCount,
134                self.chunk_count,
135                ceiling.chunk_count,
136            ),
137            (
138                ResourceDimension::OutputBytes,
139                self.module_decoded_bytes,
140                ceiling.module_decoded_bytes,
141            ),
142            (
143                ResourceDimension::OutputBytes,
144                self.aggregate_decoded_bytes,
145                ceiling.aggregate_decoded_bytes,
146            ),
147            (
148                ResourceDimension::RetainedBytes,
149                self.retained_bytes,
150                ceiling.retained_bytes,
151            ),
152            (
153                ResourceDimension::OutputBytes,
154                self.output_bytes,
155                ceiling.output_bytes,
156            ),
157        ] {
158            if value == 0 || value > maximum {
159                return Err(vba_limit(
160                    dimension,
161                    maximum,
162                    value.max(maximum.saturating_add(1)),
163                    ResourceStage::Validate,
164                ));
165            }
166        }
167        Ok(self)
168    }
169}
170
171struct VbaBudget {
172    limits: VbaLimits,
173    stream_count: u64,
174    aggregate_declared: u64,
175    aggregate_read: u64,
176    compressed: u64,
177    modules: u64,
178    chunks: u64,
179    aggregate_decoded: u64,
180    retained: u64,
181    output: u64,
182}
183
184impl VbaBudget {
185    fn new(limits: VbaLimits) -> Result<Self> {
186        Ok(Self {
187            limits: limits.validate()?,
188            stream_count: 0,
189            aggregate_declared: 0,
190            aggregate_read: 0,
191            compressed: 0,
192            modules: 0,
193            chunks: 0,
194            aggregate_decoded: 0,
195            retained: 0,
196            output: 0,
197        })
198    }
199
200    fn check_input(&self, observed: u64) -> Result<()> {
201        check_vba_limit(
202            ResourceDimension::InputBytes,
203            self.limits.input_bytes,
204            observed,
205            ResourceStage::Inspect,
206        )
207    }
208
209    fn inspect_stream(&mut self, declared: u64) -> Result<()> {
210        self.stream_count = checked_total(self.stream_count, 1);
211        check_vba_limit(
212            ResourceDimension::StreamCount,
213            self.limits.cfb_stream_count,
214            self.stream_count,
215            ResourceStage::Inspect,
216        )?;
217        check_vba_limit(
218            ResourceDimension::EntryDeclaredBytes,
219            self.limits.cfb_stream_declared_bytes,
220            declared,
221            ResourceStage::Inspect,
222        )?;
223        let aggregate = checked_total(self.aggregate_declared, declared);
224        check_vba_limit(
225            ResourceDimension::AggregateDeclaredBytes,
226            self.limits.cfb_aggregate_declared_bytes,
227            aggregate,
228            ResourceStage::Inspect,
229        )?;
230        self.aggregate_declared = aggregate;
231        Ok(())
232    }
233
234    fn charge_stream_read(&mut self, stream_total: u64, amount: u64) -> Result<u64> {
235        let stream_total = checked_total(stream_total, amount);
236        check_vba_limit(
237            ResourceDimension::EntryActualBytes,
238            self.limits.cfb_stream_read_bytes,
239            stream_total,
240            ResourceStage::Read,
241        )?;
242        let aggregate = checked_total(self.aggregate_read, amount);
243        check_vba_limit(
244            ResourceDimension::AggregateActualBytes,
245            self.limits.cfb_aggregate_read_bytes,
246            aggregate,
247            ResourceStage::Read,
248        )?;
249        self.aggregate_read = aggregate;
250        Ok(stream_total)
251    }
252
253    fn charge_compressed(&mut self, amount: u64) -> Result<()> {
254        let observed = checked_total(self.compressed, amount);
255        check_vba_limit(
256            ResourceDimension::InputBytes,
257            self.limits.compressed_bytes,
258            observed,
259            ResourceStage::Decode,
260        )?;
261        self.compressed = observed;
262        Ok(())
263    }
264
265    fn charge_module(&mut self) -> Result<()> {
266        let observed = checked_total(self.modules, 1);
267        check_vba_limit(
268            ResourceDimension::ModuleCount,
269            self.limits.module_count,
270            observed,
271            ResourceStage::Parse,
272        )?;
273        self.modules = observed;
274        Ok(())
275    }
276
277    fn charge_chunk(&mut self) -> Result<()> {
278        let observed = checked_total(self.chunks, 1);
279        check_vba_limit(
280            ResourceDimension::ChunkCount,
281            self.limits.chunk_count,
282            observed,
283            ResourceStage::Decode,
284        )?;
285        self.chunks = observed;
286        Ok(())
287    }
288
289    fn check_decoded(&self, module_total: u64, amount: u64) -> Result<(u64, u64)> {
290        let module_total = checked_total(module_total, amount);
291        check_vba_limit(
292            ResourceDimension::OutputBytes,
293            self.limits.module_decoded_bytes,
294            module_total,
295            ResourceStage::Decode,
296        )?;
297        let aggregate = checked_total(self.aggregate_decoded, amount);
298        check_vba_limit(
299            ResourceDimension::OutputBytes,
300            self.limits.aggregate_decoded_bytes,
301            aggregate,
302            ResourceStage::Decode,
303        )?;
304        Ok((module_total, aggregate))
305    }
306
307    fn commit_decoded(&mut self, aggregate: u64) {
308        self.aggregate_decoded = aggregate;
309    }
310
311    fn charge_retained(&mut self, amount: u64) -> Result<()> {
312        let observed = checked_total(self.retained, amount);
313        check_vba_limit(
314            ResourceDimension::RetainedBytes,
315            self.limits.retained_bytes,
316            observed,
317            ResourceStage::Decode,
318        )?;
319        self.retained = observed;
320        Ok(())
321    }
322
323    fn charge_output(&mut self, amount: u64) -> Result<()> {
324        let observed = checked_total(self.output, amount);
325        check_vba_limit(
326            ResourceDimension::OutputBytes,
327            self.limits.output_bytes,
328            observed,
329            ResourceStage::Decode,
330        )?;
331        self.output = observed;
332        Ok(())
333    }
334}
335
336fn checked_total(current: u64, amount: u64) -> u64 {
337    current.saturating_add(amount)
338}
339
340fn check_vba_limit(
341    dimension: ResourceDimension,
342    limit: u64,
343    observed: u64,
344    stage: ResourceStage,
345) -> Result<()> {
346    if observed > limit {
347        return Err(vba_limit(dimension, limit, observed, stage));
348    }
349    Ok(())
350}
351
352fn vba_limit(
353    dimension: ResourceDimension,
354    limit: u64,
355    observed: u64,
356    stage: ResourceStage,
357) -> Error {
358    let metadata = ResourceLimitError::exceeded(
359        ResourceOperation::MacroRead,
360        ResourceCategory::Macro,
361        dimension,
362        limit,
363        observed,
364        Some(stage),
365    );
366    match metadata {
367        Some(metadata) => Error::ResourceLimitExceeded(metadata),
368        None => Error::Internal("invalid VBA resource limit state".to_string()),
369    }
370}
371
372/// Classification of a VBA module.
373#[derive(Debug, Clone, PartialEq, Eq)]
374pub enum VbaModuleType {
375    /// A standard code module (`.bas`).
376    Standard,
377    /// A class module (`.cls`).
378    Class,
379    /// A UserForm module.
380    Form,
381    /// A document module (e.g. Sheet code-behind).
382    Document,
383    /// The ThisWorkbook module.
384    ThisWorkbook,
385}
386
387/// A single VBA module with its name, source code, and type.
388#[derive(Debug, Clone)]
389pub struct VbaModule {
390    pub name: String,
391    pub source_code: String,
392    pub module_type: VbaModuleType,
393}
394
395/// Result of extracting a VBA project from a `.xlsm` file.
396///
397/// Contains extracted modules and any non-fatal warnings encountered
398/// during parsing (e.g., unreadable streams, decompression failures,
399/// unsupported codepages).
400#[derive(Debug, Clone)]
401pub struct VbaProject {
402    pub modules: Vec<VbaModule>,
403    pub warnings: Vec<String>,
404}
405
406/// Offset entry parsed from the `dir` stream for a single module.
407#[derive(Debug)]
408struct ModuleEntry {
409    name: String,
410    stream_name: String,
411    text_offset: u32,
412    module_type: VbaModuleType,
413}
414
415/// Parsed metadata from the `dir` stream.
416#[derive(Debug)]
417struct DirInfo {
418    entries: Vec<ModuleEntry>,
419    codepage: u16,
420}
421
422/// Extract VBA module source code from a `vbaProject.bin` binary blob.
423///
424/// Parses the OLE/CFB container, reads the `dir` stream to discover
425/// module metadata, then decompresses each module stream.
426///
427/// Returns a [`VbaProject`] containing extracted modules and any
428/// non-fatal warnings (e.g., modules that could not be read or
429/// decompressed, unsupported codepages).
430pub fn extract_vba_modules(vba_bin: &[u8]) -> Result<VbaProject> {
431    extract_vba_modules_with_limits(vba_bin, VbaLimits::default())
432}
433
434/// Validates a raw VBA project against finite input and hard-ceiling limits.
435pub(crate) fn validate_vba_input(vba_bin: &[u8], limits: VbaLimits) -> Result<()> {
436    let budget = VbaBudget::new(limits)?;
437    budget.check_input(u64::try_from(vba_bin.len()).unwrap_or(u64::MAX))
438}
439
440/// Extract VBA modules using explicit finite limits.
441pub fn extract_vba_modules_with_limits(vba_bin: &[u8], limits: VbaLimits) -> Result<VbaProject> {
442    validate_vba_input(vba_bin, limits)?;
443    let mut budget = VbaBudget::new(limits)?;
444    let cursor = Cursor::new(vba_bin);
445    let mut cfb = cfb::CompoundFile::open(cursor)
446        .map_err(|_| Error::Internal("failed to open VBA project as CFB".to_string()))?;
447
448    for entry in cfb.walk() {
449        if entry.is_stream() {
450            budget.inspect_stream(entry.len())?;
451        }
452    }
453
454    // Find the VBA storage root. Typically `/VBA` or could be nested.
455    let vba_prefix = find_vba_prefix(&mut cfb)?;
456
457    // Read the `dir` stream to get module entries.
458    let dir_path = format!("{vba_prefix}dir");
459    let dir_data = read_cfb_stream(&mut cfb, &dir_path, &mut budget)?;
460
461    // The dir stream is compressed using MS-OVBA compression.
462    let decompressed_dir = decompress_vba_stream_budgeted(&dir_data, &mut budget)?;
463
464    // Parse module entries and codepage from the decompressed dir stream.
465    let dir_info = parse_dir_stream_budgeted(&decompressed_dir, &mut budget)?;
466
467    let mut modules = Vec::new();
468    modules
469        .try_reserve(dir_info.entries.len())
470        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
471    let mut warnings = Vec::new();
472    warnings
473        .try_reserve(MAX_WARNINGS + 1)
474        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
475
476    for (module_index, entry) in dir_info.entries.into_iter().enumerate() {
477        let stream_path = format!("{vba_prefix}{}", entry.stream_name);
478        let compressed_data = match read_cfb_stream(&mut cfb, &stream_path, &mut budget) {
479            Ok(data) => data,
480            Err(Error::ResourceLimitExceeded(metadata)) => {
481                return Err(Error::ResourceLimitExceeded(metadata));
482            }
483            Err(_) => {
484                push_warning(
485                    &mut warnings,
486                    "module skipped: stream read failed",
487                    &mut budget,
488                )?;
489                continue;
490            }
491        };
492
493        // The module stream has text_offset bytes of "performance cache"
494        // (compiled code) followed by compressed source code.
495        let text_offset = usize::try_from(entry.text_offset)
496            .map_err(|_| Error::Internal("invalid VBA module offset".to_string()))?;
497        if text_offset > compressed_data.len() {
498            push_warning(
499                &mut warnings,
500                "module skipped: invalid source offset",
501                &mut budget,
502            )?;
503            continue;
504        }
505        let source_compressed = &compressed_data[text_offset..];
506        let source_bytes = match decompress_vba_stream_budgeted(source_compressed, &mut budget) {
507            Ok(b) => b,
508            Err(Error::ResourceLimitExceeded(metadata)) => {
509                return Err(Error::ResourceLimitExceeded(metadata));
510            }
511            Err(_) => {
512                push_warning(
513                    &mut warnings,
514                    "module skipped: decompression failed",
515                    &mut budget,
516                )?;
517                continue;
518            }
519        };
520
521        let source_code = decode_source_bytes(
522            &source_bytes,
523            dir_info.codepage,
524            module_index,
525            &mut warnings,
526            &mut budget,
527        )?;
528        budget.charge_retained(u64::try_from(entry.name.len()).unwrap_or(u64::MAX))?;
529        budget.charge_output(u64::try_from(entry.name.len()).unwrap_or(u64::MAX))?;
530
531        modules.push(VbaModule {
532            name: entry.name,
533            source_code,
534            module_type: entry.module_type,
535        });
536    }
537
538    Ok(VbaProject { modules, warnings })
539}
540
541fn push_warning(warnings: &mut Vec<String>, warning: &str, budget: &mut VbaBudget) -> Result<()> {
542    if warnings.len() < MAX_WARNINGS {
543        let len = u64::try_from(warning.len()).unwrap_or(u64::MAX);
544        budget.charge_output(len)?;
545        budget.charge_retained(len)?;
546        warnings.push(warning.to_string());
547    } else if warnings.len() == MAX_WARNINGS {
548        const OMITTED: &str = "additional VBA warnings omitted";
549        let len = u64::try_from(OMITTED.len()).unwrap_or(u64::MAX);
550        budget.charge_output(len)?;
551        budget.charge_retained(len)?;
552        warnings.push(OMITTED.to_string());
553    }
554    Ok(())
555}
556
557/// Decode source bytes using the specified codepage.
558///
559/// Codepages 1252 (Western European) and 65001 (UTF-8) are decoded fully.
560/// Codepages 932 (Shift-JIS), 949 (Korean), and 936 (GBK) are decoded lossily:
561/// ASCII and CP932 half-width katakana are preserved, while other
562/// double-byte sequences become U+FFFD and a per-module warning reports the
563/// replacement count. Unrecognized codepages fall back to UTF-8 lossy
564/// decoding with a warning.
565fn decode_source_bytes(
566    bytes: &[u8],
567    codepage: u16,
568    module_index: usize,
569    warnings: &mut Vec<String>,
570    budget: &mut VbaBudget,
571) -> Result<String> {
572    let decoded_len = decoded_source_len(bytes, codepage);
573    budget.charge_output(decoded_len)?;
574    budget.charge_retained(decoded_len)?;
575    let capacity = usize::try_from(decoded_len)
576        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
577    if !matches!(codepage, 65001 | 0 | 1252 | 932 | 949 | 936) {
578        push_warning(
579            warnings,
580            "unsupported codepage; used UTF-8 lossy decoding",
581            budget,
582        )?;
583    }
584    let decoded = decode_with_codepage(bytes, codepage, capacity)?;
585    if matches!(codepage, 932 | 949 | 936) {
586        // ASCII-only input cannot produce U+FFFD on these paths, so every
587        // replacement character marks a sequence that was not decoded.
588        let replaced = decoded.chars().filter(|&c| c == '\u{FFFD}').count();
589        if replaced > 0 {
590            let warning = format!(
591                "module {}: codepage {codepage} decoding is lossy; {replaced} byte sequence(s) replaced with U+FFFD",
592                module_index + 1
593            );
594            push_warning(warnings, &warning, budget)?;
595        }
596    }
597    Ok(decoded)
598}
599
600/// Decode bytes with the project codepage without charging any budget.
601fn decode_with_codepage(bytes: &[u8], codepage: u16, capacity: usize) -> Result<String> {
602    match codepage {
603        1252 => decode_single_byte(bytes, &WINDOWS_1252_HIGH, capacity),
604        932 => decode_shift_jis(bytes, capacity),
605        949 | 936 => decode_double_byte_lossy(bytes, capacity),
606        _ => decode_utf8_lossy(bytes, capacity),
607    }
608}
609
610/// Decode an ANSI `dir` record name with the project codepage, charging the
611/// decoded length against the retained budget.
612fn decode_dir_name(bytes: &[u8], codepage: u16, budget: &mut VbaBudget) -> Result<String> {
613    let decoded_len = decoded_source_len(bytes, codepage);
614    budget.charge_retained(decoded_len)?;
615    let capacity = usize::try_from(decoded_len)
616        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
617    decode_with_codepage(bytes, codepage, capacity)
618}
619
620/// Decode a UTF-16LE `dir` record name, ignoring an odd trailing byte and
621/// trailing NULs. Returns `None` when the decoded name is empty.
622fn decode_dir_unicode_name(bytes: &[u8], budget: &mut VbaBudget) -> Result<Option<String>> {
623    let even_len = bytes.len() & !1;
624    budget.charge_retained(
625        u64::try_from(even_len)
626            .unwrap_or(u64::MAX)
627            .saturating_mul(2),
628    )?;
629    let mut units = Vec::new();
630    units
631        .try_reserve(even_len / 2)
632        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
633    let (pairs, _) = bytes[..even_len].as_chunks::<2>();
634    units.extend(pairs.iter().map(|pair| u16::from_le_bytes(*pair)));
635    let name = String::from_utf16_lossy(&units);
636    let name = name.trim_end_matches('\0');
637    Ok((!name.is_empty()).then(|| name.to_string()))
638}
639
640fn decoded_source_len(bytes: &[u8], codepage: u16) -> u64 {
641    let length = match codepage {
642        65001 | 0 => utf8_lossy_len(bytes),
643        1252 => bytes.iter().fold(0_usize, |total, &byte| {
644            let width = if byte < 0x80 {
645                1
646            } else {
647                WINDOWS_1252_HIGH[usize::from(byte - 0x80)].len_utf8()
648            };
649            total.saturating_add(width)
650        }),
651        932 => shift_jis_lossy_len(bytes),
652        949 | 936 => double_byte_lossy_len(bytes),
653        _ => utf8_lossy_len(bytes),
654    };
655    u64::try_from(length).unwrap_or(u64::MAX)
656}
657
658fn utf8_lossy_len(mut bytes: &[u8]) -> usize {
659    let mut length = 0_usize;
660    while !bytes.is_empty() {
661        match std::str::from_utf8(bytes) {
662            Ok(valid) => return length.saturating_add(valid.len()),
663            Err(error) => {
664                length = length
665                    .saturating_add(error.valid_up_to())
666                    .saturating_add('�'.len_utf8());
667                match error.error_len() {
668                    Some(invalid) => bytes = &bytes[error.valid_up_to() + invalid..],
669                    None => return length,
670                }
671            }
672        }
673    }
674    length
675}
676
677fn decode_utf8_lossy(mut bytes: &[u8], capacity: usize) -> Result<String> {
678    let mut output = String::new();
679    output
680        .try_reserve(capacity)
681        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
682    while !bytes.is_empty() {
683        match std::str::from_utf8(bytes) {
684            Ok(valid) => {
685                output.push_str(valid);
686                break;
687            }
688            Err(error) => {
689                let valid = &bytes[..error.valid_up_to()];
690                let valid = std::str::from_utf8(valid)
691                    .map_err(|_| Error::Internal("invalid VBA decode state".to_string()))?;
692                output.push_str(valid);
693                output.push('�');
694                match error.error_len() {
695                    Some(invalid) => bytes = &bytes[error.valid_up_to() + invalid..],
696                    None => break,
697                }
698            }
699        }
700    }
701    Ok(output)
702}
703
704/// Windows-1252 high-byte mapping (0x80..0xFF).
705/// Bytes 0x00..0x7F are identical to ASCII.
706static WINDOWS_1252_HIGH: [char; 128] = [
707    '\u{20AC}', '\u{0081}', '\u{201A}', '\u{0192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}',
708    '\u{02C6}', '\u{2030}', '\u{0160}', '\u{2039}', '\u{0152}', '\u{008D}', '\u{017D}', '\u{008F}',
709    '\u{0090}', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}',
710    '\u{02DC}', '\u{2122}', '\u{0161}', '\u{203A}', '\u{0153}', '\u{009D}', '\u{017E}', '\u{0178}',
711    '\u{00A0}', '\u{00A1}', '\u{00A2}', '\u{00A3}', '\u{00A4}', '\u{00A5}', '\u{00A6}', '\u{00A7}',
712    '\u{00A8}', '\u{00A9}', '\u{00AA}', '\u{00AB}', '\u{00AC}', '\u{00AD}', '\u{00AE}', '\u{00AF}',
713    '\u{00B0}', '\u{00B1}', '\u{00B2}', '\u{00B3}', '\u{00B4}', '\u{00B5}', '\u{00B6}', '\u{00B7}',
714    '\u{00B8}', '\u{00B9}', '\u{00BA}', '\u{00BB}', '\u{00BC}', '\u{00BD}', '\u{00BE}', '\u{00BF}',
715    '\u{00C0}', '\u{00C1}', '\u{00C2}', '\u{00C3}', '\u{00C4}', '\u{00C5}', '\u{00C6}', '\u{00C7}',
716    '\u{00C8}', '\u{00C9}', '\u{00CA}', '\u{00CB}', '\u{00CC}', '\u{00CD}', '\u{00CE}', '\u{00CF}',
717    '\u{00D0}', '\u{00D1}', '\u{00D2}', '\u{00D3}', '\u{00D4}', '\u{00D5}', '\u{00D6}', '\u{00D7}',
718    '\u{00D8}', '\u{00D9}', '\u{00DA}', '\u{00DB}', '\u{00DC}', '\u{00DD}', '\u{00DE}', '\u{00DF}',
719    '\u{00E0}', '\u{00E1}', '\u{00E2}', '\u{00E3}', '\u{00E4}', '\u{00E5}', '\u{00E6}', '\u{00E7}',
720    '\u{00E8}', '\u{00E9}', '\u{00EA}', '\u{00EB}', '\u{00EC}', '\u{00ED}', '\u{00EE}', '\u{00EF}',
721    '\u{00F0}', '\u{00F1}', '\u{00F2}', '\u{00F3}', '\u{00F4}', '\u{00F5}', '\u{00F6}', '\u{00F7}',
722    '\u{00F8}', '\u{00F9}', '\u{00FA}', '\u{00FB}', '\u{00FC}', '\u{00FD}', '\u{00FE}', '\u{00FF}',
723];
724
725/// Decode bytes using a single-byte codepage with the given high-byte table.
726fn decode_single_byte(bytes: &[u8], high_table: &[char; 128], capacity: usize) -> Result<String> {
727    let mut out = String::new();
728    out.try_reserve(capacity)
729        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
730    for &b in bytes {
731        if b < 0x80 {
732            out.push(b as char);
733        } else {
734            out.push(high_table[(b - 0x80) as usize]);
735        }
736    }
737    Ok(out)
738}
739
740/// Decode Shift-JIS (codepage 932) bytes to a String.
741/// Lossy: ASCII and half-width katakana are decoded; double-byte characters
742/// and invalid bytes become U+FFFD because no full mapping table is bundled.
743fn decode_shift_jis(bytes: &[u8], capacity: usize) -> Result<String> {
744    let mut out = String::new();
745    out.try_reserve(capacity)
746        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
747    let mut i = 0;
748    while i < bytes.len() {
749        let b = bytes[i];
750        if b < 0x80 {
751            out.push(b as char);
752            i += 1;
753        } else if b == 0x80 || b == 0xA0 || b >= 0xFD {
754            out.push('\u{FFFD}');
755            i += 1;
756        } else if (0xA1..=0xDF).contains(&b) {
757            // Half-width katakana
758            out.push(char::from_u32(0xFF61 + (b as u32 - 0xA1)).unwrap_or('\u{FFFD}'));
759            i += 1;
760        } else if i + 1 < bytes.len() {
761            // Double-byte character -- fall back to replacement for simplicity
762            // Full Shift-JIS decoding requires a large mapping table.
763            out.push('\u{FFFD}');
764            i += 2;
765        } else {
766            out.push('\u{FFFD}');
767            i += 1;
768        }
769    }
770    Ok(out)
771}
772
773fn shift_jis_lossy_len(bytes: &[u8]) -> usize {
774    let mut length = 0_usize;
775    let mut i = 0;
776    while i < bytes.len() {
777        let b = bytes[i];
778        if b < 0x80 {
779            length = length.saturating_add(1);
780            i += 1;
781        } else if b == 0x80 || b == 0xA0 || b >= 0xFD || (0xA1..=0xDF).contains(&b) {
782            length = length.saturating_add(3);
783            i += 1;
784        } else if i + 1 < bytes.len() {
785            length = length.saturating_add(3);
786            i += 2;
787        } else {
788            length = length.saturating_add(3);
789            i += 1;
790        }
791    }
792    length
793}
794
795/// Decode a two-byte codepage such as CP949 or GBK lossily: ASCII is
796/// preserved and every non-ASCII sequence becomes U+FFFD.
797fn decode_double_byte_lossy(bytes: &[u8], capacity: usize) -> Result<String> {
798    let mut out = String::new();
799    out.try_reserve(capacity)
800        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
801    let mut i = 0;
802    while i < bytes.len() {
803        let b = bytes[i];
804        if b < 0x80 {
805            out.push(b as char);
806            i += 1;
807        } else if i + 1 < bytes.len() {
808            out.push('\u{FFFD}');
809            i += 2;
810        } else {
811            out.push('\u{FFFD}');
812            i += 1;
813        }
814    }
815    Ok(out)
816}
817
818fn double_byte_lossy_len(bytes: &[u8]) -> usize {
819    let mut length = 0_usize;
820    let mut i = 0;
821    while i < bytes.len() {
822        if bytes[i] < 0x80 {
823            length = length.saturating_add(1);
824            i += 1;
825        } else {
826            length = length.saturating_add(3);
827            i = i.saturating_add(2).min(bytes.len());
828        }
829    }
830    length
831}
832
833/// Find the VBA storage prefix inside the CFB container.
834/// Returns the path prefix ending with a separator (e.g. "VBA/").
835fn find_vba_prefix(cfb: &mut cfb::CompoundFile<Cursor<&[u8]>>) -> Result<String> {
836    // Look for a "dir" stream under a VBA storage.
837    for entry in cfb.walk() {
838        let entry_path = entry.path().to_string_lossy();
839        let normalized = entry_path.replace('\\', "/");
840        if normalized.ends_with("/dir") || normalized.ends_with("/DIR") {
841            let prefix = &normalized[..normalized.len() - 3];
842            return Ok(prefix.to_string());
843        }
844    }
845
846    // Try common paths directly.
847    for prefix in ["/VBA/", "VBA/", "/"] {
848        let dir_path = format!("{prefix}dir");
849        if cfb.is_stream(&dir_path) {
850            return Ok(prefix.to_string());
851        }
852    }
853
854    Err(Error::Internal(
855        "could not find VBA dir stream in vbaProject.bin".to_string(),
856    ))
857}
858
859/// Read a stream from the CFB container as raw bytes.
860fn read_cfb_stream(
861    cfb: &mut cfb::CompoundFile<Cursor<&[u8]>>,
862    path: &str,
863    budget: &mut VbaBudget,
864) -> Result<Vec<u8>> {
865    let declared = cfb
866        .entry(path)
867        .map_err(|_| Error::Internal("failed to inspect VBA CFB stream".to_string()))?
868        .len();
869    check_vba_limit(
870        ResourceDimension::EntryDeclaredBytes,
871        budget.limits.cfb_stream_declared_bytes,
872        declared,
873        ResourceStage::Inspect,
874    )?;
875    let capacity = usize::try_from(declared.min(8192)).map_err(|_| {
876        vba_limit(
877            ResourceDimension::EntryDeclaredBytes,
878            budget.limits.cfb_stream_declared_bytes,
879            declared,
880            ResourceStage::Inspect,
881        )
882    })?;
883    let mut stream = cfb
884        .open_stream(path)
885        .map_err(|_| Error::Internal("failed to open VBA CFB stream".to_string()))?;
886    let mut data = Vec::new();
887    data.try_reserve(capacity)
888        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
889    let mut buffer = [0_u8; 8192];
890    let mut stream_total = 0_u64;
891    loop {
892        let read = stream
893            .read(&mut buffer)
894            .map_err(|_| Error::Internal("failed to read VBA CFB stream".to_string()))?;
895        if read == 0 {
896            break;
897        }
898        let amount = u64::try_from(read).unwrap_or(u64::MAX);
899        stream_total = budget.charge_stream_read(stream_total, amount)?;
900        data.try_reserve(read)
901            .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
902        data.extend_from_slice(&buffer[..read]);
903    }
904    Ok(data)
905}
906
907/// Decompress a VBA compressed stream per MS-OVBA 2.4.1.
908///
909/// The format is:
910/// - 1 byte signature (0x01)
911/// - Sequence of compressed chunks, each starting with a 2-byte header
912/// - Each chunk contains a mix of literal bytes and copy tokens
913pub fn decompress_vba_stream(data: &[u8]) -> Result<Vec<u8>> {
914    let mut budget = VbaBudget::new(VbaLimits::default())?;
915    decompress_vba_stream_budgeted(data, &mut budget)
916}
917
918fn decompress_vba_stream_budgeted(data: &[u8], budget: &mut VbaBudget) -> Result<Vec<u8>> {
919    budget.charge_compressed(u64::try_from(data.len()).unwrap_or(u64::MAX))?;
920    if data.is_empty() {
921        return Ok(Vec::new());
922    }
923
924    if data[0] != 0x01 {
925        return Err(Error::Internal(
926            "invalid VBA compression signature".to_string(),
927        ));
928    }
929
930    let mut output = Vec::new();
931    let mut pos = 1; // skip signature byte
932    let mut module_total = 0_u64;
933
934    while pos < data.len() {
935        budget.charge_chunk()?;
936        if pos + 1 >= data.len() {
937            return Err(Error::Internal(
938                "truncated VBA compressed chunk header".to_string(),
939            ));
940        }
941
942        // Read chunk header (2 bytes, little-endian)
943        let header = u16::from_le_bytes([data[pos], data[pos + 1]]);
944        pos += 2;
945
946        let chunk_size = (header & 0x0FFF) as usize + 3;
947        let is_compressed = (header & 0x8000) != 0;
948
949        let payload_size = chunk_size - 2;
950        let chunk_end = pos
951            .checked_add(payload_size)
952            .filter(|&end| end <= data.len())
953            .ok_or_else(|| Error::Internal("truncated VBA compressed chunk".to_string()))?;
954
955        if !is_compressed {
956            // Uncompressed chunk: raw bytes (4096 bytes max)
957            let raw_end = chunk_end.min(pos + 4096);
958            let amount = u64::try_from(raw_end - pos).unwrap_or(u64::MAX);
959            let (next_module, next_aggregate) = budget.check_decoded(module_total, amount)?;
960            output
961                .try_reserve(raw_end - pos)
962                .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
963            output.extend_from_slice(&data[pos..raw_end]);
964            module_total = next_module;
965            budget.commit_decoded(next_aggregate);
966            pos = chunk_end;
967            continue;
968        }
969
970        // Compressed chunk
971        let chunk_start_output = output.len();
972        while pos < chunk_end {
973            if pos >= data.len() {
974                break;
975            }
976
977            let flag_byte = data[pos];
978            pos += 1;
979
980            for bit_index in 0..8 {
981                if pos >= chunk_end {
982                    break;
983                }
984
985                if (flag_byte >> bit_index) & 1 == 0 {
986                    // Literal byte
987                    if output.len() - chunk_start_output >= 4096 {
988                        return Err(Error::Internal(
989                            "VBA literal exceeds decompressed chunk size".to_string(),
990                        ));
991                    }
992                    let (next_module, next_aggregate) = budget.check_decoded(module_total, 1)?;
993                    output
994                        .try_reserve(1)
995                        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
996                    output.push(data[pos]);
997                    module_total = next_module;
998                    budget.commit_decoded(next_aggregate);
999                    pos += 1;
1000                } else {
1001                    // Copy token (2 bytes, little-endian)
1002                    if pos + 1 >= chunk_end {
1003                        return Err(Error::Internal("truncated VBA copy token".to_string()));
1004                    }
1005                    let token = u16::from_le_bytes([data[pos], data[pos + 1]]);
1006                    pos += 2;
1007
1008                    // Calculate the number of bits for the length and offset
1009                    let decompressed_current = output.len() - chunk_start_output;
1010                    let bit_count = offset_bit_count(decompressed_current);
1011                    let length_mask = 0xFFFF >> bit_count;
1012                    let offset_mask = !length_mask;
1013
1014                    let length = ((token & length_mask) + 3) as usize;
1015                    let offset = (((token & offset_mask) >> (16 - bit_count)) + 1) as usize;
1016
1017                    if offset == 0 || offset > decompressed_current {
1018                        return Err(Error::Internal("invalid VBA copy token offset".to_string()));
1019                    }
1020                    if decompressed_current + length > 4096 {
1021                        return Err(Error::Internal(
1022                            "VBA copy token exceeds decompressed chunk size".to_string(),
1023                        ));
1024                    }
1025
1026                    let amount = u64::try_from(length).unwrap_or(u64::MAX);
1027                    let (next_module, next_aggregate) =
1028                        budget.check_decoded(module_total, amount)?;
1029                    output
1030                        .try_reserve(length)
1031                        .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
1032                    for _ in 0..length {
1033                        let byte = output[output.len() - offset];
1034                        output.push(byte);
1035                    }
1036                    module_total = next_module;
1037                    budget.commit_decoded(next_aggregate);
1038                }
1039            }
1040        }
1041    }
1042
1043    Ok(output)
1044}
1045
1046/// Calculate the bit count for the copy token offset field.
1047/// Per MS-OVBA 2.4.1.3.19.1:
1048/// The number of bits used for the offset is ceil(log2(decompressed_current)) with min 4.
1049fn offset_bit_count(decompressed_current: usize) -> u16 {
1050    if decompressed_current <= 16 {
1051        return 4;
1052    }
1053    if decompressed_current <= 32 {
1054        return 5;
1055    }
1056    if decompressed_current <= 64 {
1057        return 6;
1058    }
1059    if decompressed_current <= 128 {
1060        return 7;
1061    }
1062    if decompressed_current <= 256 {
1063        return 8;
1064    }
1065    if decompressed_current <= 512 {
1066        return 9;
1067    }
1068    if decompressed_current <= 1024 {
1069        return 10;
1070    }
1071    if decompressed_current <= 2048 {
1072        return 11;
1073    }
1074    12
1075}
1076
1077/// Parse the decompressed `dir` stream to extract module entries and codepage.
1078///
1079/// The dir stream is a sequence of records with 2-byte IDs and 4-byte sizes.
1080/// We look for MODULE_NAME, MODULE_STREAM_NAME, MODULE_OFFSET,
1081/// MODULE_TYPE, and PROJECTCODEPAGE records.
1082///
1083/// MODULE_TYPE record 0x0021 indicates a procedural (standard) module.
1084/// MODULE_TYPE record 0x0022 indicates a document/class module. When 0x0022
1085/// is present, we refine the type to `Document`, `ThisWorkbook`, or `Class`
1086/// based on the module name (since OOXML does not distinguish these subtypes
1087/// at the record level).
1088#[cfg(test)]
1089fn parse_dir_stream(data: &[u8]) -> Result<DirInfo> {
1090    let mut budget = VbaBudget::new(VbaLimits::default())?;
1091    parse_dir_stream_budgeted(data, &mut budget)
1092}
1093
1094fn parse_dir_stream_budgeted(data: &[u8], budget: &mut VbaBudget) -> Result<DirInfo> {
1095    let mut pos = 0;
1096    let mut modules = Vec::new();
1097    let mut codepage: u16 = 1252; // Default to Windows-1252
1098
1099    // Current module being built
1100    let mut current_name: Option<String> = None;
1101    let mut current_stream_name: Option<String> = None;
1102    let mut current_offset: u32 = 0;
1103    let mut current_type = VbaModuleType::Standard;
1104    let mut in_module = false;
1105
1106    while data.len().saturating_sub(pos) >= 6 {
1107        let record_id = u16::from_le_bytes([data[pos], data[pos + 1]]);
1108        let record_size =
1109            u32::from_le_bytes([data[pos + 2], data[pos + 3], data[pos + 4], data[pos + 5]])
1110                as usize;
1111        pos += 6;
1112
1113        let payload_size = if record_id == 0x0009 {
1114            if record_size != 4 {
1115                return Err(Error::Internal(
1116                    "invalid PROJECTVERSION declared size".to_string(),
1117                ));
1118            }
1119            6
1120        } else {
1121            record_size
1122        };
1123        let payload_end = pos
1124            .checked_add(payload_size)
1125            .filter(|&end| end <= data.len())
1126            .ok_or_else(|| Error::Internal("truncated VBA dir record".to_string()))?;
1127        let record_data = &data[pos..payload_end];
1128
1129        match record_id {
1130            // PROJECTCODEPAGE
1131            0x0003 => {
1132                if record_size >= 2 {
1133                    codepage = u16::from_le_bytes([record_data[0], record_data[1]]);
1134                }
1135            }
1136            // MODULENAME
1137            0x0019 => {
1138                if in_module {
1139                    // Save previous module
1140                    if let (Some(name), Some(stream)) =
1141                        (current_name.take(), current_stream_name.take())
1142                    {
1143                        budget.charge_module()?;
1144                        modules
1145                            .try_reserve(1)
1146                            .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
1147                        let refined_type = refine_module_type(&current_type, &name);
1148                        modules.push(ModuleEntry {
1149                            name,
1150                            stream_name: stream,
1151                            text_offset: current_offset,
1152                            module_type: refined_type,
1153                        });
1154                    }
1155                }
1156                in_module = true;
1157                current_name = Some(decode_dir_name(record_data, codepage, budget)?);
1158                current_stream_name = None;
1159                current_offset = 0;
1160                current_type = VbaModuleType::Standard;
1161            }
1162            // MODULENAMEUNICODE
1163            0x0047 => {
1164                // UTF-16LE encoded name, prefer this over the ANSI name.
1165                // Use only the even portion of the data; an odd trailing
1166                // byte indicates a truncated record and is safely ignored.
1167                if record_size >= 2 {
1168                    if let Some(name) = decode_dir_unicode_name(record_data, budget)? {
1169                        current_name = Some(name);
1170                    }
1171                }
1172            }
1173            // MODULESTREAMNAME
1174            0x001A => {
1175                current_stream_name = Some(decode_dir_name(record_data, codepage, budget)?);
1176                // MS-OVBA follows StreamName with Reserved 0x0032 and the
1177                // UTF-16LE StreamNameUnicode, which is lossless and preferred.
1178                if let Some(next_header) = pos
1179                    .checked_add(payload_size)
1180                    .filter(|&start| data.len().saturating_sub(start) >= 6)
1181                {
1182                    let next_id = u16::from_le_bytes([data[next_header], data[next_header + 1]]);
1183                    if next_id == 0x0032 {
1184                        let next_size = u32::from_le_bytes([
1185                            data[next_header + 2],
1186                            data[next_header + 3],
1187                            data[next_header + 4],
1188                            data[next_header + 5],
1189                        ]) as usize;
1190                        let unicode_start = next_header + 6;
1191                        let unicode_end = unicode_start
1192                            .checked_add(next_size)
1193                            .filter(|&end| end <= data.len())
1194                            .ok_or_else(|| {
1195                                Error::Internal("truncated VBA dir record".to_string())
1196                            })?;
1197                        if let Some(name) =
1198                            decode_dir_unicode_name(&data[unicode_start..unicode_end], budget)?
1199                        {
1200                            current_stream_name = Some(name);
1201                        }
1202                        pos = unicode_end;
1203                        continue;
1204                    }
1205                }
1206            }
1207            // MODULEOFFSET
1208            0x0031 => {
1209                if record_size >= 4 {
1210                    current_offset = u32::from_le_bytes([
1211                        record_data[0],
1212                        record_data[1],
1213                        record_data[2],
1214                        record_data[3],
1215                    ]);
1216                }
1217            }
1218            // MODULETYPE procedural (0x0021)
1219            0x0021 => {
1220                current_type = VbaModuleType::Standard;
1221            }
1222            // MODULETYPE document/class (0x0022)
1223            0x0022 => {
1224                // The dir stream only distinguishes procedural (0x0021) from
1225                // non-procedural (0x0022). We refine 0x0022 into Document,
1226                // ThisWorkbook, or Class based on the module name when the
1227                // module is finalized.
1228                current_type = VbaModuleType::Class;
1229            }
1230            // TERMINATOR for modules section (0x002B)
1231            0x002B => {
1232                // End of module list
1233            }
1234            _ => {}
1235        }
1236
1237        pos = payload_end;
1238    }
1239
1240    // Save the last module if present
1241    if in_module {
1242        if let (Some(name), Some(stream)) = (current_name, current_stream_name) {
1243            budget.charge_module()?;
1244            modules
1245                .try_reserve(1)
1246                .map_err(|_| Error::Internal("VBA allocation failed".to_string()))?;
1247            let refined_type = refine_module_type(&current_type, &name);
1248            modules.push(ModuleEntry {
1249                name,
1250                stream_name: stream,
1251                text_offset: current_offset,
1252                module_type: refined_type,
1253            });
1254        }
1255    }
1256
1257    Ok(DirInfo {
1258        entries: modules,
1259        codepage,
1260    })
1261}
1262
1263/// Refine the module type for non-procedural modules (0x0022) based on
1264/// the module name. Procedural modules (0x0021) are always `Standard`.
1265fn refine_module_type(base_type: &VbaModuleType, name: &str) -> VbaModuleType {
1266    if *base_type == VbaModuleType::Standard {
1267        return VbaModuleType::Standard;
1268    }
1269    let name_lower = name.to_lowercase();
1270    if name_lower == "thisworkbook" {
1271        VbaModuleType::ThisWorkbook
1272    } else if name_lower.starts_with("sheet") {
1273        VbaModuleType::Document
1274    } else {
1275        // Remains as Class (could be a class module or UserForm).
1276        VbaModuleType::Class
1277    }
1278}
1279
1280#[cfg(test)]
1281#[allow(clippy::same_item_push)]
1282mod tests {
1283    use super::*;
1284
1285    #[test]
1286    fn test_decompress_empty_input() {
1287        let result = decompress_vba_stream(&[]);
1288        assert!(result.is_ok());
1289        assert!(result.unwrap().is_empty());
1290    }
1291
1292    #[test]
1293    fn test_decompress_invalid_signature() {
1294        let result = decompress_vba_stream(&[0x00, 0x01, 0x02]);
1295        assert!(result.is_err());
1296        let err_msg = result.unwrap_err().to_string();
1297        assert!(err_msg.contains("invalid VBA compression signature"));
1298    }
1299
1300    fn two_uncompressed_chunks() -> Vec<u8> {
1301        vec![0x01, 0x00, 0x00, b'a', 0x00, 0x00, b'b']
1302    }
1303
1304    #[test]
1305    fn test_chunk_limit_accepts_exact_and_rejects_plus_one() {
1306        let data = two_uncompressed_chunks();
1307        let mut limits = VbaLimits {
1308            chunk_count: 2,
1309            ..VbaLimits::default()
1310        };
1311        let mut budget = VbaBudget::new(limits).unwrap();
1312        assert_eq!(
1313            decompress_vba_stream_budgeted(&data, &mut budget).unwrap(),
1314            b"ab"
1315        );
1316
1317        limits.chunk_count = 1;
1318        let mut budget = VbaBudget::new(limits).unwrap();
1319        let error = decompress_vba_stream_budgeted(&data, &mut budget).unwrap_err();
1320        assert_eq!(
1321            error.resource_metadata().unwrap().dimension(),
1322            ResourceDimension::ChunkCount
1323        );
1324    }
1325
1326    #[test]
1327    fn test_decoded_limits_are_cumulative_and_cannot_reset() {
1328        let data = vec![0x01, 0x00, 0x00, b'a'];
1329        let limits = VbaLimits {
1330            module_decoded_bytes: 1,
1331            aggregate_decoded_bytes: 1,
1332            ..VbaLimits::default()
1333        };
1334        let mut budget = VbaBudget::new(limits).unwrap();
1335        assert_eq!(
1336            decompress_vba_stream_budgeted(&data, &mut budget).unwrap(),
1337            b"a"
1338        );
1339        let error = decompress_vba_stream_budgeted(&data, &mut budget).unwrap_err();
1340        assert_eq!(
1341            error.resource_metadata().unwrap().dimension(),
1342            ResourceDimension::OutputBytes
1343        );
1344
1345        let limits = VbaLimits {
1346            module_decoded_bytes: 1,
1347            ..VbaLimits::default()
1348        };
1349        let too_large = vec![0x01, 0x01, 0x00, b'a', b'b'];
1350        let mut budget = VbaBudget::new(limits).unwrap();
1351        let error = decompress_vba_stream_budgeted(&too_large, &mut budget).unwrap_err();
1352        assert_eq!(
1353            error.resource_metadata().unwrap().dimension(),
1354            ResourceDimension::OutputBytes
1355        );
1356    }
1357
1358    #[test]
1359    fn test_module_limit_counts_all_dir_entries() {
1360        let mut dir = Vec::new();
1361        for name in [b"First".as_slice(), b"Second".as_slice()] {
1362            write_dir_record(&mut dir, 0x0019, name);
1363            write_dir_record(&mut dir, 0x001A, name);
1364        }
1365
1366        let mut limits = VbaLimits {
1367            module_count: 2,
1368            ..VbaLimits::default()
1369        };
1370        let mut budget = VbaBudget::new(limits).unwrap();
1371        assert_eq!(
1372            parse_dir_stream_budgeted(&dir, &mut budget)
1373                .unwrap()
1374                .entries
1375                .len(),
1376            2
1377        );
1378
1379        limits.module_count = 1;
1380        let mut budget = VbaBudget::new(limits).unwrap();
1381        let error = parse_dir_stream_budgeted(&dir, &mut budget).unwrap_err();
1382        assert_eq!(
1383            error.resource_metadata().unwrap().dimension(),
1384            ResourceDimension::ModuleCount
1385        );
1386    }
1387
1388    #[test]
1389    fn test_decompress_uncompressed_chunk() {
1390        // Signature byte + uncompressed chunk header (size=3 -> 3+3-2=4 bytes, bit 15 clear)
1391        // Header: chunk_size = 3 bytes (field = 3-3 = 0), not compressed (bit 15 = 0)
1392        // So header = 0x0000 means size=3, uncompressed
1393        let mut data = vec![0x01]; // signature
1394                                   // Uncompressed chunk: header with bit 15 clear, size field = N-3
1395                                   // For 4 bytes of data: chunk_size = 4, field = 4-3 = 1
1396        let header: u16 = 0x0001; // bit 15 = 0 (uncompressed), size = 1+3-2 = 2 (actual chunk payload = 2)
1397                                  // Wait, let me recalculate.
1398                                  // chunk_size = (header & 0x0FFF) + 3 = field + 3
1399                                  // The chunk payload is chunk_size - 2 = field + 1 bytes
1400                                  // For 3 bytes of payload: field = 2, header = 0x0002
1401        data.extend_from_slice(&header.to_le_bytes());
1402        data.extend_from_slice(b"AB");
1403        // This should produce "AB" but limited to min(chunk_end, pos+4096)
1404        let result = decompress_vba_stream(&data).unwrap();
1405        assert_eq!(&result, b"AB");
1406    }
1407
1408    #[test]
1409    fn test_decompress_real_compressed_data() {
1410        // Test with a known compressed sequence from the MS-OVBA spec example.
1411        // Compressed representation of "aaaaaaaaaaaaaaa" (15 'a's)
1412        // Signature: 0x01
1413        // Chunk header: compressed, size field
1414        // Flag byte: 0b00000011 = 0x03 (bit 0: literal, bit 1: copy token)
1415        // Actually building a minimal valid compressed stream:
1416        // Signature: 0x01
1417        // Chunk header: size = N-3, compressed bit set
1418        // Then flag + data
1419
1420        // A simpler approach: verify that decompression of a manually built stream works.
1421        let mut compressed = vec![0x01u8];
1422        // Build chunk: 1 literal 'a', then copy token referencing offset=1, length=3
1423        // Flag byte: 0b00000010 = bit 0 literal, bit 1 copy
1424        // Literal: b'a'
1425        // Copy token with decompressed_current=1 -> bit_count=12, length_mask=0x000F
1426        // offset=1, length=3 -> offset_field=(1-1)<<4=0, length_field=3-3=0
1427        // token = 0x0000
1428        let flag = 0x02u8; // bits: 0=literal, 1=copy, rest=0
1429        let literal = b'a';
1430        let copy_token: u16 = 0x0000; // offset=1, length=3
1431
1432        let mut chunk_payload = Vec::new();
1433        chunk_payload.push(flag);
1434        chunk_payload.push(literal);
1435        chunk_payload.extend_from_slice(&copy_token.to_le_bytes());
1436
1437        let chunk_size = chunk_payload.len() + 2; // +2 for header
1438        let header: u16 = 0x8000 | ((chunk_size as u16 - 3) & 0x0FFF);
1439        compressed.extend_from_slice(&header.to_le_bytes());
1440        compressed.extend_from_slice(&chunk_payload);
1441
1442        let result = decompress_vba_stream(&compressed).unwrap();
1443        assert_eq!(&result, b"aaaa"); // 1 literal + 3 from copy
1444    }
1445
1446    #[test]
1447    fn test_offset_bit_count_thresholds() {
1448        for (position, expected) in [
1449            (0, 4),
1450            (16, 4),
1451            (17, 5),
1452            (32, 5),
1453            (33, 6),
1454            (64, 6),
1455            (65, 7),
1456            (128, 7),
1457            (129, 8),
1458            (256, 8),
1459            (257, 9),
1460            (512, 9),
1461            (513, 10),
1462            (1024, 10),
1463            (1025, 11),
1464            (2048, 11),
1465            (2049, 12),
1466            (4096, 12),
1467        ] {
1468            assert_eq!(offset_bit_count(position), expected, "position {position}");
1469        }
1470    }
1471
1472    #[test]
1473    fn test_copy_tokens_at_each_bit_width_threshold() {
1474        for position in [
1475            16, 17, 32, 33, 64, 65, 128, 129, 256, 257, 512, 513, 1024, 1025, 2048, 2049,
1476        ] {
1477            let literals: Vec<u8> = (0..position).map(|i| (i % 251) as u8).collect();
1478            let offset = position.min(13);
1479            let stream = compressed_copy_stream(&literals, offset, 3);
1480            let output = decompress_vba_stream(&stream).unwrap();
1481            assert_eq!(
1482                &output[position..],
1483                &literals[position - offset..position - offset + 3]
1484            );
1485        }
1486    }
1487
1488    #[test]
1489    fn test_copy_token_uses_overlapping_expanding_output() {
1490        let output = decompress_vba_stream(&compressed_copy_stream(b"abc", 3, 9)).unwrap();
1491        assert_eq!(output, b"abcabcabcabc");
1492    }
1493
1494    #[test]
1495    fn test_maximum_valid_copy_token_fills_chunk() {
1496        let output = decompress_vba_stream(&compressed_copy_stream(b"x", 1, 4095)).unwrap();
1497        assert_eq!(output.len(), 4096);
1498        assert!(output.iter().all(|&byte| byte == b'x'));
1499    }
1500
1501    #[test]
1502    fn test_copy_token_rejects_offset_beyond_current_chunk() {
1503        let error = decompress_vba_stream(&compressed_copy_stream(b"x", 2, 3)).unwrap_err();
1504        assert!(error.to_string().contains("invalid VBA copy token offset"));
1505    }
1506
1507    #[test]
1508    fn test_copy_token_rejects_output_past_chunk_limit() {
1509        let error = decompress_vba_stream(&compressed_copy_stream(b"x", 1, 4096)).unwrap_err();
1510        assert!(error
1511            .to_string()
1512            .contains("exceeds decompressed chunk size"));
1513    }
1514
1515    #[test]
1516    fn test_copy_token_rejects_truncated_token() {
1517        let data = [0x01, 0x01, 0x80, 0x01, 0x00];
1518        let error = decompress_vba_stream(&data).unwrap_err();
1519        assert!(error.to_string().contains("truncated VBA copy token"));
1520    }
1521
1522    #[test]
1523    fn test_project_version_consumes_fixed_six_byte_payload() {
1524        let mut data = Vec::new();
1525        data.extend_from_slice(&0x0009u16.to_le_bytes());
1526        data.extend_from_slice(&4u32.to_le_bytes());
1527        data.extend_from_slice(&0x0001_0000u32.to_le_bytes());
1528        data.extend_from_slice(&7u16.to_le_bytes());
1529        write_dir_record(&mut data, 0x0003, &65001u16.to_le_bytes());
1530
1531        assert_eq!(parse_dir_stream(&data).unwrap().codepage, 65001);
1532    }
1533
1534    #[test]
1535    fn test_project_version_rejects_truncated_fixed_payload() {
1536        let mut data = Vec::new();
1537        data.extend_from_slice(&0x0009u16.to_le_bytes());
1538        data.extend_from_slice(&4u32.to_le_bytes());
1539        data.extend_from_slice(&1u32.to_le_bytes());
1540        assert!(parse_dir_stream(&data).is_err());
1541    }
1542
1543    #[test]
1544    fn test_parse_dir_stream_empty() {
1545        let result = parse_dir_stream(&[]);
1546        assert!(result.is_ok());
1547        let info = result.unwrap();
1548        assert!(info.entries.is_empty());
1549        assert_eq!(info.codepage, 1252);
1550    }
1551
1552    #[test]
1553    fn test_extract_vba_modules_invalid_cfb() {
1554        let result = extract_vba_modules(b"not a CFB file");
1555        assert!(result.is_err());
1556        let err_msg = result.unwrap_err().to_string();
1557        assert!(err_msg.contains("failed to open VBA project as CFB"));
1558    }
1559
1560    #[test]
1561    fn test_vba_module_type_clone() {
1562        let t = VbaModuleType::Standard;
1563        let t2 = t.clone();
1564        assert_eq!(t, t2);
1565    }
1566
1567    #[test]
1568    fn test_vba_module_debug() {
1569        let m = VbaModule {
1570            name: "Module1".to_string(),
1571            source_code: "Sub Test()\nEnd Sub".to_string(),
1572            module_type: VbaModuleType::Standard,
1573        };
1574        let debug = format!("{:?}", m);
1575        assert!(debug.contains("Module1"));
1576    }
1577
1578    #[test]
1579    fn test_vba_roundtrip_with_xlsm() {
1580        use std::io::{Read as _, Write as _};
1581
1582        // Build a minimal CFB container with a VBA dir stream and a module
1583        let vba_bin = build_test_vba_project();
1584
1585        // Create a valid xlsx using the Workbook API, then inject vbaProject.bin
1586        let base_wb = crate::workbook::Workbook::new();
1587        let base_buf = base_wb.save_to_buffer().unwrap();
1588
1589        // Rewrite the ZIP, adding the vbaProject.bin entry
1590        let mut buf = Vec::new();
1591        {
1592            let base_cursor = std::io::Cursor::new(&base_buf);
1593            let mut base_archive = zip::ZipArchive::new(base_cursor).unwrap();
1594
1595            let out_cursor = std::io::Cursor::new(&mut buf);
1596            let mut zip = zip::ZipWriter::new(out_cursor);
1597            let options = zip::write::SimpleFileOptions::default()
1598                .compression_method(zip::CompressionMethod::Deflated);
1599
1600            for i in 0..base_archive.len() {
1601                let mut entry = base_archive.by_index(i).unwrap();
1602                let name = entry.name().to_string();
1603                zip.start_file(&name, options).unwrap();
1604                let mut data = Vec::new();
1605                entry.read_to_end(&mut data).unwrap();
1606                zip.write_all(&data).unwrap();
1607            }
1608
1609            zip.start_file("xl/vbaProject.bin", options).unwrap();
1610            zip.write_all(&vba_bin).unwrap();
1611            zip.finish().unwrap();
1612        }
1613
1614        // Open and extract
1615        let opts = crate::workbook::OpenOptions::new()
1616            .read_mode(crate::workbook::ReadMode::Eager)
1617            .aux_parts(crate::workbook::AuxParts::EagerLoad);
1618        let wb = crate::workbook::Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
1619
1620        // Raw VBA project should be available
1621        let raw = wb.get_vba_project();
1622        assert!(raw.is_some(), "VBA project binary should be present");
1623        assert_eq!(raw.unwrap(), vba_bin);
1624    }
1625
1626    #[test]
1627    fn test_xlsx_without_vba_returns_none() {
1628        let wb = crate::workbook::Workbook::new();
1629        assert!(wb.get_vba_project().is_none());
1630        assert!(wb.get_vba_modules().unwrap().is_none());
1631    }
1632
1633    #[test]
1634    fn test_xlsx_roundtrip_no_vba() {
1635        let wb = crate::workbook::Workbook::new();
1636        let buf = wb.save_to_buffer().unwrap();
1637        let wb2 = crate::workbook::Workbook::open_from_buffer(&buf).unwrap();
1638        assert!(wb2.get_vba_project().is_none());
1639    }
1640
1641    #[test]
1642    fn test_get_vba_modules_from_test_project() {
1643        use std::io::{Read as _, Write as _};
1644
1645        let vba_bin = build_test_vba_project();
1646
1647        // Create a valid xlsx, then inject vbaProject.bin
1648        let base_wb = crate::workbook::Workbook::new();
1649        let base_buf = base_wb.save_to_buffer().unwrap();
1650
1651        let mut buf = Vec::new();
1652        {
1653            let base_cursor = std::io::Cursor::new(&base_buf);
1654            let mut base_archive = zip::ZipArchive::new(base_cursor).unwrap();
1655
1656            let out_cursor = std::io::Cursor::new(&mut buf);
1657            let mut zip = zip::ZipWriter::new(out_cursor);
1658            let options = zip::write::SimpleFileOptions::default()
1659                .compression_method(zip::CompressionMethod::Deflated);
1660
1661            for i in 0..base_archive.len() {
1662                let mut entry = base_archive.by_index(i).unwrap();
1663                let name = entry.name().to_string();
1664                zip.start_file(&name, options).unwrap();
1665                let mut data = Vec::new();
1666                entry.read_to_end(&mut data).unwrap();
1667                zip.write_all(&data).unwrap();
1668            }
1669
1670            zip.start_file("xl/vbaProject.bin", options).unwrap();
1671            zip.write_all(&vba_bin).unwrap();
1672            zip.finish().unwrap();
1673        }
1674
1675        let opts = crate::workbook::OpenOptions::new()
1676            .read_mode(crate::workbook::ReadMode::Eager)
1677            .aux_parts(crate::workbook::AuxParts::EagerLoad);
1678        let wb = crate::workbook::Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
1679        let project = wb.get_vba_modules().unwrap();
1680        assert!(project.is_some(), "should have VBA modules");
1681        let project = project.unwrap();
1682        assert_eq!(project.modules.len(), 1);
1683        assert_eq!(project.modules[0].name, "Module1");
1684        assert_eq!(project.modules[0].module_type, VbaModuleType::Standard);
1685        assert!(
1686            project.modules[0].source_code.contains("Sub Hello()"),
1687            "source should contain Sub Hello(), got: {}",
1688            project.modules[0].source_code
1689        );
1690    }
1691
1692    #[test]
1693    fn test_vba_project_preserved_in_save_roundtrip() {
1694        use std::io::{Read as _, Write as _};
1695
1696        let vba_bin = build_test_vba_project();
1697
1698        let base_wb = crate::workbook::Workbook::new();
1699        let base_buf = base_wb.save_to_buffer().unwrap();
1700
1701        let mut buf = Vec::new();
1702        {
1703            let base_cursor = std::io::Cursor::new(&base_buf);
1704            let mut base_archive = zip::ZipArchive::new(base_cursor).unwrap();
1705
1706            let out_cursor = std::io::Cursor::new(&mut buf);
1707            let mut zip = zip::ZipWriter::new(out_cursor);
1708            let options = zip::write::SimpleFileOptions::default()
1709                .compression_method(zip::CompressionMethod::Deflated);
1710
1711            for i in 0..base_archive.len() {
1712                let mut entry = base_archive.by_index(i).unwrap();
1713                let name = entry.name().to_string();
1714                zip.start_file(&name, options).unwrap();
1715                let mut data = Vec::new();
1716                entry.read_to_end(&mut data).unwrap();
1717                zip.write_all(&data).unwrap();
1718            }
1719
1720            zip.start_file("xl/vbaProject.bin", options).unwrap();
1721            zip.write_all(&vba_bin).unwrap();
1722            zip.finish().unwrap();
1723        }
1724
1725        // Open, then save again
1726        let opts = crate::workbook::OpenOptions::new()
1727            .read_mode(crate::workbook::ReadMode::Eager)
1728            .aux_parts(crate::workbook::AuxParts::EagerLoad);
1729        let mut wb = crate::workbook::Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
1730        wb.set_format(crate::workbook::WorkbookFormat::Xlsm);
1731        let saved_buf = wb.save_to_buffer().unwrap();
1732
1733        // Re-open and verify VBA is preserved
1734        let wb2 =
1735            crate::workbook::Workbook::open_from_buffer_with_options(&saved_buf, &opts).unwrap();
1736        let raw = wb2.get_vba_project();
1737        assert!(raw.is_some(), "VBA project should survive save roundtrip");
1738        assert_eq!(raw.unwrap(), vba_bin);
1739
1740        // Modules should still be extractable
1741        let project = wb2.get_vba_modules().unwrap().unwrap();
1742        assert_eq!(project.modules.len(), 1);
1743        assert_eq!(project.modules[0].name, "Module1");
1744    }
1745
1746    /// Build a minimal CFB container that looks like a VBA project.
1747    fn build_test_vba_project() -> Vec<u8> {
1748        let mut buf = Vec::new();
1749        let cursor = std::io::Cursor::new(&mut buf);
1750        let mut cfb = cfb::CompoundFile::create(cursor).unwrap();
1751
1752        // Create VBA storage
1753        cfb.create_storage("/VBA").unwrap();
1754
1755        // Build a minimal dir stream
1756        let dir_data = build_minimal_dir_stream("Module1");
1757
1758        // Compress the dir stream
1759        let compressed_dir = compress_for_test(&dir_data);
1760
1761        // Write dir stream
1762        {
1763            let mut stream = cfb.create_stream("/VBA/dir").unwrap();
1764            std::io::Write::write_all(&mut stream, &compressed_dir).unwrap();
1765        }
1766
1767        // Build module source: "Sub Hello()\nEnd Sub\n"
1768        let source = b"Sub Hello()\r\nEnd Sub\r\n";
1769        let compressed_source = compress_for_test(source);
1770
1771        // The module stream has 0 bytes of performance cache + compressed source.
1772        // (text_offset = 0 in the dir stream)
1773        {
1774            let mut stream = cfb.create_stream("/VBA/Module1").unwrap();
1775            std::io::Write::write_all(&mut stream, &compressed_source).unwrap();
1776        }
1777
1778        // Create _VBA_PROJECT stream (required for validity, can be minimal)
1779        {
1780            let mut stream = cfb.create_stream("/VBA/_VBA_PROJECT").unwrap();
1781            // Minimal header: version bytes
1782            let header = [0xCC, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00];
1783            std::io::Write::write_all(&mut stream, &header).unwrap();
1784        }
1785
1786        cfb.flush().unwrap();
1787        buf
1788    }
1789
1790    /// Build a minimal dir stream binary for one standard module.
1791    fn build_minimal_dir_stream(module_name: &str) -> Vec<u8> {
1792        let mut data = Vec::new();
1793        let name_bytes = module_name.as_bytes();
1794
1795        // PROJECTSYSKIND record (0x0001): 4 bytes, value = 1 (Win32)
1796        write_dir_record(&mut data, 0x0001, &1u32.to_le_bytes());
1797
1798        // PROJECTLCID record (0x0002): 4 bytes
1799        write_dir_record(&mut data, 0x0002, &0x0409u32.to_le_bytes());
1800
1801        // PROJECTLCIDINVOKE record (0x0014): 4 bytes
1802        write_dir_record(&mut data, 0x0014, &0x0409u32.to_le_bytes());
1803
1804        // PROJECTCODEPAGE record (0x0003): 2 bytes (1252 = Windows-1252)
1805        write_dir_record(&mut data, 0x0003, &1252u16.to_le_bytes());
1806
1807        // PROJECTNAME record (0x0004)
1808        write_dir_record(&mut data, 0x0004, b"VBAProject");
1809
1810        // PROJECTDOCSTRING record (0x0005): empty
1811        write_dir_record(&mut data, 0x0005, &[]);
1812        // Unicode variant (0x0040): empty
1813        write_dir_record(&mut data, 0x0040, &[]);
1814
1815        // PROJECTHELPFILEPATH record (0x0006): empty
1816        write_dir_record(&mut data, 0x0006, &[]);
1817        // Unicode variant (0x003D): empty
1818        write_dir_record(&mut data, 0x003D, &[]);
1819
1820        // PROJECTHELPCONTEXT (0x0007): 4 bytes
1821        write_dir_record(&mut data, 0x0007, &0u32.to_le_bytes());
1822
1823        // PROJECTLIBFLAGS (0x0008): 4 bytes
1824        write_dir_record(&mut data, 0x0008, &0u32.to_le_bytes());
1825
1826        // PROJECTVERSION (0x0009): 4 + 2 bytes (major + minor)
1827        let mut version = Vec::new();
1828        version.extend_from_slice(&1u32.to_le_bytes());
1829        version.extend_from_slice(&0u16.to_le_bytes());
1830        // Version record is special: id=0x0009, size=4 for major, then 2 bytes minor appended
1831        data.extend_from_slice(&0x0009u16.to_le_bytes());
1832        data.extend_from_slice(&4u32.to_le_bytes());
1833        data.extend_from_slice(&version);
1834
1835        // PROJECTCONSTANTS (0x000C): empty
1836        write_dir_record(&mut data, 0x000C, &[]);
1837        // Unicode variant (0x003C): empty
1838        write_dir_record(&mut data, 0x003C, &[]);
1839
1840        // MODULES count record: id=0x000F, size=2
1841        let module_count: u16 = 1;
1842        write_dir_record(&mut data, 0x000F, &module_count.to_le_bytes());
1843
1844        // PROJECTCOOKIE record (0x0013): 2 bytes
1845        write_dir_record(&mut data, 0x0013, &0u16.to_le_bytes());
1846
1847        // MODULE_NAME record (0x0019)
1848        write_dir_record(&mut data, 0x0019, name_bytes);
1849
1850        // MODULE_STREAM_NAME record (0x001A)
1851        write_dir_record(&mut data, 0x001A, name_bytes);
1852        // Unicode variant (0x0032)
1853        let name_utf16: Vec<u8> = module_name
1854            .encode_utf16()
1855            .flat_map(|c| c.to_le_bytes())
1856            .collect();
1857        write_dir_record(&mut data, 0x0032, &name_utf16);
1858
1859        // MODULE_OFFSET record (0x0031): 4 bytes (offset = 0)
1860        write_dir_record(&mut data, 0x0031, &0u32.to_le_bytes());
1861
1862        // MODULE_TYPE procedural (0x0021): 0 bytes
1863        write_dir_record(&mut data, 0x0021, &[]);
1864
1865        // MODULE_TERMINATOR (0x002B): 0 bytes
1866        write_dir_record(&mut data, 0x002B, &[]);
1867
1868        // End of modules
1869        // Global TERMINATOR (0x0010): 0 bytes
1870        write_dir_record(&mut data, 0x0010, &[]);
1871
1872        data
1873    }
1874
1875    fn write_dir_record(buf: &mut Vec<u8>, id: u16, data: &[u8]) {
1876        buf.extend_from_slice(&id.to_le_bytes());
1877        buf.extend_from_slice(&(data.len() as u32).to_le_bytes());
1878        buf.extend_from_slice(data);
1879    }
1880
1881    fn compressed_copy_stream(literals: &[u8], offset: usize, length: usize) -> Vec<u8> {
1882        let mut payload = Vec::new();
1883        let mut literal_pos = 0;
1884        while literals.len() - literal_pos >= 8 {
1885            payload.push(0);
1886            payload.extend_from_slice(&literals[literal_pos..literal_pos + 8]);
1887            literal_pos += 8;
1888        }
1889
1890        let remaining = literals.len() - literal_pos;
1891        payload.push(1 << remaining);
1892        payload.extend_from_slice(&literals[literal_pos..]);
1893
1894        let offset_bits = offset_bit_count(literals.len());
1895        let length_bits = 16 - offset_bits;
1896        let token = (((offset - 1) as u16) << length_bits) | (length - 3) as u16;
1897        payload.extend_from_slice(&token.to_le_bytes());
1898
1899        let header = 0x8000 | ((payload.len() as u16 - 1) & 0x0FFF);
1900        let mut stream = vec![0x01];
1901        stream.extend_from_slice(&header.to_le_bytes());
1902        stream.extend_from_slice(&payload);
1903        stream
1904    }
1905
1906    /// Minimal MS-OVBA "compression" that produces an uncompressed container.
1907    /// Signature 0x01 + one uncompressed chunk per 4096 bytes.
1908    fn compress_for_test(data: &[u8]) -> Vec<u8> {
1909        let mut result = vec![0x01u8]; // signature
1910        let mut pos = 0;
1911        while pos < data.len() {
1912            let chunk_len = (data.len() - pos).min(4096);
1913            let chunk_data = &data[pos..pos + chunk_len];
1914            // An uncompressed chunk always carries a full 4096-byte payload.
1915            let header: u16 = 0x0FFF;
1916            result.extend_from_slice(&header.to_le_bytes());
1917            result.extend_from_slice(chunk_data);
1918            // Pad to 4096 if needed
1919            for _ in chunk_len..4096 {
1920                result.push(0x00);
1921            }
1922            pos += chunk_len;
1923        }
1924        result
1925    }
1926}