wim-parser 0.1.1

A Rust library for parsing Windows Imaging (WIM) files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
use anyhow::{Context, Result};
use std::fs::File;
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::path::Path;
use tracing::{debug, info};

// 性能优化导入
use encoding_rs::UTF_16LE;
use quick_xml::events::Event;
use quick_xml::Reader;

/// 字符串池用于减少内存分配
#[derive(Debug)]
struct StringPool {
    pool: Vec<String>,
    index: usize,
}

#[allow(dead_code)]
impl StringPool {
    fn new() -> Self {
        Self {
            pool: Vec::with_capacity(32), // 预分配32个字符串
            index: 0,
        }
    }

    fn get_string(&mut self) -> &mut String {
        if self.index >= self.pool.len() {
            self.pool.push(String::with_capacity(256)); // 预分配容量
        }
        let string = &mut self.pool[self.index];
        string.clear();
        self.index += 1;
        string
    }

    fn reset(&mut self) {
        self.index = 0;
        // 保留字符串对象,只重置索引
    }
}

/// WIM 文件头结构体 (WIMHEADER_V1_PACKED)
/// 总大小:204 字节
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct WimHeader {
    /// 文件签名 "MSWIM\x00\x00\x00"
    pub signature: [u8; 8],
    /// 文件头大小
    pub header_size: u32,
    /// 格式版本
    pub format_version: u32,
    /// 文件标志
    pub file_flags: u32,
    /// 压缩文件大小
    pub compressed_size: u32,
    /// 唯一标识符 (GUID)
    pub guid: [u8; 16],
    /// 段号
    pub segment_number: u16,
    /// 段总数
    pub total_segments: u16,
    /// 镜像数量
    pub image_count: u32,
    /// 偏移表文件资源
    pub offset_table_resource: FileResourceEntry,
    /// XML 数据文件资源
    pub xml_data_resource: FileResourceEntry,
    /// 引导元数据文件资源
    pub boot_metadata_resource: FileResourceEntry,
    /// 可引导镜像索引
    pub bootable_image_index: u32,
    /// 完整性数据文件资源
    pub integrity_resource: FileResourceEntry,
}

/// 文件资源条目结构体 (_RESHDR_DISK_SHORT)
/// 总大小:24 字节
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct FileResourceEntry {
    /// 资源大小 (7 字节)
    pub size: u64,
    /// 资源标志 (1 字节)
    pub flags: u8,
    /// 资源偏移 (8 字节)
    pub offset: u64,
    /// 原始大小 (8 字节)
    pub original_size: u64,
}

/// 文件资源条目标志
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct ResourceFlags;

#[allow(dead_code)]
impl ResourceFlags {
    pub const FREE: u8 = 0x01; // 条目空闲
    pub const METADATA: u8 = 0x02; // 包含元数据
    pub const COMPRESSED: u8 = 0x04; // 已压缩
    pub const SPANNED: u8 = 0x08; // 跨段
}

/// 文件标志
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct FileFlags;

#[allow(dead_code)]
impl FileFlags {
    pub const COMPRESSION: u32 = 0x00000002; // 资源已压缩
    pub const READONLY: u32 = 0x00000004; // 只读
    pub const SPANNED: u32 = 0x00000008; // 跨段
    pub const RESOURCE_ONLY: u32 = 0x00000010; // 仅包含文件资源
    pub const METADATA_ONLY: u32 = 0x00000020; // 仅包含元数据
    pub const COMPRESS_XPRESS: u32 = 0x00020000; // XPRESS 压缩
    pub const COMPRESS_LZX: u32 = 0x00040000; // LZX 压缩
}

/// 镜像信息结构体
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct ImageInfo {
    /// 镜像索引
    pub index: u32,
    /// 镜像名称
    pub name: String,
    /// 镜像描述
    pub description: String,
    /// 目录数量
    pub dir_count: u32,
    /// 文件数量
    pub file_count: u32,
    /// 总字节数
    pub total_bytes: u64,
    /// 创建时间
    pub creation_time: Option<u64>,
    /// 最后修改时间
    pub last_modification_time: Option<u64>,
    /// 版本信息
    pub version: Option<String>,
    /// 架构信息
    pub architecture: Option<String>,
}

#[allow(dead_code)]
impl ImageInfo {
    /// 创建新的ImageInfo实例(用于优化的XML解析)
    pub fn new_with_index(index: u32) -> Self {
        Self {
            index,
            name: String::new(),
            description: String::new(),
            dir_count: 0,
            file_count: 0,
            total_bytes: 0,
            creation_time: None,
            last_modification_time: None,
            version: None,
            architecture: None,
        }
    }

    /// 高效设置字段值(避免多次字符串分配)
    pub fn set_field(&mut self, tag: &str, value: &str) {
        match tag {
            "DISPLAYNAME" => self.name = value.to_string(),
            "DISPLAYDESCRIPTION" => self.description = value.to_string(),
            "DIRCOUNT" => self.dir_count = value.parse().unwrap_or(0),
            "FILECOUNT" => self.file_count = value.parse().unwrap_or(0),
            "TOTALBYTES" => self.total_bytes = value.parse().unwrap_or(0),
            "ARCH" => {
                self.architecture = match value {
                    "0" => Some("x86".to_string()),
                    "9" => Some("x64".to_string()),
                    "5" => Some("ARM".to_string()),
                    "12" => Some("ARM64".to_string()),
                    _ => None,
                };
            }
            _ => {} // 忽略其他标签
        }
    }

    /// 根据名称和描述推断版本和架构信息
    pub fn infer_version_and_arch(&mut self) {
        let combined_text = format!("{} {}", self.name, self.description).to_lowercase();

        // 推断版本信息
        if self.version.is_none() {
            self.version = if combined_text.contains("windows 11") {
                Some("Windows 11".to_string())
            } else if combined_text.contains("windows 10") {
                Some("Windows 10".to_string())
            } else if combined_text.contains("windows server 2022") {
                Some("Windows Server 2022".to_string())
            } else if combined_text.contains("windows server 2019") {
                Some("Windows Server 2019".to_string())
            } else if combined_text.contains("windows server") {
                Some("Windows Server".to_string())
            } else if combined_text.contains("windows") {
                Some("Windows".to_string())
            } else {
                None
            };
        }

        // 推断架构信息(仅在未从XML ARCH标签获取时)
        if self.architecture.is_none() {
            self.architecture = if combined_text.contains("x64") || combined_text.contains("amd64")
            {
                Some("x64".to_string())
            } else if combined_text.contains("x86") {
                Some("x86".to_string())
            } else if combined_text.contains("arm64") {
                Some("ARM64".to_string())
            } else {
                None
            };
        }
    }
}

/// WIM 文件解析器
#[allow(dead_code)]
pub struct WimParser {
    file: BufReader<File>,
    header: Option<WimHeader>,
    images: Vec<ImageInfo>,
    string_pool: StringPool,
}

#[allow(dead_code)]
impl WimParser {
    /// 创建新的 WIM 解析器
    pub fn new<P: AsRef<Path>>(wim_path: P) -> Result<Self> {
        let file = File::open(wim_path.as_ref())
            .with_context(|| format!("无法打开 WIM 文件: {}", wim_path.as_ref().display()))?;

        let buffered_file = BufReader::with_capacity(64 * 1024, file); // 64KB缓冲区

        debug!("创建 WIM 解析器: {}", wim_path.as_ref().display());

        Ok(Self {
            file: buffered_file,
            header: None,
            images: Vec::with_capacity(8), // 预分配镜像容量
            string_pool: StringPool::new(),
        })
    }

    /// 创建用于测试的 WIM 解析器(不需要实际文件)
    #[doc(hidden)]
    #[allow(dead_code)]
    pub fn new_for_test(file: File) -> Self {
        Self {
            file: BufReader::new(file),
            header: None,
            images: Vec::with_capacity(8),
            string_pool: StringPool::new(),
        }
    }

    /// 读取并解析 WIM 文件头
    pub fn read_header(&mut self) -> Result<&WimHeader> {
        if self.header.is_some() {
            return Ok(self.header.as_ref().unwrap());
        }

        debug!("开始读取 WIM 文件头");

        // 跳转到文件开始
        self.file.seek(SeekFrom::Start(0))?;

        // 读取 204 字节的文件头
        let mut header_buffer = vec![0u8; 204];
        self.file
            .read_exact(&mut header_buffer)
            .context("读取 WIM 文件头失败")?;

        let header = self.parse_header_buffer(&header_buffer)?;

        // 验证签名
        if &header.signature != b"MSWIM\x00\x00\x00" {
            return Err(anyhow::anyhow!("无效的 WIM 文件签名"));
        }

        info!(
            "成功读取 WIM 文件头 - 版本: {}, 镜像数: {}",
            header.format_version, header.image_count
        );

        self.header = Some(header);
        Ok(self.header.as_ref().unwrap())
    }

    /// 解析文件头缓冲区
    fn parse_header_buffer(&self, buffer: &[u8]) -> Result<WimHeader> {
        use std::convert::TryInto;

        // 辅助函数:从缓冲区读取 little-endian 数值
        let read_u32_le = |offset: usize| -> u32 {
            u32::from_le_bytes(buffer[offset..offset + 4].try_into().unwrap())
        };

        let read_u16_le = |offset: usize| -> u16 {
            u16::from_le_bytes(buffer[offset..offset + 2].try_into().unwrap())
        };

        let read_u64_le = |offset: usize| -> u64 {
            u64::from_le_bytes(buffer[offset..offset + 8].try_into().unwrap())
        };

        // 解析文件资源条目
        let parse_resource_entry = |offset: usize| -> FileResourceEntry {
            // 读取 7 字节的大小 + 1 字节标志
            let size_bytes = &buffer[offset..offset + 7];
            let mut size_array = [0u8; 8];
            size_array[..7].copy_from_slice(size_bytes);
            let size = u64::from_le_bytes(size_array);

            let flags = buffer[offset + 7];
            let offset_val = read_u64_le(offset + 8);
            let original_size = read_u64_le(offset + 16);

            FileResourceEntry {
                size,
                flags,
                offset: offset_val,
                original_size,
            }
        };

        // 解析文件头各个字段
        let mut signature = [0u8; 8];
        signature.copy_from_slice(&buffer[0..8]);

        let header = WimHeader {
            signature,
            header_size: read_u32_le(8),
            format_version: read_u32_le(12),
            file_flags: read_u32_le(16),
            compressed_size: read_u32_le(20),
            guid: buffer[24..40].try_into().unwrap(),
            segment_number: read_u16_le(40),
            total_segments: read_u16_le(42),
            image_count: read_u32_le(44),
            offset_table_resource: parse_resource_entry(48),
            xml_data_resource: parse_resource_entry(72),
            boot_metadata_resource: parse_resource_entry(96),
            bootable_image_index: read_u32_le(120),
            integrity_resource: parse_resource_entry(124),
        };

        debug!(
            "解析 WIM 头部完成 - 镜像数: {}, 文件标志: 0x{:08X}",
            header.image_count, header.file_flags
        );

        Ok(header)
    }

    /// 读取并解析 XML 数据
    pub fn read_xml_data(&mut self) -> Result<()> {
        // 确保文件头已读取
        if self.header.is_none() {
            self.read_header()?;
        }

        let header = self.header.as_ref().unwrap();

        // 检查 XML 数据资源是否存在
        if header.xml_data_resource.size == 0 {
            return Err(anyhow::anyhow!("WIM 文件中没有 XML 数据资源"));
        }

        debug!(
            "开始读取 XML 数据,偏移: {}, 大小: {}",
            header.xml_data_resource.offset, header.xml_data_resource.size
        );

        // 跳转到 XML 数据位置
        self.file
            .seek(SeekFrom::Start(header.xml_data_resource.offset))?;

        // 读取 XML 数据
        let mut xml_buffer = vec![0u8; header.xml_data_resource.size as usize];
        self.file
            .read_exact(&mut xml_buffer)
            .context("读取 XML 数据失败")?;

        // 解析 XML 数据
        self.parse_xml_data(&xml_buffer)?;

        info!("成功解析 {} 个镜像的信息", self.images.len());
        Ok(())
    }

    /// 解析 XML 数据
    fn parse_xml_data(&mut self, xml_buffer: &[u8]) -> Result<()> {
        // XML 数据以 UTF-16 LE BOM 开始
        if xml_buffer.len() < 2 {
            return Err(anyhow::anyhow!("XML 数据太短"));
        }

        // 检查 BOM (0xFEFF)
        if xml_buffer[0] != 0xFF || xml_buffer[1] != 0xFE {
            return Err(anyhow::anyhow!("无效的 XML 数据 BOM"));
        }

        // 将 UTF-16 LE 转换为 UTF-8
        let xml_utf16_data = &xml_buffer[2..]; // 跳过 BOM

        // 确保数据长度为偶数(UTF-16 每个字符 2 字节)
        if xml_utf16_data.len() % 2 != 0 {
            return Err(anyhow::anyhow!("XML UTF-16 数据长度不是偶数"));
        }

        // 转换为 u16 数组
        let mut utf16_chars = Vec::new();
        for chunk in xml_utf16_data.chunks_exact(2) {
            let char_val = u16::from_le_bytes([chunk[0], chunk[1]]);
            utf16_chars.push(char_val);
        }

        // 转换为 UTF-8 字符串
        let xml_string = String::from_utf16(&utf16_chars).context("无法将 XML 数据转换为 UTF-8")?;

        debug!("XML 数据长度: {} 字符", xml_string.len());

        // 解析 XML 镜像信息
        self.parse_xml_images(&xml_string)?;

        Ok(())
    }

    /// 优化的XML解析函数 - 使用proper XML parser和高效UTF-16解码
    fn parse_xml_data_optimized(&mut self, xml_buffer: &[u8]) -> Result<()> {
        // 检查基本格式
        if xml_buffer.len() < 2 {
            return Err(anyhow::anyhow!("XML 数据太短"));
        }

        // 检查 BOM (0xFEFF)
        if xml_buffer[0] != 0xFF || xml_buffer[1] != 0xFE {
            return Err(anyhow::anyhow!("无效的 XML 数据 BOM"));
        }

        // 使用encoding_rs进行高效UTF-16解码
        let (xml_string, _, had_errors) = UTF_16LE.decode(&xml_buffer[2..]);
        if had_errors {
            return Err(anyhow::anyhow!("UTF-16解码过程中发现错误"));
        }

        debug!("XML 数据长度: {} 字符", xml_string.len());

        // 使用quick-xml进行解析
        self.parse_xml_images_optimized(&xml_string)?;

        Ok(())
    }

    /// 优化的XML镜像解析函数 - 使用quick-xml
    fn parse_xml_images_optimized(&mut self, xml_content: &str) -> Result<()> {
        self.images.clear();

        let mut reader = Reader::from_str(xml_content);
        reader.config_mut().trim_text(true);

        let mut current_image: Option<ImageInfo> = None;
        let mut current_tag = String::new();
        let mut in_windows_section = false;

        loop {
            match reader.read_event() {
                Ok(Event::Start(ref e)) => {
                    match e.name().as_ref() {
                        b"IMAGE" => {
                            // 提取INDEX属性
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"INDEX" {
                                    if let Ok(index_str) = std::str::from_utf8(&attr.value) {
                                        if let Ok(index) = index_str.parse::<u32>() {
                                            current_image = Some(ImageInfo::new_with_index(index));
                                        }
                                    }
                                }
                            }
                        }
                        b"WINDOWS" => {
                            in_windows_section = true;
                        }
                        tag => {
                            current_tag = String::from_utf8_lossy(tag).into_owned();
                        }
                    }
                }
                Ok(Event::Text(e)) => {
                    if let Some(ref mut image) = current_image {
                        // 获取文本内容
                        let text = std::str::from_utf8(&e)?;

                        // 特殊处理WINDOWS节中的ARCH标签
                        if in_windows_section && current_tag == "ARCH" {
                            image.set_field("ARCH", text);
                        } else if !in_windows_section {
                            // 其他标签在非WINDOWS节中处理
                            image.set_field(&current_tag, text);
                        }
                    }
                }
                Ok(Event::End(ref e)) => {
                    match e.name().as_ref() {
                        b"IMAGE" => {
                            if let Some(mut image) = current_image.take() {
                                // 推断版本和架构信息(如果尚未设置)
                                image.infer_version_and_arch();
                                self.images.push(image);
                            }
                        }
                        b"WINDOWS" => {
                            in_windows_section = false;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(anyhow::anyhow!("XML解析错误: {}", e)),
                _ => {}
            }
        }

        info!("优化解析完成:成功解析 {} 个镜像的信息", self.images.len());
        Ok(())
    }

    /// 解析 XML 中的镜像信息
    fn parse_xml_images(&mut self, xml_content: &str) -> Result<()> {
        // 简单的 XML 解析(基于字符串匹配)
        // 在实际生产环境中,建议使用专门的 XML 解析库

        self.images.clear();

        // 查找所有 <IMAGE> 标签
        let mut start_pos = 0;
        while let Some(image_start) = xml_content[start_pos..].find("<IMAGE") {
            let absolute_start = start_pos + image_start;

            // 查找对应的 </IMAGE> 标签
            if let Some(image_end) = xml_content[absolute_start..].find("</IMAGE>") {
                let absolute_end = absolute_start + image_end + 8; // 包含 </IMAGE>
                let image_xml = &xml_content[absolute_start..absolute_end];

                // 解析单个镜像信息
                if let Ok(image_info) = self.parse_single_image_xml(image_xml) {
                    self.images.push(image_info);
                }

                start_pos = absolute_end;
            } else {
                break;
            }
        }

        Ok(())
    }

    /// 解析单个镜像的 XML 信息
    pub fn parse_single_image_xml(&self, image_xml: &str) -> Result<ImageInfo> {
        // 辅助函数:从 XML 中提取标签值
        let extract_tag_value = |xml: &str, tag: &str| -> Option<String> {
            let start_tag = format!("<{tag}>");
            let end_tag = format!("</{tag}>");

            if let Some(start) = xml.find(&start_tag) {
                if let Some(end) = xml.find(&end_tag) {
                    let value_start = start + start_tag.len();
                    if value_start < end {
                        return Some(xml[value_start..end].trim().to_string());
                    }
                }
            }
            None
        };

        // 提取 INDEX 属性
        let index = if let Some(index_start) = image_xml.find("INDEX=\"") {
            let index_value_start = index_start + 7; // "INDEX=\"".len()
            if let Some(index_end) = image_xml[index_value_start..].find("\"") {
                let index_str = &image_xml[index_value_start..index_value_start + index_end];
                index_str.parse().unwrap_or(0)
            } else {
                0
            }
        } else {
            0
        };

        // 提取各种信息
        let name =
            extract_tag_value(image_xml, "DISPLAYNAME").unwrap_or_else(|| format!("Image {index}"));
        let description = extract_tag_value(image_xml, "DISPLAYDESCRIPTION")
            .unwrap_or_else(|| "Unknown".to_string());
        let dir_count = extract_tag_value(image_xml, "DIRCOUNT")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);
        let file_count = extract_tag_value(image_xml, "FILECOUNT")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);
        let total_bytes = extract_tag_value(image_xml, "TOTALBYTES")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0);

        // 尝试从XML中的ARCH标签解析架构信息
        let arch_from_xml = self.parse_arch_from_xml(image_xml);

        // 从名称中提取版本信息,架构信息优先使用XML中的ARCH标签
        let (version, arch_from_name) = self.extract_version_and_arch(&name, &description);
        let architecture = arch_from_xml.or(arch_from_name);

        let image_info = ImageInfo {
            index,
            name,
            description,
            dir_count,
            file_count,
            total_bytes,
            creation_time: None,          // 可以进一步解析 CREATIONTIME
            last_modification_time: None, // 可以进一步解析 LASTMODIFICATIONTIME
            version,
            architecture,
        };

        debug!(
            "解析镜像信息: {} - {} - {} - {:#?}",
            image_info.index, image_info.name, image_info.description, image_info.architecture
        );

        Ok(image_info)
    }

    /// 从镜像名称和描述中提取版本和架构信息
    fn extract_version_and_arch(
        &self,
        name: &str,
        description: &str,
    ) -> (Option<String>, Option<String>) {
        let combined_text = format!("{name} {description}").to_lowercase();

        // 提取版本信息
        let version = if combined_text.contains("windows 11") {
            Some("Windows 11".to_string())
        } else if combined_text.contains("windows 10") {
            Some("Windows 10".to_string())
        } else if combined_text.contains("windows server 2022") {
            Some("Windows Server 2022".to_string())
        } else if combined_text.contains("windows server 2019") {
            Some("Windows Server 2019".to_string())
        } else if combined_text.contains("windows server") {
            Some("Windows Server".to_string())
        } else if combined_text.contains("windows") {
            Some("Windows".to_string())
        } else {
            None
        };

        // 提取架构信息
        let architecture = if combined_text.contains("x64") || combined_text.contains("amd64") {
            Some("x64".to_string())
        } else if combined_text.contains("x86") {
            Some("x86".to_string())
        } else if combined_text.contains("arm64") {
            Some("ARM64".to_string())
        } else {
            None
        };

        (version, architecture)
    }

    /// 从XML中的ARCH标签解析架构信息
    pub fn parse_arch_from_xml(&self, image_xml: &str) -> Option<String> {
        // 辅助函数:从 XML 中提取标签值
        let extract_tag_value = |xml: &str, tag: &str| -> Option<String> {
            let start_tag = format!("<{tag}>");
            let end_tag = format!("</{tag}>");

            if let Some(start) = xml.find(&start_tag) {
                if let Some(end) = xml.find(&end_tag) {
                    let value_start = start + start_tag.len();
                    if value_start < end {
                        return Some(xml[value_start..end].trim().to_string());
                    }
                }
            }
            None
        };

        // 提取ARCH标签值
        if let Some(arch_value) = extract_tag_value(image_xml, "ARCH") {
            match arch_value.as_str() {
                "0" => Some("x86".to_string()),
                "9" => Some("x64".to_string()),
                "5" => Some("ARM".to_string()),
                "12" => Some("ARM64".to_string()),
                _ => {
                    debug!("未知的架构值: {}", arch_value);
                    None
                }
            }
        } else {
            None
        }
    }

    /// 获取所有镜像信息
    pub fn get_images(&self) -> &[ImageInfo] {
        &self.images
    }

    /// 获取指定索引的镜像信息
    #[allow(dead_code)]
    pub fn get_image(&self, index: u32) -> Option<&ImageInfo> {
        self.images.iter().find(|img| img.index == index)
    }

    /// 获取文件头信息
    #[allow(dead_code)]
    pub fn get_header(&self) -> Option<&WimHeader> {
        self.header.as_ref()
    }

    /// 检查是否包含多个镜像
    #[allow(dead_code)]
    pub fn has_multiple_images(&self) -> bool {
        self.header
            .as_ref()
            .map(|h| h.image_count > 1)
            .unwrap_or(false)
    }

    /// 获取镜像数量
    #[allow(dead_code)]
    pub fn get_image_count(&self) -> u32 {
        self.header.as_ref().map(|h| h.image_count).unwrap_or(0)
    }

    /// 检查是否为压缩文件
    #[allow(dead_code)]
    pub fn is_compressed(&self) -> bool {
        self.header
            .as_ref()
            .map(|h| h.file_flags & FileFlags::COMPRESSION != 0)
            .unwrap_or(false)
    }

    /// 获取压缩类型
    #[allow(dead_code)]
    pub fn get_compression_type(&self) -> Option<&'static str> {
        if let Some(header) = &self.header {
            if header.file_flags & FileFlags::COMPRESS_XPRESS != 0 {
                Some("XPRESS")
            } else if header.file_flags & FileFlags::COMPRESS_LZX != 0 {
                Some("LZX")
            } else if header.file_flags & FileFlags::COMPRESSION != 0 {
                Some("Unknown")
            } else {
                None
            }
        } else {
            None
        }
    }

    /// 完整解析 WIM 文件(头部 + XML 数据)
    pub fn parse_full(&mut self) -> Result<()> {
        self.read_header()?;
        self.read_xml_data()?;
        Ok(())
    }
}

impl std::fmt::Display for ImageInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "镜像 {} - {}", self.index, self.name)?;
        if let Some(ref version) = self.version {
            write!(f, " [{version}]")?;
        }
        if let Some(ref arch) = self.architecture {
            write!(f, " [{arch}]")?;
        }
        write!(f, " | 描述: {}", self.description)?;
        write!(
            f,
            " | 文件数: {}, 目录数: {}",
            self.file_count, self.dir_count
        )?;
        write!(f, " | 总大小: {} MB", self.total_bytes / (1024 * 1024))?;
        Ok(())
    }
}

impl std::fmt::Display for WimHeader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "WIM Header:")?;
        writeln!(f, "  Format Version: {}", self.format_version)?;
        writeln!(f, "  File Flags: 0x{:08X}", self.file_flags)?;
        writeln!(f, "  Image Count: {}", self.image_count)?;
        writeln!(
            f,
            "  Segment: {}/{}",
            self.segment_number, self.total_segments
        )?;
        writeln!(f, "  Bootable Image Index: {}", self.bootable_image_index)?;
        Ok(())
    }
}

#[allow(dead_code)]
impl WimParser {
    /// 获取所有镜像的版本摘要
    #[allow(dead_code)]
    pub fn get_version_summary(&self) -> Vec<String> {
        let mut summaries = Vec::new();

        for image in &self.images {
            let mut summary = format!("镜像 {}: {}", image.index, image.name);

            if let Some(ref version) = image.version {
                summary.push_str(&format!(" ({version})"));
            }

            if let Some(ref arch) = image.architecture {
                summary.push_str(&format!(" [{arch}]"));
            }

            summaries.push(summary);
        }

        summaries
    }

    /// 获取主要版本信息(如果有多个镜像,返回最常见的版本)
    pub fn get_primary_version(&self) -> Option<String> {
        if self.images.is_empty() {
            return None;
        }

        // 统计版本出现频率
        let mut version_counts = std::collections::HashMap::new();
        for image in &self.images {
            if let Some(ref version) = image.version {
                *version_counts.entry(version.clone()).or_insert(0) += 1;
            }
        }

        // 找到最常见的版本
        version_counts
            .into_iter()
            .max_by_key(|(_, count)| *count)
            .map(|(version, _)| version)
    }

    /// 获取主要架构信息(如果有多个镜像,返回最常见的架构)
    pub fn get_primary_architecture(&self) -> Option<String> {
        if self.images.is_empty() {
            return None;
        }

        // 统计架构出现频率
        let mut arch_counts = std::collections::HashMap::new();
        for image in &self.images {
            if let Some(ref arch) = image.architecture {
                *arch_counts.entry(arch.clone()).or_insert(0) += 1;
            }
        }

        // 找到最常见的架构
        arch_counts
            .into_iter()
            .max_by_key(|(_, count)| *count)
            .map(|(arch, _)| arch)
    }

    /// 检查是否包含指定版本的镜像
    #[allow(dead_code)]
    pub fn has_version(&self, version: &str) -> bool {
        self.images.iter().any(|img| {
            img.version
                .as_ref()
                .is_some_and(|v| v.to_lowercase().contains(&version.to_lowercase()))
        })
    }

    /// 检查是否包含指定架构的镜像
    #[allow(dead_code)]
    pub fn has_architecture(&self, arch: &str) -> bool {
        self.images.iter().any(|img| {
            img.architecture
                .as_ref()
                .is_some_and(|a| a.to_lowercase().contains(&arch.to_lowercase()))
        })
    }

    /// 获取Windows版本的详细信息
    pub fn get_windows_info(&self) -> Option<WindowsInfo> {
        let primary_version = self.get_primary_version()?;
        let primary_arch = self.get_primary_architecture()?;

        // 检查是否是Windows镜像
        if !primary_version.to_lowercase().contains("windows") {
            return None;
        }

        // 计算总的镜像版本(如Pro, Home, Enterprise等)
        let mut editions = Vec::new();
        for image in &self.images {
            let name_lower = image.name.to_lowercase();
            if name_lower.contains("pro") && !editions.contains(&"Pro".to_string()) {
                editions.push("Pro".to_string());
            } else if name_lower.contains("home") && !editions.contains(&"Home".to_string()) {
                editions.push("Home".to_string());
            } else if name_lower.contains("enterprise")
                && !editions.contains(&"Enterprise".to_string())
            {
                editions.push("Enterprise".to_string());
            } else if name_lower.contains("education")
                && !editions.contains(&"Education".to_string())
            {
                editions.push("Education".to_string());
            }
        }

        Some(WindowsInfo {
            version: primary_version,
            architecture: primary_arch,
            editions,
            image_count: self.images.len() as u32,
            total_size: self.images.iter().map(|img| img.total_bytes).sum(),
        })
    }
}

/// Windows 版本信息摘要
#[derive(Debug, Clone)]
pub struct WindowsInfo {
    pub version: String,
    pub architecture: String,
    pub editions: Vec<String>,
    pub image_count: u32,
    pub total_size: u64,
}

impl std::fmt::Display for WindowsInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} ({})", self.version, self.architecture)?;
        if !self.editions.is_empty() {
            write!(f, " - 版本: {}", self.editions.join(", "))?;
        }
        write!(f, " | 镜像数量: {}", self.image_count)?;
        write!(f, " | 总大小: {} MB", self.total_size / (1024 * 1024))?;
        Ok(())
    }
}

// 基准测试和测试辅助函数
#[cfg(any(test, feature = "benchmarking"))]
impl WimParser {
    /// 测试用:直接解析XML数据(当前实现)
    pub fn parse_xml_data_for_bench(&mut self, xml_buffer: &[u8]) -> Result<()> {
        self.parse_xml_data(xml_buffer)
    }

    /// 测试用:直接解析XML数据(优化实现)
    pub fn parse_xml_data_optimized_for_bench(&mut self, xml_buffer: &[u8]) -> Result<()> {
        self.parse_xml_data_optimized(xml_buffer)
    }

    /// 测试用:切换到优化解析模式
    pub fn use_optimized_parsing(&mut self, xml_buffer: &[u8]) -> Result<()> {
        self.parse_xml_data_optimized(xml_buffer)
    }
}