dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
//! Resource data encoding for .NET resource files and embedded resources.
//!
//! This module provides comprehensive encoding functionality for creating .NET resource files
//! and managing embedded resource data within assemblies. It supports the complete .NET resource
//! type system and handles proper alignment and format compliance according to
//! the .NET resource file specification.
//!
//! # Architecture
//!
//! The encoding system implements a layered approach to resource data creation:
//!
//! ## Format Support
//! - **.NET Resource File Format**: Complete support for .resources file generation
//! - **Embedded Resource Data**: Direct binary data embedding in assemblies
//! - **Resource Alignment**: Configurable alignment for optimal performance
//!
//! ## Encoding Pipeline
//! The encoding process follows these stages:
//! 1. **Resource Registration**: Add individual resources with names and data
//! 2. **Type Analysis**: Determine optimal encoding for each resource type
//! 3. **Format Selection**: Choose between .NET resource format or raw binary
//! 4. **Alignment Processing**: Apply proper alignment constraints
//! 5. **Serialization**: Write final binary data with proper structure
//!
//! ## Optimization Strategies
//! For resource optimization:
//! - **Duplicate Detection**: Identify and deduplicate identical resource data
//! - **Alignment Optimization**: Balance size and performance requirements
//! - **Efficient Encoding**: Optimal encoding of resource metadata
//!
//! # Key Components
//!
//! - [`crate::metadata::resources::DotNetResourceEncoder`] - Main encoder for resource data creation
//! - [`crate::metadata::resources::DotNetResourceEncoder`] - Specialized encoder for .NET resource file format
//!
//! # Usage Examples
//!
//! ## Basic Resource Data Encoding
//!
//! ```
//! use dotscope::metadata::resources::DotNetResourceEncoder;
//!
//! let mut encoder = DotNetResourceEncoder::new();
//!
//! // Add various resource types
//! encoder.add_string("AppName", "My Application")?;
//! encoder.add_int32("Version", 1)?;
//! encoder.add_byte_array("IconData", &[0x89, 0x50, 0x4E, 0x47])?;
//!
//! // Generate encoded resource data
//! let resource_data = encoder.encode_dotnet_format()?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## .NET Resource File Creation
//!
//! ```
//! use dotscope::metadata::resources::DotNetResourceEncoder;
//!
//! let mut encoder = DotNetResourceEncoder::new();
//!
//! // Add strongly-typed resources
//! encoder.add_string("WelcomeMessage", "Welcome to the application!")?;
//! encoder.add_int32("MaxConnections", 100)?;
//! encoder.add_byte_array("DefaultConfig", &[1, 2, 3, 4])?;
//!
//! // Generate .NET resource file format
//! let resource_file = encoder.encode_dotnet_format()?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//!
//! # Error Handling
//!
//! This module defines resource encoding-specific error handling:
//! - **Invalid Resource Types**: When resource data cannot be encoded in the target format
//! - **Alignment Violations**: When resource data cannot meet alignment requirements
//! - **Format Compliance**: When generated data violates .NET resource format specifications
//!
//! All encoding operations return [`crate::Result<Vec<u8>>`] and follow consistent error patterns.
//!
//! # Thread Safety
//!
//! The [`crate::metadata::resources::encoder::DotNetResourceEncoder`] is not [`Send`] or [`Sync`] due to internal
//! mutable state. For concurrent encoding, create separate encoder instances per thread
//! or use the stateless encoding functions for simple scenarios.
//!
//! # Integration
//!
//! This module integrates with:
//! - [`crate::metadata::resources::types`] - For resource type definitions and parsing compatibility
//! - [`crate::metadata::resources::parser`] - For validation and round-trip testing
//! - [`crate::cilassembly::CilAssembly`] - For embedding resources in assembly modification pipeline
//! - [`crate::file::io`] - For 7-bit encoded integer encoding and binary I/O utilities
//!
//! # References
//!
//! - [.NET Resource File Format Specification](https://docs.microsoft.com/en-us/dotnet/framework/resources/)
//! - [.NET Binary Format Data Structure](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nrbf/)
//! - Microsoft .NET Framework Resource Management Documentation

use crate::{
    metadata::resources::{ResourceType, RESOURCE_MAGIC},
    utils::{compressed_uint_size, to_u32, write_7bit_encoded_int, write_compressed_uint},
    Error, Result,
};
use std::collections::BTreeMap;

/// Computes the hash value for a resource name using the official .NET hash function.
///
/// This hash function MUST match the one used by the .NET runtime exactly
/// (from FastResourceComparer.cs) to ensure proper resource lookup.
///
/// # Arguments
///
/// * `key` - The resource name to hash
///
/// # Returns
///
/// Returns the 32-bit hash value used in .NET resource files.
fn compute_resource_hash(key: &str) -> u32 {
    // This is the official .NET hash function from FastResourceComparer.cs
    // It MUST match exactly for compatibility
    let mut hash = 5381u32;
    for ch in key.chars() {
        hash = hash.wrapping_mul(33).wrapping_add(ch as u32);
    }
    hash
}

/// Specialized encoder for .NET resource file format.
///
/// The [`crate::metadata::resources::encoder::DotNetResourceEncoder`] creates resource files compatible with
/// the .NET resource system, including proper magic numbers, type headers, and
/// data serialization according to the .NET binary format specification.
///
/// # .NET Resource Format
///
/// The .NET resource format includes:
/// 1. **Magic Number**: `0xBEEFCACE` to identify the format
/// 2. **Version Information**: Resource format version numbers
/// 3. **Type Table**: Names and indices of resource types used
/// 4. **Resource Table**: Names and data offsets for each resource
/// 5. **Data Section**: Actual resource data with type information
///
/// # Usage Examples
///
/// ```
/// use dotscope::metadata::resources::DotNetResourceEncoder;
///
/// let mut encoder = DotNetResourceEncoder::new();
///
/// // Add various .NET resource types
/// encoder.add_string("WelcomeMessage", "Welcome to the application!")?;
/// encoder.add_int32("MaxRetries", 3)?;
/// encoder.add_boolean("DebugMode", true)?;
/// encoder.add_byte_array("ConfigData", &[1, 2, 3, 4])?;
///
/// // Generate .NET resource file
/// let resource_file = encoder.encode_dotnet_format()?;
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// # Thread Safety
///
/// This type is not [`Send`] or [`Sync`] because it maintains mutable state
/// during resource building. Create separate instances for concurrent encoding.
#[derive(Debug, Clone)]
pub struct DotNetResourceEncoder {
    /// Collection of typed resources
    resources: Vec<(String, ResourceType)>,
    /// Resource format version
    version: u32,
}

impl DotNetResourceEncoder {
    /// Creates a new .NET resource encoder.
    ///
    /// Initializes an empty encoder configured for .NET resource file format
    /// generation with the current format version.
    ///
    /// # Returns
    ///
    /// Returns a new [`crate::metadata::resources::encoder::DotNetResourceEncoder`] instance ready for resource addition.
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// assert_eq!(encoder.resource_count(), 0);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        DotNetResourceEncoder {
            resources: Vec::new(),
            version: 2, // Microsoft ResourceWriter uses version 2
        }
    }

    /// Adds a string resource.
    ///
    /// Registers a string value with the specified name. String resources are
    /// encoded using the .NET string serialization format.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - String value to store
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_string("ApplicationName", "My Application")?;
    /// encoder.add_string("Version", "1.0.0")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_string(&mut self, name: &str, value: &str) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::String(value.to_string())));
        Ok(())
    }

    /// Adds a 32-bit integer resource.
    ///
    /// Registers an integer value with the specified name. Integer resources
    /// use the .NET Int32 serialization format.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - Integer value to store
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_int32("MaxConnections", 100)?;
    /// encoder.add_int32("TimeoutSeconds", 30)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_int32(&mut self, name: &str, value: i32) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::Int32(value)));
        Ok(())
    }

    /// Adds a boolean resource.
    ///
    /// Registers a boolean value with the specified name. Boolean resources
    /// use the .NET Boolean serialization format.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - Boolean value to store
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_boolean("DebugMode", true)?;
    /// encoder.add_boolean("EnableLogging", false)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_boolean(&mut self, name: &str, value: bool) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::Boolean(value)));
        Ok(())
    }

    /// Adds a byte array resource.
    ///
    /// Registers binary data as a byte array resource. Byte array resources
    /// use the .NET byte array serialization format with length prefix.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `data` - Binary data to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    ///
    /// let config_data = vec![0x01, 0x02, 0x03, 0x04];
    /// encoder.add_byte_array("ConfigurationData", &config_data)?;
    ///
    /// // For file data, read the file first
    /// // let icon_data = std::fs::read("icon.png")?;
    /// // encoder.add_byte_array("ApplicationIcon", &icon_data)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_byte_array(&mut self, name: &str, data: &[u8]) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::ByteArray(data.to_vec())));
        Ok(())
    }

    /// Adds a stream resource.
    ///
    /// Registers binary data as a stream resource. Stream resources use the same
    /// storage format as byte arrays (4-byte LE length prefix + data), but are
    /// returned as a `Stream` by .NET's `ResourceReader` instead of a `byte[]`.
    /// This allows for memory-mapped access and streaming reads for large resources.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `data` - Binary data to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    ///
    /// let image_data = vec![0x89, 0x50, 0x4E, 0x47]; // PNG header
    /// encoder.add_stream("BackgroundImage", &image_data)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_stream(&mut self, name: &str, data: &[u8]) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::Stream(data.to_vec())));
        Ok(())
    }

    /// Adds an unsigned 8-bit integer resource.
    ///
    /// Registers a byte value with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - Byte value to store (0-255)
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_byte("MaxRetries", 5)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_byte(&mut self, name: &str, value: u8) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::Byte(value)));
        Ok(())
    }

    /// Adds a signed 8-bit integer resource.
    ///
    /// Registers a signed byte value with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - Signed byte value to store (-128 to 127)
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_sbyte("TemperatureOffset", -10)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_sbyte(&mut self, name: &str, value: i8) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::SByte(value)));
        Ok(())
    }

    /// Adds a character resource.
    ///
    /// Registers a Unicode character with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - Character value to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_char("Separator", ',')?;
    /// encoder.add_char("Delimiter", '|')?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_char(&mut self, name: &str, value: char) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::Char(value)));
        Ok(())
    }

    /// Adds a signed 16-bit integer resource.
    ///
    /// Registers a 16-bit signed integer value with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - 16-bit signed integer value to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_int16("PortNumber", 8080)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_int16(&mut self, name: &str, value: i16) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::Int16(value)));
        Ok(())
    }

    /// Adds an unsigned 16-bit integer resource.
    ///
    /// Registers a 16-bit unsigned integer value with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - 16-bit unsigned integer value to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_uint16("MaxConnections", 65535)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_uint16(&mut self, name: &str, value: u16) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::UInt16(value)));
        Ok(())
    }

    /// Adds an unsigned 32-bit integer resource.
    ///
    /// Registers a 32-bit unsigned integer value with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - 32-bit unsigned integer value to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_uint32("FileSize", 1024000)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_uint32(&mut self, name: &str, value: u32) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::UInt32(value)));
        Ok(())
    }

    /// Adds a signed 64-bit integer resource.
    ///
    /// Registers a 64-bit signed integer value with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - 64-bit signed integer value to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_int64("TimestampTicks", 637500000000000000)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_int64(&mut self, name: &str, value: i64) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::Int64(value)));
        Ok(())
    }

    /// Adds an unsigned 64-bit integer resource.
    ///
    /// Registers a 64-bit unsigned integer value with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - 64-bit unsigned integer value to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_uint64("MaxFileSize", 18446744073709551615)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_uint64(&mut self, name: &str, value: u64) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::UInt64(value)));
        Ok(())
    }

    /// Adds a 32-bit floating point resource.
    ///
    /// Registers a single-precision floating point value with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - 32-bit floating point value to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_single("ScaleFactor", 1.5)?;
    /// encoder.add_single("Pi", 3.14159)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_single(&mut self, name: &str, value: f32) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::Single(value)));
        Ok(())
    }

    /// Adds a 64-bit floating point resource.
    ///
    /// Registers a double-precision floating point value with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `value` - 64-bit floating point value to store
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_double("PreciseValue", 3.14159265358979323846)?;
    /// encoder.add_double("EulerNumber", 2.71828182845904523536)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_double(&mut self, name: &str, value: f64) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::Double(value)));
        Ok(())
    }

    /// Adds a .NET Decimal resource using raw bit representation.
    ///
    /// Registers a 128-bit decimal value with the specified name using the same
    /// binary format as .NET's `System.Decimal`. The four 32-bit integers represent
    /// the internal structure of a .NET decimal number.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `lo` - Low 32 bits of the 96-bit mantissa
    /// * `mid` - Middle 32 bits of the 96-bit mantissa
    /// * `hi` - High 32 bits of the 96-bit mantissa
    /// * `flags` - Sign (bit 31) and scale (bits 16-23, valid range 0-28)
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    ///
    /// // Represents 3.261 (mantissa=3261, scale=3, positive)
    /// // flags = 0x00030000 (scale 3 in bits 16-23)
    /// encoder.add_decimal("Price", 3261, 0, 0, 0x00030000)?;
    ///
    /// // Represents -123.45 (mantissa=12345, scale=2, negative)
    /// // flags = 0x80020000 (sign bit + scale 2)
    /// encoder.add_decimal("Discount", 12345, 0, 0, 0x80020000_u32 as i32)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_decimal(
        &mut self,
        name: &str,
        lo: i32,
        mid: i32,
        hi: i32,
        flags: i32,
    ) -> Result<()> {
        self.resources.push((
            name.to_string(),
            ResourceType::Decimal { lo, mid, hi, flags },
        ));
        Ok(())
    }

    /// Adds a .NET DateTime resource using binary representation.
    ///
    /// Registers a date/time value with the specified name using the same binary
    /// format as .NET's `DateTime.ToBinary()`. The 64-bit value encodes both the
    /// ticks and the `DateTimeKind`.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `binary_value` - The binary representation from `DateTime.ToBinary()`
    ///   - Bits 0-61: Ticks (100-nanosecond intervals since 01/01/0001 00:00:00)
    ///   - Bits 62-63: DateTimeKind (0=Unspecified, 1=UTC, 2=Local)
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    ///
    /// // Ticks for 2024-01-01 00:00:00 UTC (kind=1, so bits 62-63 = 0b01)
    /// let ticks: i64 = 638_396_736_000_000_000; // Ticks component
    /// let kind: i64 = 1 << 62; // UTC kind
    /// encoder.add_datetime("ReleaseDate", ticks | kind)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_datetime(&mut self, name: &str, binary_value: i64) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::DateTime(binary_value)));
        Ok(())
    }

    /// Adds a .NET TimeSpan resource using ticks.
    ///
    /// Registers a time interval with the specified name. The 64-bit signed value
    /// represents the number of 100-nanosecond intervals in the time span.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the resource
    /// * `ticks` - Number of 100-nanosecond intervals (negative for negative spans)
    ///
    /// # Conversion Reference
    ///
    /// Common tick conversions:
    /// - 1 millisecond = 10,000 ticks
    /// - 1 second = 10,000,000 ticks
    /// - 1 minute = 600,000,000 ticks
    /// - 1 hour = 36,000,000,000 ticks
    /// - 1 day = 864,000,000,000 ticks
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    ///
    /// // 1 hour timeout
    /// encoder.add_timespan("Timeout", 36_000_000_000)?;
    ///
    /// // 30 seconds
    /// encoder.add_timespan("RetryDelay", 300_000_000)?;
    ///
    /// // Negative 5 minutes
    /// encoder.add_timespan("TimeOffset", -3_000_000_000)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always returns `Ok(())`. Future versions may return errors
    /// for invalid resource names or encoding issues.
    pub fn add_timespan(&mut self, name: &str, ticks: i64) -> Result<()> {
        self.resources
            .push((name.to_string(), ResourceType::TimeSpan(ticks)));
        Ok(())
    }

    /// Returns the number of resources in the encoder.
    ///
    /// # Returns
    ///
    /// The total number of resources that have been added.
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// assert_eq!(encoder.resource_count(), 0);
    ///
    /// encoder.add_string("test", "value")?;
    /// assert_eq!(encoder.resource_count(), 1);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn resource_count(&self) -> usize {
        self.resources.len()
    }

    /// Encodes all resources into .NET resource file format.
    ///
    /// Generates a complete .NET resource file including magic number, headers,
    /// type information, and resource data according to the .NET specification.
    ///
    /// # Returns
    ///
    /// Returns the encoded .NET resource file as a byte vector.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error`] if encoding fails due to invalid resource data
    /// or serialization errors.
    ///
    /// # Examples
    ///
    /// ```
    /// use dotscope::metadata::resources::DotNetResourceEncoder;
    ///
    /// let mut encoder = DotNetResourceEncoder::new();
    /// encoder.add_string("AppName", "My Application")?;
    /// encoder.add_int32("Version", 1)?;
    ///
    /// let resource_file = encoder.encode_dotnet_format()?;
    ///
    /// // The encoded data can be saved to a file or embedded in an assembly
    /// assert!(!resource_file.is_empty());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn encode_dotnet_format(&self) -> Result<Vec<u8>> {
        let mut buffer = Vec::new();

        // Reserve space for the size field (will be updated at the end)
        let size_placeholder_pos = buffer.len();
        buffer.extend_from_slice(&0u32.to_le_bytes());

        // Resource Manager Header
        buffer.extend_from_slice(&RESOURCE_MAGIC.to_le_bytes());
        buffer.extend_from_slice(&self.version.to_le_bytes());

        let header_size_pos = buffer.len();
        buffer.extend_from_slice(&0u32.to_le_bytes()); // Placeholder for header size

        // Resource reader type name (exact Microsoft constant)
        let reader_type = "System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
        write_compressed_uint(to_u32(reader_type.len())?, &mut buffer);
        buffer.extend_from_slice(reader_type.as_bytes());

        // Resource set type name (exact Microsoft constant)
        let resource_set_type = "System.Resources.RuntimeResourceSet";
        write_compressed_uint(to_u32(resource_set_type.len())?, &mut buffer);
        buffer.extend_from_slice(resource_set_type.as_bytes());

        // Calculate header size and update placeholder
        let header_size = buffer.len() - header_size_pos - 4;
        let header_size_bytes = to_u32(header_size)?.to_le_bytes();
        buffer[header_size_pos..header_size_pos + 4].copy_from_slice(&header_size_bytes);

        // Runtime Resource Reader Header
        buffer.extend_from_slice(&self.version.to_le_bytes()); // RR version

        // Resource count
        buffer.extend_from_slice(&to_u32(self.resources.len())?.to_le_bytes());

        // Write type table
        Self::write_type_table(&mut buffer)?;

        // Add padding for 8-byte alignment
        while buffer.len() % 8 != 0 {
            buffer.push(b'P'); // Padding byte
        }

        // Write hash table using official .NET hash function
        let mut name_hashes: Vec<(u32, usize)> = self
            .resources
            .iter()
            .enumerate()
            .map(|(i, (name, _))| (compute_resource_hash(name), i))
            .collect();

        // Sort by hash value as required by .NET format
        name_hashes.sort_by_key(|(hash, _)| *hash);

        for (hash, _) in &name_hashes {
            buffer.extend_from_slice(&hash.to_le_bytes());
        }

        // Calculate name section layout in sorted hash order
        let mut name_section_layout = Vec::new();
        let mut name_offset = 0u32;
        for (_, resource_index) in &name_hashes {
            let (name, _) = &self.resources[*resource_index];
            let name_utf16: Vec<u16> = name.encode_utf16().collect();
            let byte_count = name_utf16.len() * 2;
            #[allow(clippy::cast_possible_truncation)] // compressed_uint_size returns at most 4
            let len_size = compressed_uint_size(byte_count) as u32;
            let entry_size = len_size + to_u32(byte_count)? + 4;

            name_section_layout.push(name_offset);
            name_offset += entry_size;
        }

        // Write position table (in sorted hash order)
        for name_position in &name_section_layout {
            buffer.extend_from_slice(&name_position.to_le_bytes());
        }

        // Calculate data offsets for sorted resources BEFORE writing name section
        let mut data_offsets = Vec::new();
        let mut data_offset = 0u32;
        for (_, resource_index) in &name_hashes {
            let (_, resource_type) = &self.resources[*resource_index];

            data_offsets.push(data_offset);

            // Calculate the actual size this resource will take in the data section
            let type_code_size = if let Some(type_code) = resource_type.type_code() {
                u32::try_from(compressed_uint_size(type_code as usize))
                    .map_err(|_| Error::NotSupported)?
            } else {
                return Err(Error::NotSupported);
            };

            let data_size = resource_type.data_size().ok_or(Error::NotSupported)?;
            data_offset += type_code_size + data_size;
        }

        // Reserve space for data section offset - we'll update it after writing the name section
        let data_section_offset_pos = buffer.len();
        buffer.extend_from_slice(&0u32.to_le_bytes()); // Placeholder

        // Write resource names and data offsets (in sorted hash order)
        for (i, (_, resource_index)) in name_hashes.iter().enumerate() {
            let (name, _) = &self.resources[*resource_index];
            let name_utf16: Vec<u16> = name.encode_utf16().collect();
            let byte_count = name_utf16.len() * 2;

            // Write byte count, not character count
            write_compressed_uint(to_u32(byte_count)?, &mut buffer);

            for utf16_char in name_utf16 {
                buffer.extend_from_slice(&utf16_char.to_le_bytes());
            }

            buffer.extend_from_slice(&data_offsets[i].to_le_bytes());
        }

        // Calculate the actual data section offset following Microsoft's ResourceWriter exactly
        // From ResourceWriter.cs: startOfDataSection += 4; // We're writing an int to store this data
        // Standard .NET convention: offset is relative to magic number position, requiring +4 adjustment in parser
        // For embedded resources, we need to be careful about the offset calculation
        // The offset should point to where the data actually starts in the file
        let actual_data_section_offset = buffer.len() - 4; // -4 to account for size prefix
        let data_section_offset_value = to_u32(actual_data_section_offset)?.to_le_bytes();
        buffer[data_section_offset_pos..data_section_offset_pos + 4]
            .copy_from_slice(&data_section_offset_value);

        // Write resource data (in sorted hash order)
        self.write_resource_data_sorted(&mut buffer, &name_hashes)?;

        // Update the size field at the beginning
        let total_size = buffer.len() - 4; // Exclude the size field itself
        let size_bytes = to_u32(total_size)?.to_le_bytes();
        buffer[size_placeholder_pos..size_placeholder_pos + 4].copy_from_slice(&size_bytes);

        Ok(buffer)
    }

    /// Collects all unique resource types used in the current resource set.
    ///
    /// This method identifies which .NET resource types are actually used, allowing
    /// the type table to include only necessary types for optimal file size.
    ///
    /// # Returns
    ///
    /// Returns a vector of tuples containing (type_name, type_index) pairs sorted by index.
    fn get_used_types(&self) -> Vec<(&'static str, u32)> {
        let mut used_types = BTreeMap::new();

        for (_, resource_type) in &self.resources {
            if let (Some(type_name), Some(type_index)) =
                (resource_type.as_str(), resource_type.index())
            {
                used_types.insert(type_index, type_name);
            }
        }

        used_types
            .into_iter()
            .map(|(index, name)| (name, index))
            .collect()
    }

    /// Writes the type table section of the .NET resource format.
    /// Following Microsoft's ResourceWriter implementation, we write an empty type table
    /// for primitive types and use ResourceTypeCode enum values directly.
    #[allow(clippy::unnecessary_wraps)]
    fn write_type_table(buffer: &mut Vec<u8>) -> Result<()> {
        // Microsoft's ResourceWriter.cs line 344: "write 0 for this writer implementation"
        // For primitive types, Microsoft uses an empty type table and ResourceTypeCode values
        buffer.extend_from_slice(&0u32.to_le_bytes()); // Type count = 0

        Ok(())
    }

    /// Writes the resource data section of the .NET resource format in sorted order.
    fn write_resource_data_sorted(
        &self,
        buffer: &mut Vec<u8>,
        name_hashes: &[(u32, usize)],
    ) -> Result<()> {
        for (_, resource_index) in name_hashes {
            let (_, resource_type) = &self.resources[*resource_index];

            // Use Microsoft's ResourceTypeCode enum values exactly
            let type_code = match resource_type {
                ResourceType::Null => 0u32,            // ResourceTypeCode.Null
                ResourceType::String(_) => 1u32,       // ResourceTypeCode.String
                ResourceType::Boolean(_) => 2u32,      // ResourceTypeCode.Boolean
                ResourceType::Char(_) => 3u32,         // ResourceTypeCode.Char
                ResourceType::Byte(_) => 4u32,         // ResourceTypeCode.Byte
                ResourceType::SByte(_) => 5u32,        // ResourceTypeCode.SByte
                ResourceType::Int16(_) => 6u32,        // ResourceTypeCode.Int16
                ResourceType::UInt16(_) => 7u32,       // ResourceTypeCode.UInt16
                ResourceType::Int32(_) => 8u32,        // ResourceTypeCode.Int32
                ResourceType::UInt32(_) => 9u32,       // ResourceTypeCode.UInt32
                ResourceType::Int64(_) => 10u32,       // ResourceTypeCode.Int64
                ResourceType::UInt64(_) => 11u32,      // ResourceTypeCode.UInt64
                ResourceType::Single(_) => 12u32,      // ResourceTypeCode.Single
                ResourceType::Double(_) => 13u32,      // ResourceTypeCode.Double
                ResourceType::Decimal { .. } => 14u32, // ResourceTypeCode.Decimal (0x0E)
                ResourceType::DateTime(_) => 15u32,    // ResourceTypeCode.DateTime (0x0F)
                ResourceType::TimeSpan(_) => 16u32,    // ResourceTypeCode.TimeSpan (0x10)
                ResourceType::ByteArray(_) => 32u32,   // ResourceTypeCode.ByteArray (0x20)
                ResourceType::Stream(_) => 33u32,      // ResourceTypeCode.Stream (0x21)
                ResourceType::StartOfUserTypes => return Err(Error::NotSupported),
            };

            // Write type code using 7-bit encoding (exactly like Microsoft's data.Write7BitEncodedInt)
            write_compressed_uint(type_code, buffer);

            // Write value data following Microsoft's WriteValue method exactly
            match resource_type {
                ResourceType::Null => {
                    // No data for null
                }
                ResourceType::String(s) => {
                    // Microsoft uses BinaryWriter.Write(string) which writes UTF-8 with 7-bit encoded length prefix
                    let utf8_bytes = s.as_bytes();
                    write_7bit_encoded_int(to_u32(utf8_bytes.len())?, buffer);
                    buffer.extend_from_slice(utf8_bytes);
                }
                ResourceType::Boolean(b) => {
                    buffer.push(u8::from(*b));
                }
                ResourceType::Char(c) => {
                    // Microsoft writes char as ushort (UTF-16)
                    let utf16_char = *c as u16;
                    buffer.extend_from_slice(&utf16_char.to_le_bytes());
                }
                ResourceType::Byte(b) => {
                    buffer.push(*b);
                }
                ResourceType::SByte(sb) => {
                    #[allow(clippy::cast_sign_loss)]
                    {
                        buffer.push(*sb as u8);
                    }
                }
                ResourceType::Int16(i) => {
                    buffer.extend_from_slice(&i.to_le_bytes());
                }
                ResourceType::UInt16(u) => {
                    buffer.extend_from_slice(&u.to_le_bytes());
                }
                ResourceType::Int32(i) => {
                    buffer.extend_from_slice(&i.to_le_bytes());
                }
                ResourceType::UInt32(u) => {
                    buffer.extend_from_slice(&u.to_le_bytes());
                }
                ResourceType::Int64(i) => {
                    buffer.extend_from_slice(&i.to_le_bytes());
                }
                ResourceType::UInt64(u) => {
                    buffer.extend_from_slice(&u.to_le_bytes());
                }
                ResourceType::Single(f) => {
                    buffer.extend_from_slice(&f.to_le_bytes());
                }
                ResourceType::Double(d) => {
                    buffer.extend_from_slice(&d.to_le_bytes());
                }
                ResourceType::Decimal { lo, mid, hi, flags } => {
                    // Write 4 × i32 in little-endian order: lo, mid, hi, flags
                    buffer.extend_from_slice(&lo.to_le_bytes());
                    buffer.extend_from_slice(&mid.to_le_bytes());
                    buffer.extend_from_slice(&hi.to_le_bytes());
                    buffer.extend_from_slice(&flags.to_le_bytes());
                }
                ResourceType::DateTime(binary_value) => {
                    // Write i64 binary representation (ticks + kind)
                    buffer.extend_from_slice(&binary_value.to_le_bytes());
                }
                ResourceType::TimeSpan(ticks) => {
                    // Write i64 ticks
                    buffer.extend_from_slice(&ticks.to_le_bytes());
                }
                ResourceType::ByteArray(data) | ResourceType::Stream(data) => {
                    buffer.extend_from_slice(&to_u32(data.len())?.to_le_bytes());
                    buffer.extend_from_slice(data);
                }
                ResourceType::StartOfUserTypes => {
                    return Err(Error::NotSupported);
                }
            }
        }

        Ok(())
    }
}

impl Default for DotNetResourceEncoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metadata::resources::parser::parse_dotnet_resource;

    #[test]
    fn test_dotnet_resource_encoder_basic() {
        let mut encoder = DotNetResourceEncoder::new();
        assert_eq!(encoder.resource_count(), 0);

        encoder
            .add_string("AppName", "Test App")
            .expect("Should add string");
        encoder.add_int32("Version", 1).expect("Should add integer");
        encoder
            .add_boolean("Debug", true)
            .expect("Should add boolean");

        assert_eq!(encoder.resource_count(), 3);
    }

    #[test]
    fn test_dotnet_resource_encoder_encoding() {
        let mut encoder = DotNetResourceEncoder::new();
        encoder
            .add_string("test", "value")
            .expect("Should add string resource");

        let encoded = encoder
            .encode_dotnet_format()
            .expect("Should encode .NET format");
        assert!(!encoded.is_empty());

        // Should start with size field, then magic number
        assert!(encoded.len() >= 8);
        let _size = u32::from_le_bytes([encoded[0], encoded[1], encoded[2], encoded[3]]);
        let magic = u32::from_le_bytes([encoded[4], encoded[5], encoded[6], encoded[7]]);
        assert_eq!(magic, RESOURCE_MAGIC);

        // Verify encoding works and produces reasonable output
        assert!(encoded.len() > 20); // Should have headers and data
    }

    /// Test that demonstrates the complete DotNetResourceEncoder API
    #[test]
    fn test_comprehensive_resource_encoder_api() {
        let mut encoder = DotNetResourceEncoder::new();

        // Test all supported add methods
        encoder.add_string("AppName", "My Application").unwrap();
        encoder.add_boolean("DebugMode", true).unwrap();
        encoder.add_char("Separator", ',').unwrap();
        encoder.add_byte("MaxRetries", 5).unwrap();
        encoder.add_sbyte("Offset", -10).unwrap();
        encoder.add_int16("Port", 8080).unwrap();
        encoder.add_uint16("MaxConnections", 65535).unwrap();
        encoder.add_int32("Version", 42).unwrap();
        encoder.add_uint32("FileSize", 1024000).unwrap();
        encoder
            .add_int64("TimestampTicks", 637500000000000000)
            .unwrap();
        encoder
            .add_uint64("MaxFileSize", 18446744073709551615)
            .unwrap();
        encoder.add_single("ScaleFactor", 1.5).unwrap();
        encoder.add_double("Pi", std::f64::consts::PI).unwrap();
        encoder
            .add_byte_array("ConfigData", &[1, 2, 3, 4, 5])
            .unwrap();

        // Verify all resources were added
        assert_eq!(encoder.resource_count(), 14);

        // Test that encoding produces valid output
        let encoded_data = encoder.encode_dotnet_format().unwrap();
        assert!(!encoded_data.is_empty());
        assert!(encoded_data.len() > 100); // Should be substantial

        // Verify magic number is correct
        let magic = u32::from_le_bytes([
            encoded_data[4],
            encoded_data[5],
            encoded_data[6],
            encoded_data[7],
        ]);
        assert_eq!(magic, RESOURCE_MAGIC);

        // Verify encoding completed successfully
        assert_eq!(encoder.resource_count(), 14);
        assert!(encoded_data.len() > 100);
    }

    #[test]
    fn test_debug_encoder_format() {
        let mut encoder = DotNetResourceEncoder::new();
        encoder.add_string("TestResource", "Hello World").unwrap();

        let buffer = encoder.encode_dotnet_format().unwrap();

        // Use our own parser to verify the generated data is valid
        let mut resource = crate::metadata::resources::Resource::parse(&buffer).unwrap();

        // Verify basic characteristics
        assert_eq!(resource.rr_version, 2);
        assert_eq!(resource.resource_count, 1);

        // Try to parse the resources to verify validity
        resource
            .read_resources(&buffer)
            .expect("Should be able to parse generated resources");
    }

    #[test]
    fn test_roundtrip_edge_values() {
        let mut encoder = DotNetResourceEncoder::new();

        // Test edge values
        encoder.add_string("EmptyString", "").unwrap();
        encoder
            .add_string("UnicodeString", "🦀 Rust rocks! 你好世界")
            .unwrap();
        encoder.add_byte_array("EmptyByteArray", &[]).unwrap();
        encoder.add_single("NaN", f32::NAN).unwrap();
        encoder.add_single("Infinity", f32::INFINITY).unwrap();
        encoder
            .add_single("NegInfinity", f32::NEG_INFINITY)
            .unwrap();
        encoder.add_double("DoubleNaN", f64::NAN).unwrap();
        encoder.add_double("DoubleInfinity", f64::INFINITY).unwrap();
        encoder
            .add_double("DoubleNegInfinity", f64::NEG_INFINITY)
            .unwrap();

        // Encode and parse back
        let encoded_data = encoder.encode_dotnet_format().unwrap();
        let parsed_resources = parse_dotnet_resource(&encoded_data).unwrap();

        // Verify edge cases
        assert_eq!(parsed_resources.len(), 9);

        // Empty string
        let empty_string = parsed_resources.get("EmptyString").unwrap();
        if let crate::metadata::resources::ResourceType::String(ref s) = empty_string.data {
            assert_eq!(s, "");
        } else {
            panic!("Expected String resource type");
        }

        // Unicode string
        let unicode_string = parsed_resources.get("UnicodeString").unwrap();
        if let crate::metadata::resources::ResourceType::String(ref s) = unicode_string.data {
            assert_eq!(s, "🦀 Rust rocks! 你好世界");
        } else {
            panic!("Expected String resource type");
        }

        // Empty byte array
        let empty_bytes = parsed_resources.get("EmptyByteArray").unwrap();
        if let crate::metadata::resources::ResourceType::ByteArray(ref ba) = empty_bytes.data {
            assert_eq!(ba, &Vec::<u8>::new());
        } else {
            panic!("Expected ByteArray resource type");
        }

        // NaN and infinity values
        let nan_val = parsed_resources.get("NaN").unwrap();
        if let crate::metadata::resources::ResourceType::Single(f) = nan_val.data {
            assert!(f.is_nan());
        } else {
            panic!("Expected Single resource type");
        }

        let inf_val = parsed_resources.get("Infinity").unwrap();
        if let crate::metadata::resources::ResourceType::Single(f) = inf_val.data {
            assert_eq!(f, f32::INFINITY);
        } else {
            panic!("Expected Single resource type");
        }

        let neg_inf_val = parsed_resources.get("NegInfinity").unwrap();
        if let crate::metadata::resources::ResourceType::Single(f) = neg_inf_val.data {
            assert_eq!(f, f32::NEG_INFINITY);
        } else {
            panic!("Expected Single resource type");
        }
    }

    #[test]
    fn test_large_resource_data() {
        let mut encoder = DotNetResourceEncoder::new();

        // Test large string resource
        let large_string = "x".repeat(10000);
        encoder.add_string("LargeString", &large_string).unwrap();

        // Test large byte array
        let large_bytes: Vec<u8> = (0..5000).map(|i| (i % 256) as u8).collect();
        encoder
            .add_byte_array("LargeByteArray", &large_bytes)
            .unwrap();

        // Encode and parse back
        let encoded_data = encoder.encode_dotnet_format().unwrap();
        let parsed_resources = parse_dotnet_resource(&encoded_data).unwrap();

        assert_eq!(parsed_resources.len(), 2);

        // Verify large string
        let parsed_string = parsed_resources.get("LargeString").unwrap();
        if let crate::metadata::resources::ResourceType::String(ref s) = parsed_string.data {
            assert_eq!(s.len(), 10000);
            assert_eq!(s, &large_string);
        } else {
            panic!("Expected String resource type");
        }

        // Verify large byte array
        let parsed_bytes = parsed_resources.get("LargeByteArray").unwrap();
        if let crate::metadata::resources::ResourceType::ByteArray(ref ba) = parsed_bytes.data {
            assert_eq!(ba.len(), 5000);
            assert_eq!(ba, &large_bytes);
        } else {
            panic!("Expected ByteArray resource type");
        }
    }
}