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
//! ECMA-335 Stream Header Parsing for .NET Metadata Directory
//!
//! This module provides parsing and validation of stream headers according to ECMA-335 Section II.24.2.2.
//! Stream headers form the directory structure within .NET metadata that describes the location, size,
//! and identity of each metadata stream (strings, blobs, GUIDs, tables) within the assembly file.
//!
//! # Stream Header Structure
//!
//! Each stream header consists of a fixed-size binary structure followed by a variable-length
//! null-terminated ASCII name. The header provides essential information for locating and
//! validating stream content within the metadata section.
//!
//! ## Binary Format
//! ```text
//! Offset | Size | Field       | Description
//! -------|------|-------------|------------------------------------------
//! 0      | 4    | Offset      | Byte offset from metadata root to stream data
//! 4      | 4    | Size        | Stream size in bytes (must be 4-byte aligned)
//! 8      | N+1  | Name        | Null-terminated ASCII stream name (max 32 chars)
//! ```
//!
//! ## ECMA-335 Compliance Requirements
//! - **Size Alignment**: Stream size should be divisible by 4 per spec, but unaligned sizes are tolerated
//! - **Offset Range**: Stream offset must not exceed maximum reasonable metadata size
//! - **Name Validation**: Stream name must match predefined standard stream identifiers
//! - **Null Termination**: Stream name must be properly null-terminated ASCII
//!
//! # Standard Stream Names
//!
//! The ECMA-335 specification defines specific names for standard metadata streams:
//!
//! ## String Storage Streams
//! - **`#Strings`**: UTF-8 identifier strings (type names, member names, namespaces)
//! - **`#US`**: UTF-16 user string literals (IL string constants, resource names)
//!
//! ## Binary Data Streams
//! - **`#Blob`**: Variable-length binary data (signatures, custom attributes, constants)
//! - **`#GUID`**: 128-bit globally unique identifiers (assembly/module correlation)
//!
//! ## Metadata Table Streams
//! - **`#~`**: Compressed metadata tables (modern .NET assemblies)
//! - **`#-`**: Uncompressed metadata tables (legacy format, rare)
//!
//! # Validation and Security
//!
//! Stream header parsing includes comprehensive validation to prevent:
//! - **Buffer overflow attacks**: Bounds checking on all field access
//! - **Integer overflow**: Range validation on offset and size values
//! - **Format corruption**: Alignment and name validation
//! - **Resource exhaustion**: Reasonable limits on stream sizes
//!
//! ## Validation Rules
//! 1. **Minimum size**: Header must contain at least offset, size, and one name byte
//! 2. **4-byte alignment**: Stream size must be multiple of 4 per ECMA-335
//! 3. **Range limits**: Offset and size must not exceed 0x7FFFFFFF (2GB limit)
//! 4. **Name validation**: Must match one of the six standard stream names
//! 5. **Null termination**: Name must be properly terminated within 32-character limit
//!
//! # Examples
//!
//! ## Basic Stream Header Parsing
//! ```rust
//! use dotscope::metadata::streams::StreamHeader;
//!
//! # fn example() -> dotscope::Result<()> {
//! // Example metadata table stream header
//! #[rustfmt::skip]
//! let header_data = [
//!     0x6C, 0x00, 0x00, 0x00,  // Offset: 0x6C (108 bytes)
//!     0xA4, 0x45, 0x00, 0x00,  // Size: 0x45A4 (17,828 bytes)
//!     0x23, 0x7E, 0x00,        // Name: "#~\0" (compressed tables)
//! ];
//!
//! let header = StreamHeader::from(&header_data)?;
//!
//! assert_eq!(header.offset, 0x6C);
//! assert_eq!(header.size, 0x45A4);
//! assert_eq!(header.name, "#~");
//!
//! println!("Stream '{}' at offset 0x{:X}, size {} bytes",
//!          header.name, header.offset, header.size);
//! # Ok(())
//! # }
//! ```
//!
//! ## Stream Directory Processing
//! ```rust
//! use dotscope::metadata::streams::StreamHeader;
//!
//! # fn example() -> dotscope::Result<()> {
//! // Process multiple stream headers from metadata directory
//! let directory_data = &[
//!     // First stream header
//!     0x6C, 0x00, 0x00, 0x00,           // Offset
//!     0xA4, 0x45, 0x00, 0x00,           // Size  
//!     0x23, 0x7E, 0x00, 0x00,           // "#~\0" (padded to 4-byte boundary)
//!     // Second stream header would follow...
//! ];
//!
//! let mut offset = 0;
//! let mut streams = Vec::new();
//!
//! // Parse first stream header
//! if offset < directory_data.len() {
//!     let header = StreamHeader::from(&directory_data[offset..])?;
//!     println!("Found stream: {} (offset: 0x{:X}, size: {})",
//!              header.name, header.offset, header.size);
//!     streams.push(header);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Error Handling and Validation
//! ```rust
//! use dotscope::metadata::streams::StreamHeader;
//!
//! # fn example() -> dotscope::Result<()> {
//! // Example with invalid stream header (unaligned size)
//! #[rustfmt::skip]
//! let invalid_data = [
//!     0x6C, 0x00, 0x00, 0x00,  // Valid offset
//!     0xA5, 0x45, 0x00, 0x00,  // Invalid size (not 4-byte aligned)
//!     0x23, 0x7E, 0x00,        // Valid name "#~\0"
//! ];
//!
//! match StreamHeader::from(&invalid_data) {
//!     Ok(header) => println!("Parsed header: {}", header.name),
//!     Err(e) => println!("Validation failed: {}", e),
//! }
//!
//! // Example with invalid stream name
//! #[rustfmt::skip]
//! let invalid_name = [
//!     0x6C, 0x00, 0x00, 0x00,  // Valid offset
//!     0xA4, 0x45, 0x00, 0x00,  // Valid size
//!     0x24, 0x7E, 0x00,        // Invalid name "$~\0"
//! ];
//!
//! assert!(StreamHeader::from(&invalid_name).is_err());
//! # Ok(())
//! # }
//! ```
//!
//! # ECMA-335 Compliance
//!
//! This implementation fully complies with ECMA-335 Partition II, Section 24.2.2:
//! - Correct parsing of offset, size, and name fields
//! - Proper validation of 4-byte size alignment requirement
//! - Standard stream name validation and recognition
//! - Comprehensive error handling for malformed headers
//!
//! # See Also
//! - [`crate::metadata::streams`]: Overview of all metadata stream types
//! - [`crate::metadata::root`]: Metadata root and stream directory parsing
//! - [ECMA-335 II.24.2.2](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf): Stream header specification
//!
//! # References
//! - **ECMA-335 II.24.2.2**: Stream header format and directory structure
//! - **ECMA-335 II.24.2**: Complete metadata stream architecture overview

use crate::{utils::read_le, Result};
use std::io::Write;

/// ECMA-335 compliant stream header providing metadata stream location and identification.
///
/// A stream header describes a single metadata stream within a .NET assembly's metadata directory.
/// Each header contains the stream's file offset, size, and identifying name according to
/// ECMA-335 Section II.24.2.2. The structure enables runtime and analysis tools to locate
/// and validate specific metadata streams (strings, blobs, GUIDs, tables) within assembly files.
///
/// ## Binary Layout
///
/// Stream headers have a variable-length binary format:
/// ```text
/// [0-3]   u32     Stream offset from metadata root (4-byte aligned)
/// [4-7]   u32     Stream size in bytes (must be multiple of 4)  
/// [8-N]   CStr    Null-terminated ASCII stream name (max 32 chars)
/// ```
///
/// ## Standard Stream Names
///
/// The ECMA-335 specification defines six standard stream names:
/// - **`#Strings`**: UTF-8 identifier strings (type/member names)
/// - **`#US`**: UTF-16 user string literals (string constants)
/// - **`#Blob`**: Variable-length binary data (signatures, attributes)
/// - **`#GUID`**: 128-bit globally unique identifiers
/// - **`#~`**: Compressed metadata tables (modern assemblies)
/// - **`#-`**: Uncompressed metadata tables (legacy format)
///
/// ## Validation Requirements
///
/// All stream headers must meet ECMA-335 compliance requirements:
/// - Stream size must be 4-byte aligned (divisible by 4)
/// - Offset and size must not exceed 0x7FFFFFFF (2GB limit)
/// - Stream name must match one of the six standard names
/// - Name must be null-terminated ASCII within 32 characters
///
/// ## Thread Safety
///
/// [`StreamHeader`] instances are immutable after construction and safe for concurrent access.
/// All fields contain owned data with no shared references or interior mutability.
///
/// # Examples
///
/// ## Parsing a Metadata Table Stream Header
/// ```rust
/// use dotscope::metadata::streams::StreamHeader;
///
/// # fn example() -> dotscope::Result<()> {
/// // Binary data for "#~" (compressed tables) stream header
/// #[rustfmt::skip]
/// let header_data = [
///     0x6C, 0x00, 0x00, 0x00,  // Offset: 0x6C (108 bytes)
///     0xA4, 0x45, 0x00, 0x00,  // Size: 0x45A4 (17,828 bytes, 4-byte aligned)
///     0x23, 0x7E, 0x00,        // Name: "#~\0" (compressed metadata tables)
/// ];
///
/// let header = StreamHeader::from(&header_data)?;
///
/// assert_eq!(header.offset, 0x6C);
/// assert_eq!(header.size, 0x45A4);
/// assert_eq!(header.name, "#~");
///
/// println!("Compressed metadata tables at offset 0x{:X}, {} bytes",
///          header.offset, header.size);
/// # Ok(())
/// # }
/// ```
///
/// ## Processing String Stream Headers
/// ```rust
/// use dotscope::metadata::streams::StreamHeader;
///
/// # fn example() -> dotscope::Result<()> {
/// // String stream header with null-terminated name
/// #[rustfmt::skip]
/// let strings_header = [
///     0x20, 0x00, 0x00, 0x00,           // Offset: 0x20 (32 bytes)
///     0x48, 0x12, 0x00, 0x00,           // Size: 0x1248 (4,680 bytes)
///     0x23, 0x53, 0x74, 0x72, 0x69,     // "#Strings" name
///     0x6E, 0x67, 0x73, 0x00,           // null-terminated
/// ];
///
/// let header = StreamHeader::from(&strings_header)?;
///
/// assert_eq!(header.name, "#Strings");
/// assert!(header.size % 4 == 0); // ECMA-335 alignment requirement
///
/// match header.name.as_str() {
///     "#Strings" => println!("Found identifier strings stream"),
///     "#US" => println!("Found user strings stream"),
///     "#Blob" => println!("Found binary data stream"),
///     "#GUID" => println!("Found GUID stream"),
///     "#~" => println!("Found compressed metadata tables"),
///     "#-" => println!("Found uncompressed metadata tables"),
///     _ => unreachable!("Invalid stream names are rejected during parsing"),
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## Error Handling for Invalid Headers
/// ```rust
/// use dotscope::metadata::streams::StreamHeader;
///
/// # fn example() {
/// // Invalid header with unaligned size
/// #[rustfmt::skip]
/// let invalid_size = [
///     0x6C, 0x00, 0x00, 0x00,  // Valid offset
///     0xA5, 0x45, 0x00, 0x00,  // Invalid size (not divisible by 4)
///     0x23, 0x7E, 0x00,        // Valid name
/// ];
///
/// assert!(StreamHeader::from(&invalid_size).is_err());
///
/// // Invalid header with unknown stream name
/// #[rustfmt::skip]
/// let invalid_name = [
///     0x6C, 0x00, 0x00, 0x00,  // Valid offset
///     0xA4, 0x45, 0x00, 0x00,  // Valid size
///     0x24, 0x58, 0x00,        // Invalid name "$X\0"
/// ];
///
/// assert!(StreamHeader::from(&invalid_name).is_err());
/// # }
/// ```
///
/// # References
/// - [ECMA-335 II.24.2.2](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf): Stream header format specification
/// - [`crate::metadata::streams`]: Overview of metadata stream architecture
/// - [`crate::metadata::root`]: Metadata root and stream directory parsing
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamHeader {
    /// Byte offset from the metadata root to the start of this stream's data.
    ///
    /// The offset is relative to the beginning of the metadata section and must point
    /// to a valid location within the assembly file. Values must not exceed 0x7FFFFFFF
    /// (2GB limit) to prevent integer overflow attacks.
    ///
    /// ## ECMA-335 Compliance
    /// - Must be a valid file offset within the metadata section
    /// - Subject to reasonable bounds checking (≤ 2GB)
    /// - Points to 4-byte aligned stream data (implementation detail)
    pub offset: u32,

    /// Size of this stream's data in bytes, must be a multiple of 4 per ECMA-335.
    ///
    /// The size represents the exact byte count of stream data. ECMA-335 Section II.24.2.2
    /// states sizes should be 4-byte aligned, but many real-world tools produce unaligned
    /// sizes which are tolerated for compatibility.
    ///
    /// ## Validation Rules
    /// - Should be divisible by 4 per spec (unaligned values are tolerated)
    /// - Must not exceed 0x7FFFFFFF (2GB limit)
    /// - Zero size is valid for empty streams
    ///
    /// ## Security Considerations
    /// - Bounds checked to prevent integer overflow attacks
    /// - Combined with offset validation to prevent out-of-bounds access
    pub size: u32,

    /// Stream identifier name, null-terminated ASCII string (maximum 32 characters).
    ///
    /// The name uniquely identifies the stream type and must match one of the six
    /// standard stream names defined in ECMA-335. Names are case-sensitive and
    /// must be properly null-terminated within the 32-character limit.
    ///
    /// ## Valid Stream Names
    /// - **`#Strings`**: UTF-8 identifier strings (namespaces, type names, member names)
    /// - **`#US`**: UTF-16 user string literals (string constants from IL code)
    /// - **`#Blob`**: Variable-length binary data (method signatures, custom attributes)
    /// - **`#GUID`**: 128-bit globally unique identifiers (assembly correlation)
    /// - **`#~`**: Compressed metadata tables (modern .NET assemblies, space-efficient)
    /// - **`#-`**: Uncompressed metadata tables (legacy format, rarely used)
    ///
    /// ## Security and Validation
    /// - Only standard ECMA-335 names are accepted to prevent malformed metadata
    /// - ASCII encoding enforced during parsing to prevent encoding attacks
    /// - Maximum length limit prevents buffer overflow vulnerabilities
    pub name: String,
}

impl StreamHeader {
    /// Parse a stream header from binary data according to ECMA-335 specification.
    ///
    /// Creates a [`StreamHeader`] by parsing the binary format defined in ECMA-335 Section II.24.2.2.
    /// The method performs comprehensive validation to ensure compliance with the specification
    /// and protect against malformed metadata that could cause security vulnerabilities.
    ///
    /// ## Binary Format Parsed
    /// ```text
    /// Offset | Size | Field       | Description
    /// -------|------|-------------|------------------------------------------
    /// 0      | 4    | Offset      | Stream data offset from metadata root (LE)
    /// 4      | 4    | Size        | Stream size in bytes (LE, 4-byte aligned)
    /// 8      | N+1  | Name        | Null-terminated ASCII name (max 32 chars)
    /// ```
    ///
    /// ## Validation Performed
    ///
    /// This method enforces all ECMA-335 compliance requirements:
    /// 1. **Minimum size**: Data must contain at least 9 bytes (8-byte header + 1 name byte)
    /// 2. **4-byte alignment**: Stream size must be divisible by 4
    /// 3. **Range limits**: Offset and size must not exceed 0x7FFFFFFF (2GB)
    /// 4. **Valid stream names**: Name must match one of six standard ECMA-335 stream identifiers
    /// 5. **Null termination**: Name must be properly null-terminated within 32 characters
    /// 6. **ASCII encoding**: Name must contain only valid ASCII characters
    ///
    /// ## Standard Stream Names
    /// - `#Strings`: UTF-8 identifier strings
    /// - `#US`: UTF-16 user string literals  
    /// - `#Blob`: Variable-length binary data
    /// - `#GUID`: 128-bit globally unique identifiers
    /// - `#~`: Compressed metadata tables
    /// - `#-`: Uncompressed metadata tables
    ///
    /// # Arguments
    /// * `data` - Binary data slice containing the stream header to parse
    ///
    /// # Returns
    /// * `Ok(StreamHeader)` - Successfully parsed and validated stream header
    /// * `Err(Error)` - Parsing failed due to insufficient data or validation errors
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error`] in the following cases:
    /// - **[`crate::Error::OutOfBounds`]**: Data slice too short (< 9 bytes)
    /// - **Malformed data**: Stream size not 4-byte aligned (ECMA-335 violation)
    /// - **Range error**: Offset or size exceeds 0x7FFFFFFF (integer overflow protection)
    /// - **Invalid name**: Stream name doesn't match standard ECMA-335 identifiers
    /// - **Format error**: Name not properly null-terminated or contains non-ASCII
    ///
    /// # Examples
    ///
    /// ## Parsing Valid Stream Headers
    /// ```rust
    /// use dotscope::metadata::streams::StreamHeader;
    ///
    /// # fn example() -> dotscope::Result<()> {
    /// // Compressed metadata tables stream header
    /// #[rustfmt::skip]
    /// let tables_header = [
    ///     0x6C, 0x00, 0x00, 0x00,  // Offset: 0x6C
    ///     0xA4, 0x45, 0x00, 0x00,  // Size: 0x45A4 (4-byte aligned)
    ///     0x23, 0x7E, 0x00,        // Name: "#~\0"
    /// ];
    ///
    /// let header = StreamHeader::from(&tables_header)?;
    /// assert_eq!(header.name, "#~");
    /// assert_eq!(header.offset, 0x6C);
    /// assert_eq!(header.size, 0x45A4);
    /// assert!(header.size % 4 == 0); // ECMA-335 alignment verified
    ///
    /// // Strings stream header with longer name
    /// #[rustfmt::skip]
    /// let strings_header = [
    ///     0x20, 0x00, 0x00, 0x00,           // Offset: 0x20
    ///     0x48, 0x12, 0x00, 0x00,           // Size: 0x1248
    ///     0x23, 0x53, 0x74, 0x72, 0x69,     // "#Strings"
    ///     0x6E, 0x67, 0x73, 0x00,           // null-terminated
    /// ];
    ///
    /// let header = StreamHeader::from(&strings_header)?;
    /// assert_eq!(header.name, "#Strings");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Error Cases and Validation
    /// ```rust
    /// use dotscope::metadata::streams::StreamHeader;
    ///
    /// # fn example() {
    /// // Error: Data too short
    /// let too_short = [0x6C, 0x00, 0x00, 0x00, 0xA4]; // Only 5 bytes
    /// assert!(StreamHeader::from(&too_short).is_err());
    ///
    /// // Error: Size not 4-byte aligned
    /// #[rustfmt::skip]
    /// let unaligned = [
    ///     0x6C, 0x00, 0x00, 0x00,  // Valid offset
    ///     0xA5, 0x45, 0x00, 0x00,  // Size 0x45A5 (not divisible by 4)
    ///     0x23, 0x7E, 0x00,        // Valid name
    /// ];
    /// assert!(StreamHeader::from(&unaligned).is_err());
    ///
    /// // Error: Invalid stream name
    /// #[rustfmt::skip]
    /// let invalid_name = [
    ///     0x6C, 0x00, 0x00, 0x00,  // Valid offset
    ///     0xA4, 0x45, 0x00, 0x00,  // Valid size
    ///     0x24, 0x58, 0x00,        // Invalid name "$X\0"
    /// ];
    /// assert!(StreamHeader::from(&invalid_name).is_err());
    ///
    /// // Error: Offset too large (> 2GB)
    /// #[rustfmt::skip]
    /// let large_offset = [
    ///     0xFF, 0xFF, 0xFF, 0xFF,  // Offset: 0xFFFFFFFF (> 0x7FFFFFFF)
    ///     0xA4, 0x45, 0x00, 0x00,  // Valid size
    ///     0x23, 0x7E, 0x00,        // Valid name
    /// ];
    /// assert!(StreamHeader::from(&large_offset).is_err());
    /// # }
    /// ```
    ///
    /// ## Processing Multiple Headers
    /// ```rust
    /// use dotscope::metadata::streams::StreamHeader;
    ///
    /// # fn example() -> dotscope::Result<()> {
    /// // Directory with multiple stream headers
    /// let directory_data = [
    ///     // First header: "#~" stream
    ///     0x6C, 0x00, 0x00, 0x00, 0xA4, 0x45, 0x00, 0x00, 0x23, 0x7E, 0x00, 0x00,
    ///     // Second header would follow at proper alignment...
    /// ];
    ///
    /// let mut offset = 0;
    /// let mut streams = Vec::new();
    ///
    /// while offset < directory_data.len() {
    ///     match StreamHeader::from(&directory_data[offset..]) {
    ///         Ok(header) => {
    ///             println!("Found stream: {}", header.name);
    ///             streams.push(header);
    ///             // Calculate next header offset (implementation specific)
    ///             break; // For this example
    ///         }
    ///         Err(_) => break,
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # ECMA-335 Compliance
    ///
    /// This implementation fully complies with ECMA-335 Partition II, Section 24.2.2
    /// including all validation requirements and format specifications.
    ///
    /// # See Also
    /// - [`crate::metadata::root`]: Metadata root parsing for stream directory context
    /// - [ECMA-335 II.24.2.2](https://ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf): Official stream header specification
    pub fn from(data: &[u8]) -> Result<StreamHeader> {
        if data.len() < 9 {
            return Err(out_of_bounds_error!());
        }

        let offset = read_le::<u32>(data)?;
        let size = read_le::<u32>(&data[4..])?;

        // ECMA-335 II.24.2.2 says stream sizes "shall be a multiple of 4", but many real-world
        // .NET tools (AsmResolver, Mono's writer, etc.) produce unaligned sizes. The .NET runtime
        // handles this gracefully, so we tolerate it here and use the actual size as-is. The stream
        // data at [offset..offset+size] is still valid regardless of alignment.

        // Validate offset bounds - offset must be reasonable
        if offset > 0x7FFF_FFFF {
            return Err(malformed_error!(
                "Stream offset {} exceeds maximum allowed value (0x7FFFFFFF)",
                offset
            ));
        }

        // Validate size bounds - prevent integer overflow and unreasonable sizes
        if size > 0x7FFF_FFFF {
            return Err(malformed_error!(
                "Stream size {} exceeds maximum allowed value (0x7FFFFFFF)",
                size
            ));
        }

        let mut name = String::with_capacity(32);
        for counter in 0..std::cmp::min(32, data.len() - 8) {
            let name_char = read_le::<u8>(&data[8 + counter..])?;
            if name_char == 0 {
                break;
            }

            name.push(char::from(name_char));
        }

        if !["#Strings", "#US", "#Blob", "#GUID", "#~", "#-"]
            .iter()
            .any(|valid_name| name == *valid_name)
        {
            return Err(malformed_error!("Invalid stream header name - {}", name));
        }

        Ok(StreamHeader { offset, size, name })
    }

    /// Writes this stream header to a writer in ECMA-335 binary format.
    ///
    /// Serializes the stream header including offset, size, and null-terminated name
    /// with proper 4-byte alignment padding according to ECMA-335 Section II.24.2.2.
    ///
    /// ## Binary Format Written
    /// ```text
    /// Offset | Size | Field  | Description
    /// -------|------|--------|------------------------------------------
    /// 0      | 4    | Offset | Stream data offset from metadata root (LE)
    /// 4      | 4    | Size   | Stream size in bytes (LE)
    /// 8      | N    | Name   | Null-terminated ASCII name
    /// 8+N    | P    | Pad    | Zero padding to 4-byte boundary
    /// ```
    ///
    /// # Arguments
    /// * `writer` - Any type implementing [`std::io::Write`]
    ///
    /// # Returns
    /// * `Ok(())` - Header written successfully
    /// * `Err(Error)` - Write operation failed
    ///
    /// # Examples
    /// ```rust,no_run
    /// use dotscope::metadata::streams::StreamHeader;
    ///
    /// # fn example() -> dotscope::Result<()> {
    /// let header = StreamHeader {
    ///     offset: 0x6C,
    ///     size: 0x1000,
    ///     name: "#~".to_string(),
    /// };
    ///
    /// let mut buffer = Vec::new();
    /// header.write_to(&mut buffer)?;
    ///
    /// // Buffer contains: offset (4) + size (4) + "#~\0" (3) + padding (1) = 12 bytes
    /// assert_eq!(buffer.len(), 12);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the writer fails.
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        // Write offset (4 bytes, little-endian)
        writer.write_all(&self.offset.to_le_bytes())?;

        // Write size (4 bytes, little-endian)
        writer.write_all(&self.size.to_le_bytes())?;

        // Write null-terminated name
        writer.write_all(self.name.as_bytes())?;
        writer.write_all(&[0u8])?; // Null terminator

        // Pad to 4-byte boundary
        // Name length + 1 (null terminator), padded to multiple of 4
        let name_with_null = self.name.len() + 1;
        let padded_len = (name_with_null + 3) & !3;
        let padding = padded_len - name_with_null;
        if padding > 0 {
            writer.write_all(&vec![0u8; padding])?;
        }

        Ok(())
    }

    /// Returns the total serialized size of this stream header in bytes.
    ///
    /// The size includes the fixed fields (offset + size = 8 bytes) plus the
    /// null-terminated name padded to a 4-byte boundary.
    ///
    /// # Returns
    /// The total size in bytes when written with [`write_to`](Self::write_to).
    ///
    /// # Examples
    /// ```rust
    /// use dotscope::metadata::streams::StreamHeader;
    ///
    /// let header = StreamHeader {
    ///     offset: 0x6C,
    ///     size: 0x1000,
    ///     name: "#~".to_string(),
    /// };
    ///
    /// // 8 (fixed) + ceil4("#~\0") = 8 + 4 = 12
    /// assert_eq!(header.serialized_size(), 12);
    ///
    /// let strings_header = StreamHeader {
    ///     offset: 0x20,
    ///     size: 0x500,
    ///     name: "#Strings".to_string(),
    /// };
    ///
    /// // 8 (fixed) + ceil4("#Strings\0") = 8 + 12 = 20
    /// assert_eq!(strings_header.serialized_size(), 20);
    /// ```
    #[must_use]
    pub fn serialized_size(&self) -> usize {
        let name_with_null = self.name.len() + 1;
        let padded_name = (name_with_null + 3) & !3;
        8 + padded_name // offset (4) + size (4) + padded name
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn crafted() {
        #[rustfmt::skip]
        let header_bytes = [
            0x6C, 0x00, 0x00, 0x00,
            0xA4, 0x45, 0x00, 0x00,
            0x23, 0x7E, 0x00,
        ];

        let parsed_header = StreamHeader::from(&header_bytes).unwrap();

        assert_eq!(parsed_header.offset, 0x6C);
        assert_eq!(parsed_header.size, 0x45A4);
        assert_eq!(parsed_header.name, "#~");
    }

    #[test]
    fn crafted_invalid() {
        #[rustfmt::skip]
        let header_bytes = [
            0x6C, 0x00, 0x00, 0x00,
            0xA4, 0x45, 0x00, 0x00,
            0x24, 0x7E, 0x00,
        ];

        if StreamHeader::from(&header_bytes).is_ok() {
            panic!("This should not be valid!")
        }
    }

    #[test]
    fn test_write_to_short_name() {
        let header = StreamHeader {
            offset: 0x6C,
            size: 0x45A4,
            name: "#~".to_string(),
        };

        let mut buffer = Vec::new();
        header.write_to(&mut buffer).unwrap();

        // Expected: offset (4) + size (4) + "#~\0" (3) + padding (1) = 12 bytes
        assert_eq!(buffer.len(), 12);

        // Verify offset
        assert_eq!(&buffer[0..4], &[0x6C, 0x00, 0x00, 0x00]);
        // Verify size
        assert_eq!(&buffer[4..8], &[0xA4, 0x45, 0x00, 0x00]);
        // Verify name "#~" + null + padding
        assert_eq!(&buffer[8..12], &[0x23, 0x7E, 0x00, 0x00]);
    }

    #[test]
    fn test_write_to_long_name() {
        let header = StreamHeader {
            offset: 0x20,
            size: 0x1248,
            name: "#Strings".to_string(),
        };

        let mut buffer = Vec::new();
        header.write_to(&mut buffer).unwrap();

        // Expected: offset (4) + size (4) + "#Strings\0" (9) + padding (3) = 20 bytes
        assert_eq!(buffer.len(), 20);

        // Verify offset
        assert_eq!(&buffer[0..4], &[0x20, 0x00, 0x00, 0x00]);
        // Verify size
        assert_eq!(&buffer[4..8], &[0x48, 0x12, 0x00, 0x00]);
        // Verify name "#Strings" + null + padding
        assert_eq!(
            &buffer[8..20],
            &[0x23, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, 0x73, 0x00, 0x00, 0x00, 0x00]
        );
    }

    #[test]
    fn test_serialized_size() {
        // "#~" (2 chars) + null = 3, padded to 4
        let header = StreamHeader {
            offset: 0,
            size: 0,
            name: "#~".to_string(),
        };
        assert_eq!(header.serialized_size(), 12); // 8 + 4

        // "#Strings" (8 chars) + null = 9, padded to 12
        let header = StreamHeader {
            offset: 0,
            size: 0,
            name: "#Strings".to_string(),
        };
        assert_eq!(header.serialized_size(), 20); // 8 + 12

        // "#US" (3 chars) + null = 4, already aligned
        let header = StreamHeader {
            offset: 0,
            size: 0,
            name: "#US".to_string(),
        };
        assert_eq!(header.serialized_size(), 12); // 8 + 4

        // "#GUID" (5 chars) + null = 6, padded to 8
        let header = StreamHeader {
            offset: 0,
            size: 0,
            name: "#GUID".to_string(),
        };
        assert_eq!(header.serialized_size(), 16); // 8 + 8

        // "#Blob" (5 chars) + null = 6, padded to 8
        let header = StreamHeader {
            offset: 0,
            size: 0,
            name: "#Blob".to_string(),
        };
        assert_eq!(header.serialized_size(), 16); // 8 + 8
    }

    #[test]
    fn test_write_read_roundtrip() {
        let original = StreamHeader {
            offset: 0x1234,
            size: 0x5678,
            name: "#Blob".to_string(),
        };

        let mut buffer = Vec::new();
        original.write_to(&mut buffer).unwrap();

        let parsed = StreamHeader::from(&buffer).unwrap();
        assert_eq!(parsed.offset, original.offset);
        assert_eq!(parsed.size, original.size);
        assert_eq!(parsed.name, original.name);
    }
}