hao 0.0.19

Read, edit, create and write .net assemblies
Documentation
//! The `#~` tables stream (ECMA-335 §II.24.2.6): its header, where each table
//! is, and the row types.
//!
//! A row is a `<Table>TableRow` struct, e.g. [`TypeDefTableRow`]. Its columns
//! are typed by what they point at:
//!
//! - heap offsets: [`StringsStreamOffset`], [`BlobStreamOffset`],
//!   [`GuidStreamOffset`];
//! - row indexes into one table, 1-based with 0 for none: `<Table>TableOffset`,
//!   e.g. [`FieldTableOffset`];
//! - [coded indexes](coded_tokens) into one of several tables:
//!   [`CodedToken`](coded_tokens::CodedToken).
//!
//! Each column is 2 or 4 bytes depending on heap and table sizes, which the
//! [`TablesStreamsHeader`] works out.

pub mod coded_tokens;
pub mod metadata;
mod reader;
mod streams_offsets;
mod tables;
pub mod values;

use self::{
    coded_tokens::CodedTokenSizes,
    metadata::{TableExistsFlags, TableLocations, TableRowCount, TableRows},
};
use super::Version;
use crate::{
    dotnet::md::MDStreamFlags,
    error::Result,
    io::{DataReader, ReadData, Readable},
};
pub use reader::*;
pub use streams_offsets::*;
pub use tables::*;

/// Where one table's rows are in the tables stream.
#[derive(Debug, Clone, Copy)]
pub struct TableLocation {
    /// Byte offset of the first row, from the end of the stream header.
    pub start_offset: usize,
    /// Number of rows.
    pub rows: TableRowCount,
    /// Size of one row in bytes, which depends on the column widths.
    pub row_size: usize,
}

/// Width of an index column: 2 or 4 bytes, depending on heap or table sizes.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ValueSize {
    /// 2 bytes.
    Small,
    /// 4 bytes.
    Big,
}

impl ValueSize {
    /// The width in bytes: 2 or 4.
    #[inline(always)]
    pub fn byte_size(&self) -> usize {
        match self {
            ValueSize::Big => std::mem::size_of::<u32>(),
            ValueSize::Small => std::mem::size_of::<u16>(),
        }
    }
}

/// The tables stream header, plus the column widths and table layout worked
/// out from it.
#[derive(Debug, Clone)]
pub struct TablesStreamsHeader {
    /// Which tables are present (the `Valid` mask).
    pub valid_tables: TableExistsFlags,
    /// Row count, position and row size of every table.
    pub table_locations: TableLocations,
    /// Heap index widths and other flags (the `HeapSizes` byte).
    pub flags: MDStreamFlags,
    /// Schema version, usually 2.0.
    pub version: Version,
    /// Which tables are sorted (the `Sorted` mask).
    pub sorted_tables: TableExistsFlags,
    /// Width of each kind of coded index.
    pub coded_token_sizes: CodedTokenSizes,
}

impl Readable for TablesStreamsHeader {
    fn from_reader(reader: &mut DataReader) -> Result<Self> {
        let _reserved1: u32 = reader.read()?;
        let major_version: u8 = reader.read()?;
        let minor_version: u8 = reader.read()?;
        let flags = MDStreamFlags::from_bits_retain(reader.read()?);
        let _log_2_rid: u8 = reader.read()?;
        let valid_tables = TableExistsFlags::from_bits_retain(reader.read()?);
        let sorted_tables = TableExistsFlags::from_bits_retain(reader.read()?);

        if flags.contains(MDStreamFlags::ExtraData) {
            let _extra: u32 = reader.read()?;
        }
        let version = Version(major_version, minor_version);
        let table_rows = TableRows::from_reader(reader, valid_tables)?;
        let coded_token_sizes = CodedTokenSizes::from_header(&table_rows);

        let table_lcoations =
            TableLocations::from_metadata(&table_rows, &coded_token_sizes, flags, version);

        Ok(Self {
            valid_tables,
            coded_token_sizes,
            table_locations: table_lcoations,
            flags,
            version,
            sorted_tables,
        })
    }
}

/// The `#~` (or `#-`) stream: its header and the row data.
///
/// Only the Module table has a public row iterator ([`modules`](Self::modules));
/// [`Module`](crate::Module) reads the rest.
#[derive(Debug, Clone)]
pub struct TablesStreams<'a> {
    /// The header and the table layout worked out from it.
    pub header: TablesStreamsHeader,
    //pub values: TablesValues,
    heap_data: &'a [u8],
}

impl<'a> TablesStreams<'a> {
    /// Parses the header; the rest of `reader` is the row data.
    pub fn from_reader(mut reader: DataReader<'a>) -> Result<Self> {
        let header = reader.read()?;

        let heap_data = reader.remaining_slice();

        Ok(Self { header, heap_data })
    }

    pub(crate) fn row_iter<T>(&'a self, location: TableLocation) -> Result<TableRowsIterator<'a, T>>
    where
        TablesStreamReader<'a>: ReadData<T>,
    {
        TableRowsIterator::new(self.heap_data, &self.header, location)
    }

    /// Iterates the Module table's rows. Errors if the table runs past the end of
    /// the stream; each row errors unless the table has exactly one row.
    pub fn modules(&'a self) -> Result<impl Iterator<Item = Result<ModulesTableRow>> + 'a> {
        self.row_iter(self.header.table_locations.module)
    }
}

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

    /// A tables stream: the header for `valid` with these row counts, then `rows`.
    fn stream(valid: TableExistsFlags, counts: &[u32], rows: &[u8]) -> Vec<u8> {
        let mut data = vec![0, 0, 0, 0, 2, 0, 0, 1];
        data.extend_from_slice(&valid.bits().to_le_bytes());
        data.extend_from_slice(&0u64.to_le_bytes());
        for count in counts {
            data.extend_from_slice(&count.to_le_bytes());
        }
        data.extend_from_slice(rows);
        data
    }

    #[test]
    fn local_scope_rows() {
        // Method, ImportScope, VariableList, ConstantList (2 bytes each), then
        // StartOffset and Length (4 bytes each).
        let mut rows = Vec::new();
        for (method, start, length) in [(1u16, 0u32, 10u32), (2, 4, 6)] {
            for index in [method, 0, 1, 1] {
                rows.extend_from_slice(&index.to_le_bytes());
            }
            rows.extend_from_slice(&start.to_le_bytes());
            rows.extend_from_slice(&length.to_le_bytes());
        }
        let data = stream(TableExistsFlags::LocalScope, &[2], &rows);
        let tables = TablesStreams::from_reader(DataReader::new(&data)).unwrap();
        let location = tables.header.table_locations.local_scope;
        assert_eq!(location.row_size, 16);

        let read: Vec<LocalScopeTableRow> = tables
            .row_iter(location)
            .unwrap()
            .collect::<Result<_>>()
            .unwrap();
        assert_eq!(read.len(), 2);
        assert_eq!(read[1].method, MethodTableOffset(2));
        assert_eq!(read[1].variable_list, LocalVariableTableOffset(1));
        assert_eq!(read[1].constant_list, LocalConstantTableOffset(1));
        assert_eq!((read[1].start_offset, read[1].length), (4, 6));
    }
}