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
//! Custom attribute blob encoding implementation for .NET metadata generation.
//!
//! This module provides comprehensive encoding of custom attribute data according to the
//! ECMA-335 II.23.3 `CustomAttribute` signature specification. It implements the inverse
//! functionality of the parsing implementation, enabling complete round-trip support for
//! all .NET custom attribute types and structures.
//!
//! # Architecture
//!
//! The encoding architecture mirrors the parsing implementation, providing:
//!
//! ## Core Components
//!
//! - **Fixed Arguments**: Encode constructor arguments using type-specific binary formats
//! - **Named Arguments**: Encode field/property assignments with embedded type tags
//! - **Type System**: Complete coverage of all .NET primitive and complex types
//! - **Binary Format**: Strict ECMA-335 compliance with proper prolog and structure
//!
//! ## Design Principles
//!
//! - **Round-Trip Accuracy**: Encoded data must parse back to identical structures
//! - **ECMA-335 Compliance**: Strict adherence to official binary format specification
//! - **Type Safety**: Leverages existing type system for accurate encoding
//! - **Error Handling**: Comprehensive validation with detailed error messages
//!
//! # Key Functions
//!
//! - [`encode_custom_attribute_value`] - Main encoding function for complete custom attributes
//! - [`encode_fixed_arguments`] - Constructor arguments encoding
//! - [`encode_named_arguments`] - Field/property assignments encoding
//! - [`encode_custom_attribute_argument`] - Individual argument value encoding
//!
//! # Usage Examples
//!
//! ## Encoding Complete Custom Attribute
//!
//! ```rust,no_run
//! use dotscope::metadata::customattributes::{
//!     CustomAttributeValue, CustomAttributeArgument, encode_custom_attribute_value
//! };
//!
//! let custom_attr = CustomAttributeValue {
//!     fixed_args: vec![
//!         CustomAttributeArgument::String("Debug".to_string()),
//!         CustomAttributeArgument::Bool(true),
//!     ],
//!     named_args: vec![],
//! };
//!
//! let encoded_blob = encode_custom_attribute_value(&custom_attr)?;
//! println!("Encoded {} bytes", encoded_blob.len());
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Encoding Individual Arguments
//!
//! ```rust,no_run
//! use dotscope::metadata::customattributes::{CustomAttributeArgument, encode_custom_attribute_argument};
//!
//! let string_arg = CustomAttributeArgument::String("Hello".to_string());
//! let mut encoded_string = Vec::new();
//! encode_custom_attribute_argument(&string_arg, &mut encoded_string)?;
//!
//! let int_arg = CustomAttributeArgument::I4(42);
//! let mut encoded_int = Vec::new();
//! encode_custom_attribute_argument(&int_arg, &mut encoded_int)?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Binary Format
//!
//! The encoder produces binary data in the exact format specified by ECMA-335:
//!
//! ```text
//! CustomAttribute ::= Prolog FixedArgs NumNamed NamedArgs
//! Prolog          ::= 0x0001
//! FixedArgs       ::= Argument*
//! NumNamed        ::= PackedLen
//! NamedArgs       ::= NamedArg*
//! NamedArg        ::= FIELD | PROPERTY FieldOrPropType FieldOrPropName FixedArg
//! ```
//!
//! # Thread Safety
//!
//! All functions in this module are thread-safe and stateless. The encoder can be called
//! concurrently from multiple threads as it operates only on immutable input data.
//!
//! # Integration
//!
//! This module integrates with:
//! - [`crate::metadata::customattributes::types`] - Type definitions for encoding
//! - [`crate::metadata::customattributes::parser`] - Round-trip validation with parsing
//! - [`crate::cilassembly::CilAssembly`] - Assembly modification and blob heap integration
//! - [`crate::metadata::typesystem`] - Type system for accurate encoding

use crate::{
    metadata::customattributes::{
        CustomAttributeArgument, CustomAttributeNamedArgument, CustomAttributeValue,
        NAMED_ARG_TYPE, SERIALIZATION_TYPE,
    },
    utils::write_compressed_uint,
    Result,
};

/// Encodes a complete custom attribute value into binary blob format according to ECMA-335.
///
/// This is the main entry point for custom attribute encoding. It produces a binary blob
/// that is compatible with the .NET custom attribute format and can be stored in the
/// blob heap of a .NET assembly.
///
/// # Binary Format
///
/// The output follows the ECMA-335 II.23.3 specification:
/// 1. Prolog: 0x0001 (little-endian)
/// 2. Fixed arguments: Constructor parameters in order
/// 3. Named argument count: Compressed integer
/// 4. Named arguments: Field/property assignments with type tags
///
/// # Arguments
///
/// * `value` - The custom attribute value to encode
///
/// # Returns
///
/// A vector of bytes representing the encoded custom attribute blob.
///
/// # Errors
///
/// Returns [`crate::Error::Malformed`] in the following cases:
/// - Too many named arguments (exceeds u16 maximum of 65535)
/// - Array length exceeds u32 maximum
/// - String length exceeds compressed uint maximum (0x1FFFFFFF bytes)
/// - Character outside the Basic Multilingual Plane (code point > 0xFFFF)
/// - Void argument in a context where a value is required
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::metadata::customattributes::{
///     CustomAttributeValue, CustomAttributeArgument, encode_custom_attribute_value,
/// };
///
/// let custom_attr = CustomAttributeValue {
///     fixed_args: vec![CustomAttributeArgument::String("Test".to_string())],
///     named_args: vec![],
/// };
///
/// let blob = encode_custom_attribute_value(&custom_attr)?;
/// # Ok::<(), dotscope::Error>(())
/// ```
pub fn encode_custom_attribute_value(value: &CustomAttributeValue) -> Result<Vec<u8>> {
    let mut buffer = Vec::new();

    // Write prolog (0x0001 in little-endian)
    buffer.extend_from_slice(&[0x01, 0x00]);

    encode_fixed_arguments(&value.fixed_args, &mut buffer)?;

    // ECMA-335 §II.23.3: NumNamed is encoded as unsigned int16
    let named_count = u16::try_from(value.named_args.len()).map_err(|_| {
        malformed_error!(
            "Too many named arguments: {} exceeds u16 maximum (65535)",
            value.named_args.len()
        )
    })?;
    buffer.extend_from_slice(&named_count.to_le_bytes());

    encode_named_arguments(&value.named_args, &mut buffer)?;

    Ok(buffer)
}

/// Encodes the fixed arguments (constructor parameters) of a custom attribute.
///
/// Fixed arguments are encoded in the order they appear in the constructor signature,
/// using type-specific binary formats for each argument type.
///
/// # Arguments
///
/// * `args` - The fixed arguments to encode
/// * `buffer` - The output buffer to write encoded data to
///
/// # ECMA-335 Reference
///
/// According to ECMA-335 II.23.3, fixed arguments are encoded as:
/// ```text
/// FixedArgs ::= Argument*
/// Argument  ::= <type-specific binary data>
/// ```
fn encode_fixed_arguments(args: &[CustomAttributeArgument], buffer: &mut Vec<u8>) -> Result<()> {
    for arg in args {
        encode_custom_attribute_argument(arg, buffer)?;
    }
    Ok(())
}

/// Encodes the named arguments (field/property assignments) of a custom attribute.
///
/// Named arguments include explicit type information via SERIALIZATION_TYPE tags,
/// enabling self-describing parsing without external type resolution.
///
/// # Arguments
///
/// * `args` - The named arguments to encode
/// * `buffer` - The output buffer to write encoded data to
///
/// # ECMA-335 Reference
///
/// According to ECMA-335 II.23.3, named arguments are encoded as:
/// ```text
/// NamedArg ::= FIELD | PROPERTY FieldOrPropType FieldOrPropName FixedArg
/// FIELD    ::= NAMED_ARG_TYPE::FIELD (0x53)
/// PROPERTY ::= NAMED_ARG_TYPE::PROPERTY (0x54)
/// ```
fn encode_named_arguments(
    args: &[CustomAttributeNamedArgument],
    buffer: &mut Vec<u8>,
) -> Result<()> {
    for arg in args {
        match &arg.value {
            CustomAttributeArgument::Array(_) => {
                return Err(malformed_error!(
                    "Array arguments are not supported in named arguments"
                ));
            }
            CustomAttributeArgument::Enum(_, _) => {
                return Err(malformed_error!(
                    "Enum arguments are not supported in named arguments"
                ));
            }
            _ => {} // Other types are supported
        }

        if arg.is_field {
            buffer.push(NAMED_ARG_TYPE::FIELD);
        } else {
            buffer.push(NAMED_ARG_TYPE::PROPERTY);
        }

        let type_tag = get_serialization_type_tag(&arg.value)?;
        buffer.push(type_tag);

        write_string(buffer, &arg.name)?;

        encode_custom_attribute_argument(&arg.value, buffer)?;
    }
    Ok(())
}

/// Encodes a single custom attribute argument value into binary format.
///
/// This function handles all supported .NET types according to the ECMA-335 specification,
/// using the appropriate binary encoding for each type variant.
///
/// # Arguments
///
/// * `arg` - The argument to encode
/// * `buffer` - The output buffer to write encoded data to
///
/// # Type Encoding
///
/// Each type is encoded according to its specific format:
/// - **Primitives**: Little-endian binary representation
/// - **Strings**: Compressed length + UTF-8 data (or 0xFF for null)
/// - **Arrays**: Compressed length + encoded elements
/// - **Enums**: Underlying type value (type name encoded separately in named args)
///
/// # Errors
///
/// Returns [`crate::Error::Malformed`] in the following cases:
/// - `Char`: Character code point exceeds 0xFFFF (outside Basic Multilingual Plane)
/// - `String`: String length exceeds compressed uint maximum (0x1FFFFFFF bytes)
/// - `Array`: Array length exceeds u32 maximum (4,294,967,295 elements)
/// - Recursive errors from nested array element encoding
pub fn encode_custom_attribute_argument(
    arg: &CustomAttributeArgument,
    buffer: &mut Vec<u8>,
) -> Result<()> {
    match arg {
        CustomAttributeArgument::Void => {
            // Void arguments are typically not used in custom attributes
        }
        CustomAttributeArgument::Bool(value) => {
            buffer.push(u8::from(*value));
        }
        CustomAttributeArgument::Char(value) => {
            // .NET's System.Char is a 16-bit UTF-16 code unit per ECMA-335 §II.23.3.
            // Characters outside the Basic Multilingual Plane (U+10000 and above) cannot
            // be represented in a single .NET char - they require surrogate pairs.
            // Since this is a fundamental .NET limitation, we reject such characters
            // rather than silently corrupting data.
            let code_point = *value as u32;
            if code_point > 0xFFFF {
                return Err(malformed_error!(
                    "Character U+{:04X} is outside the Basic Multilingual Plane and cannot be \
                     encoded as a .NET char (which is limited to U+0000..U+FFFF)",
                    code_point
                ));
            }
            #[allow(clippy::cast_possible_truncation)] // Safe: validated above
            let utf16_val = *value as u16;
            buffer.extend_from_slice(&utf16_val.to_le_bytes());
        }
        CustomAttributeArgument::I1(value) => {
            // Safe: i8 to u8 preserves the bit pattern which is correct for serialization
            #[allow(clippy::cast_sign_loss)]
            buffer.push(*value as u8);
        }
        CustomAttributeArgument::U1(value) => {
            buffer.push(*value);
        }
        CustomAttributeArgument::I2(value) => {
            buffer.extend_from_slice(&value.to_le_bytes());
        }
        CustomAttributeArgument::U2(value) => {
            buffer.extend_from_slice(&value.to_le_bytes());
        }
        CustomAttributeArgument::I4(value) => {
            buffer.extend_from_slice(&value.to_le_bytes());
        }
        CustomAttributeArgument::U4(value) => {
            buffer.extend_from_slice(&value.to_le_bytes());
        }
        CustomAttributeArgument::I8(value) => {
            buffer.extend_from_slice(&value.to_le_bytes());
        }
        CustomAttributeArgument::U8(value) => {
            buffer.extend_from_slice(&value.to_le_bytes());
        }
        CustomAttributeArgument::R4(value) => {
            buffer.extend_from_slice(&value.to_le_bytes());
        }
        CustomAttributeArgument::R8(value) => {
            buffer.extend_from_slice(&value.to_le_bytes());
        }
        CustomAttributeArgument::I(value) => {
            // Native integers (IntPtr/nint) are platform-dependent per ECMA-335:
            // - 32-bit platforms: encoded as 4 bytes (i32)
            // - 64-bit platforms: encoded as 8 bytes (i64)
            //
            // LIMITATION: This uses the HOST platform size, not the TARGET assembly's
            // platform. Cross-platform encoding (e.g., encoding a 32-bit assembly on
            // a 64-bit host) is not currently supported. The assembly would need to
            // specify its target platform, which is not available in this context.
            #[cfg(target_pointer_width = "32")]
            {
                buffer.extend_from_slice(
                    &i32::try_from(*value).unwrap_or(*value as i32).to_le_bytes(),
                );
            }
            #[cfg(not(target_pointer_width = "32"))]
            {
                buffer.extend_from_slice(&(*value as i64).to_le_bytes());
            }
        }
        CustomAttributeArgument::U(value) => {
            // Native integers (UIntPtr/nuint) are platform-dependent per ECMA-335:
            // - 32-bit platforms: encoded as 4 bytes (u32)
            // - 64-bit platforms: encoded as 8 bytes (u64)
            //
            // LIMITATION: Same cross-platform limitation as I (signed native int).
            #[cfg(target_pointer_width = "32")]
            {
                buffer.extend_from_slice(
                    &u32::try_from(*value).unwrap_or(*value as u32).to_le_bytes(),
                );
            }
            #[cfg(not(target_pointer_width = "32"))]
            {
                buffer.extend_from_slice(&(*value as u64).to_le_bytes());
            }
        }
        CustomAttributeArgument::String(value) | CustomAttributeArgument::Type(value) => {
            write_string(buffer, value)?;
        }
        CustomAttributeArgument::Array(elements) => {
            // Array length is encoded as compressed uint (max ~2^29 per ECMA-335 §II.23.2)
            let len = u32::try_from(elements.len()).map_err(|_| {
                malformed_error!("Array too large: {} exceeds u32 maximum", elements.len())
            })?;
            write_compressed_uint(len, buffer);
            for element in elements {
                encode_custom_attribute_argument(element, buffer)?;
            }
        }
        CustomAttributeArgument::Enum(_, underlying_value) => {
            encode_custom_attribute_argument(underlying_value, buffer)?;
        }
    }
    Ok(())
}

/// Gets the SERIALIZATION_TYPE tag for a custom attribute argument.
///
/// This function maps custom attribute argument types to their corresponding
/// SERIALIZATION_TYPE constants used in the binary format for named arguments.
///
/// # Arguments
///
/// * `arg` - The argument to get the type tag for
///
/// # Returns
///
/// The SERIALIZATION_TYPE constant corresponding to the argument type.
fn get_serialization_type_tag(arg: &CustomAttributeArgument) -> Result<u8> {
    let tag = match arg {
        CustomAttributeArgument::Void => {
            return Err(malformed_error!(
                "Void arguments are not supported in custom attributes"
            ));
        }
        CustomAttributeArgument::Bool(_) => SERIALIZATION_TYPE::BOOLEAN,
        CustomAttributeArgument::Char(_) => SERIALIZATION_TYPE::CHAR,
        CustomAttributeArgument::I1(_) => SERIALIZATION_TYPE::I1,
        CustomAttributeArgument::U1(_) => SERIALIZATION_TYPE::U1,
        CustomAttributeArgument::I2(_) => SERIALIZATION_TYPE::I2,
        CustomAttributeArgument::U2(_) => SERIALIZATION_TYPE::U2,
        CustomAttributeArgument::I4(_) => SERIALIZATION_TYPE::I4,
        CustomAttributeArgument::U4(_) => SERIALIZATION_TYPE::U4,
        CustomAttributeArgument::I8(_) => SERIALIZATION_TYPE::I8,
        CustomAttributeArgument::U8(_) => SERIALIZATION_TYPE::U8,
        CustomAttributeArgument::R4(_) => SERIALIZATION_TYPE::R4,
        CustomAttributeArgument::R8(_) => SERIALIZATION_TYPE::R8,
        CustomAttributeArgument::I(_) => {
            // Native integers use I4 on 32-bit, I8 on 64-bit.
            // LIMITATION: This uses the host platform's pointer width, not the target assembly's.
            // Cross-platform encoding is not supported - see MED-001 in refactoring doc.
            if cfg!(target_pointer_width = "32") {
                SERIALIZATION_TYPE::I4
            } else {
                SERIALIZATION_TYPE::I8
            }
        }
        CustomAttributeArgument::U(_) => {
            // Native unsigned integers use U4 on 32-bit, U8 on 64-bit.
            // LIMITATION: This uses the host platform's pointer width, not the target assembly's.
            // Cross-platform encoding is not supported - see MED-001 in refactoring doc.
            if cfg!(target_pointer_width = "32") {
                SERIALIZATION_TYPE::U4
            } else {
                SERIALIZATION_TYPE::U8
            }
        }
        CustomAttributeArgument::String(_) => SERIALIZATION_TYPE::STRING,
        CustomAttributeArgument::Type(_) => SERIALIZATION_TYPE::TYPE,
        CustomAttributeArgument::Array(_) => SERIALIZATION_TYPE::SZARRAY,
        CustomAttributeArgument::Enum(_, _) => SERIALIZATION_TYPE::ENUM,
    };
    Ok(tag)
}

/// Writes a string to the buffer using the .NET custom attribute string format.
///
/// # ECMA-335 String Encoding
///
/// Per ECMA-335, strings can be encoded as:
/// - **Null strings**: Single byte 0xFF
/// - **Empty strings**: Compressed uint 0 (single byte 0x00)
/// - **Non-empty strings**: Compressed length + UTF-8 data
///
/// # Design Decision
///
/// Since Rust's `String` cannot represent null (unlike .NET's `string?`), this function
/// encodes empty strings as length 0, not as the null marker 0xFF. This means:
/// - Parsing a null string (0xFF) returns an empty `String`
/// - Re-encoding that empty `String` produces length 0, not 0xFF
///
/// This round-trip asymmetry is acceptable because both representations have equivalent
/// semantics in the Rust API context.
///
/// # Arguments
///
/// * `buffer` - The output buffer to write to
/// * `value` - The string value to encode
///
/// # Errors
///
/// Returns an error if the string length exceeds the compressed uint maximum (0x1FFFFFFF bytes).
fn write_string(buffer: &mut Vec<u8>, value: &str) -> Result<()> {
    if value.is_empty() {
        write_compressed_uint(0, buffer);
    } else {
        let utf8_bytes = value.as_bytes();
        let len = u32::try_from(utf8_bytes.len()).map_err(|_| {
            malformed_error!(
                "String too long: {} bytes exceeds u32 maximum",
                utf8_bytes.len()
            )
        })?;
        write_compressed_uint(len, buffer);
        buffer.extend_from_slice(utf8_bytes);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metadata::customattributes::{CustomAttributeNamedArgument, CustomAttributeValue};

    #[test]
    fn test_encode_simple_custom_attribute() {
        let custom_attr = CustomAttributeValue {
            fixed_args: vec![CustomAttributeArgument::String("Test".to_string())],
            named_args: vec![],
        };

        let result = encode_custom_attribute_value(&custom_attr);
        assert!(
            result.is_ok(),
            "Simple custom attribute encoding should succeed"
        );

        let encoded = result.unwrap();
        assert!(!encoded.is_empty(), "Encoded data should not be empty");

        // Check prolog (0x0001)
        assert_eq!(encoded[0], 0x01, "First byte should be 0x01");
        assert_eq!(encoded[1], 0x00, "Second byte should be 0x00");

        // Should have named argument count (0)
        let last_byte = encoded[encoded.len() - 1];
        assert_eq!(last_byte, 0x00, "Named argument count should be 0");
    }

    #[test]
    fn test_encode_boolean_argument() {
        let mut buffer = Vec::new();
        let arg = CustomAttributeArgument::Bool(true);

        let result = encode_custom_attribute_argument(&arg, &mut buffer);
        assert!(result.is_ok(), "Boolean encoding should succeed");
        assert_eq!(buffer, vec![1], "True should encode as 1");

        buffer.clear();
        let arg = CustomAttributeArgument::Bool(false);
        let result = encode_custom_attribute_argument(&arg, &mut buffer);
        assert!(result.is_ok(), "Boolean encoding should succeed");
        assert_eq!(buffer, vec![0], "False should encode as 0");
    }

    #[test]
    fn test_encode_integer_arguments() {
        let mut buffer = Vec::new();

        // Test I4
        let arg = CustomAttributeArgument::I4(0x12345678);
        let result = encode_custom_attribute_argument(&arg, &mut buffer);
        assert!(result.is_ok(), "I4 encoding should succeed");
        assert_eq!(
            buffer,
            vec![0x78, 0x56, 0x34, 0x12],
            "I4 should be little-endian"
        );

        // Test U2
        buffer.clear();
        let arg = CustomAttributeArgument::U2(0x1234);
        let result = encode_custom_attribute_argument(&arg, &mut buffer);
        assert!(result.is_ok(), "U2 encoding should succeed");
        assert_eq!(buffer, vec![0x34, 0x12], "U2 should be little-endian");
    }

    #[test]
    fn test_encode_string_argument() {
        let mut buffer = Vec::new();
        let arg = CustomAttributeArgument::String("Hello".to_string());

        let result = encode_custom_attribute_argument(&arg, &mut buffer);
        assert!(result.is_ok(), "String encoding should succeed");

        // Should be: length (5) + "Hello" UTF-8
        let expected = vec![5, b'H', b'e', b'l', b'l', b'o'];
        assert_eq!(buffer, expected, "String should encode with length prefix");
    }

    #[test]
    fn test_encode_array_argument() {
        let mut buffer = Vec::new();
        let arg = CustomAttributeArgument::Array(vec![
            CustomAttributeArgument::I4(1),
            CustomAttributeArgument::I4(2),
        ]);

        let result = encode_custom_attribute_argument(&arg, &mut buffer);
        assert!(result.is_ok(), "Array encoding should succeed");

        // Should be: length (2) + two I4 values
        let expected = vec![
            2, // length
            1, 0, 0, 0, // I4(1) little-endian
            2, 0, 0, 0, // I4(2) little-endian
        ];
        assert_eq!(
            buffer, expected,
            "Array should encode with length and elements"
        );
    }

    #[test]
    fn test_encode_named_argument() {
        let named_args = vec![CustomAttributeNamedArgument {
            is_field: false, // property
            name: "Value".to_string(),
            arg_type: "String".to_string(),
            value: CustomAttributeArgument::String("Test".to_string()),
        }];

        let mut buffer = Vec::new();
        let result = encode_named_arguments(&named_args, &mut buffer);
        assert!(result.is_ok(), "Named argument encoding should succeed");

        assert!(!buffer.is_empty(), "Named argument should produce data");
        assert_eq!(buffer[0], 0x54, "Should start with PROPERTY marker");
        assert_eq!(
            buffer[1],
            SERIALIZATION_TYPE::STRING,
            "Should have STRING type tag"
        );
    }

    #[test]
    fn test_encode_compressed_uint() {
        let mut buffer = Vec::new();

        // Test single byte encoding
        write_compressed_uint(42, &mut buffer);
        assert_eq!(buffer, vec![42], "Small values should use single byte");

        // Test two byte encoding
        buffer.clear();
        write_compressed_uint(0x1234, &mut buffer);
        assert_eq!(
            buffer,
            vec![0x80 | 0x12, 0x34],
            "Medium values should use two bytes"
        );

        // Test four byte encoding
        buffer.clear();
        write_compressed_uint(0x12345678, &mut buffer);
        assert_eq!(
            buffer,
            vec![0xC0 | 0x12, 0x34, 0x56, 0x78],
            "Large values should use four bytes"
        );
    }

    #[test]
    fn test_get_serialization_type_tag() {
        assert_eq!(
            get_serialization_type_tag(&CustomAttributeArgument::Bool(true)).unwrap(),
            SERIALIZATION_TYPE::BOOLEAN
        );
        assert_eq!(
            get_serialization_type_tag(&CustomAttributeArgument::String("test".to_string()))
                .unwrap(),
            SERIALIZATION_TYPE::STRING
        );
        assert_eq!(
            get_serialization_type_tag(&CustomAttributeArgument::I4(42)).unwrap(),
            SERIALIZATION_TYPE::I4
        );
    }

    #[test]
    fn test_encode_complete_custom_attribute_with_named_args() {
        let custom_attr = CustomAttributeValue {
            fixed_args: vec![CustomAttributeArgument::String("Debug".to_string())],
            named_args: vec![CustomAttributeNamedArgument {
                is_field: false,
                name: "Name".to_string(),
                arg_type: "String".to_string(),
                value: CustomAttributeArgument::String("TestName".to_string()),
            }],
        };

        let result = encode_custom_attribute_value(&custom_attr);
        assert!(
            result.is_ok(),
            "Complete custom attribute encoding should succeed"
        );

        let encoded = result.unwrap();
        assert!(
            encoded.len() > 10,
            "Complete attribute should be substantial"
        );

        // Check prolog
        assert_eq!(encoded[0], 0x01, "Should start with prolog");
        assert_eq!(encoded[1], 0x00, "Should start with prolog");
    }

    #[test]
    fn test_debug_named_args_encoding() {
        let custom_attr = CustomAttributeValue {
            fixed_args: vec![],
            named_args: vec![CustomAttributeNamedArgument {
                is_field: true,
                name: "FieldValue".to_string(),
                arg_type: "I4".to_string(),
                value: CustomAttributeArgument::I4(42),
            }],
        };

        let encoded = encode_custom_attribute_value(&custom_attr).unwrap();

        // Expected format:
        // 0x01, 0x00 - Prolog
        // (no fixed args)
        // 0x01, 0x00 - Named args count (1, little-endian u16)
        // 0x53 - Field indicator
        // 0x08 - I4 type tag
        // field name length + "FieldValue"
        // 42 as I4

        // Check actual structure
        if encoded.len() >= 6 {
            // Verify structure: prolog, named count, field indicator, type tag
            assert_eq!(encoded[0], 0x01);
            assert_eq!(encoded[1], 0x00);
            assert_eq!(encoded[2], 0x01);
            assert_eq!(encoded[3], 0x00);
            assert_eq!(encoded[4], 0x53);
            assert_eq!(encoded[5], 0x08);
        }
    }

    #[test]
    fn test_debug_type_args_encoding() {
        let custom_attr = CustomAttributeValue {
            fixed_args: vec![CustomAttributeArgument::Type("System.String".to_string())],
            named_args: vec![],
        };

        let encoded = encode_custom_attribute_value(&custom_attr).unwrap();

        // Expected format:
        // 0x01, 0x00 - Prolog
        // Type string: compressed length + "System.String"
        // 0x00, 0x00 - Named args count (0, little-endian u16)

        // Verify byte structure
        let mut pos = 0;
        assert_eq!(encoded[pos], 0x01);
        assert_eq!(encoded[pos + 1], 0x00);
        pos += 2;

        // String encoding: first read compressed length
        if pos < encoded.len() {
            let str_len = encoded[pos];
            pos += 1;

            if pos + str_len as usize <= encoded.len() {
                let string_bytes = &encoded[pos..pos + str_len as usize];
                let string_str = String::from_utf8_lossy(string_bytes);
                assert_eq!(string_str, "System.String");
                pos += str_len as usize;
            }
        }

        if pos + 1 < encoded.len() {
            // Verify named count is 0
            assert_eq!(encoded[pos], 0x00);
            assert_eq!(encoded[pos + 1], 0x00);
        }
    }
}