hao 0.0.19

Read, edit, create and write .net assemblies
Documentation
use crate::{
    error::{HaoError, Result},
    io::DataReader,
};

/// The `#Strings` heap (ECMA-335 §II.24.2.3): null-terminated UTF-8 names of
/// types, members, namespaces and so on.
#[derive(Debug, Clone)]
pub struct StringsStream<'a> {
    /// The heap's bytes.
    pub heap_data: &'a [u8],
}

impl<'a> StringsStream<'a> {
    /// Uses the rest of `reader` as the heap.
    pub fn from_reader(reader: DataReader<'a>) -> Result<Self> {
        Ok(Self {
            heap_data: reader.remaining_slice(),
        })
    }

    /// Reads the string at byte `offset`. Errors if it is out of range, not
    /// null-terminated, or not UTF-8.
    pub fn read_string(&self, offset: u32) -> Result<&str> {
        let offset = offset as usize;

        if offset > self.heap_data.len() {
            return Err(HaoError::InvalidStreamIndex("#Strings", offset));
        }

        let slice = &self.heap_data[offset..];
        let terminator = slice
            .iter()
            .position(|c| *c == 0)
            .ok_or(HaoError::InvalidStreamIndex("#Strings", offset))?;

        std::str::from_utf8(&slice[..terminator])
            .map_err(|_| HaoError::InvalidUTF8String(offset, Vec::from(&slice[..terminator])))
    }
}

/// The `#GUID` heap (ECMA-335 §II.24.2.5): 16-byte GUIDs, indexed from 1.
#[derive(Debug, Clone)]
pub struct GuidStream<'a> {
    /// The heap's bytes.
    pub heap_data: &'a [u8],
}

impl<'a> GuidStream<'a> {
    /// Uses the rest of `reader` as the heap.
    pub fn from_reader(reader: DataReader<'a>) -> Result<Self> {
        Ok(Self {
            heap_data: reader.remaining_slice(),
        })
    }

    /// Reads the GUID at 1-based index `offset` (byte `(offset - 1) * 16`); 0
    /// gives the nil GUID. Stored as .NET lays a GUID out: the first three
    /// fields little-endian.
    pub fn read_guid(&self, offset: u32) -> Result<uuid::Uuid> {
        const GUID_SIZE: usize = 16;

        if offset == 0 {
            return Ok(uuid::Uuid::nil());
        }

        let position = ((offset - 1) as usize).saturating_mul(GUID_SIZE);
        let bytes: [u8; GUID_SIZE] = position
            .checked_add(GUID_SIZE)
            .and_then(|end| self.heap_data.get(position..end))
            .and_then(|bytes| bytes.try_into().ok())
            .ok_or(HaoError::InvalidStreamIndex("#GUID", position))?;

        Ok(uuid::Uuid::from_bytes_le(bytes))
    }
}

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

    #[test]
    fn guids_are_little_endian_16_byte_entries() {
        // .NET stores Data1..Data3 little-endian (as `Guid.ToByteArray` does).
        let first = uuid::Uuid::parse_str("00112233-4455-6677-8899-aabbccddeeff").unwrap();
        let second = uuid::Uuid::parse_str("01020304-0506-0708-090a-0b0c0d0e0f10").unwrap();
        let mut heap = vec![
            0x33, 0x22, 0x11, 0x00, 0x55, 0x44, 0x77, 0x66, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
            0xee, 0xff,
        ];
        heap.extend_from_slice(&second.to_bytes_le());
        let stream = GuidStream { heap_data: &heap };

        assert_eq!(stream.read_guid(0).unwrap(), uuid::Uuid::nil());
        assert_eq!(stream.read_guid(1).unwrap(), first);
        assert_eq!(stream.read_guid(2).unwrap(), second);
        assert!(stream.read_guid(3).is_err());

        // A truncated last entry is out of range, not a panic.
        let short = GuidStream {
            heap_data: &heap[..24],
        };
        assert!(short.read_guid(2).is_err());
    }
}