jsxbin-parser 1.0.0

Binary parser for Adobe JSX .jsxbin files with comprehensive AST representation
Documentation
use crate::error::{ParserError, ParserResult};
use byteorder::{LittleEndian, ReadBytesExt};
use std::io::Cursor;

/// Low-level binary data reader with position tracking
pub struct BinaryReader {
    cursor: Cursor<Vec<u8>>,
}

impl BinaryReader {
    /// Create a new reader from raw bytes
    pub fn new(data: Vec<u8>) -> Self {
        BinaryReader {
            cursor: Cursor::new(data),
        }
    }

    /// Current position in the buffer
    pub fn position(&self) -> usize {
        self.cursor.position() as usize
    }

    /// Set position in the buffer
    pub fn seek(&mut self, pos: usize) -> ParserResult<()> {
        use std::io::Seek;
        self.cursor
            .seek(std::io::SeekFrom::Start(pos as u64))
            .map(|_| ())
            .map_err(|e| ParserError::IoError(e.to_string()))
    }

    /// Read a single byte
    pub fn read_u8(&mut self) -> ParserResult<u8> {
        self.cursor
            .read_u8()
            .map_err(|_| ParserError::UnexpectedEof(self.position()))
    }

    /// Peek at the next byte without advancing
    pub fn peek_u8(&self) -> ParserResult<u8> {
        let pos = self.cursor.position() as usize;
        self.cursor
            .get_ref()
            .get(pos)
            .copied()
            .ok_or(ParserError::UnexpectedEof(pos))
    }

    /// Read a 16-bit unsigned integer (little-endian)
    pub fn read_u16_le(&mut self) -> ParserResult<u16> {
        self.cursor
            .read_u16::<LittleEndian>()
            .map_err(|_| ParserError::UnexpectedEof(self.position()))
    }

    /// Read a 32-bit unsigned integer (little-endian)
    pub fn read_u32_le(&mut self) -> ParserResult<u32> {
        self.cursor
            .read_u32::<LittleEndian>()
            .map_err(|_| ParserError::UnexpectedEof(self.position()))
    }

    /// Read a 64-bit unsigned integer (little-endian)
    pub fn read_u64_le(&mut self) -> ParserResult<u64> {
        self.cursor
            .read_u64::<LittleEndian>()
            .map_err(|_| ParserError::UnexpectedEof(self.position()))
    }

    /// Read a 32-bit float (little-endian)
    pub fn read_f32_le(&mut self) -> ParserResult<f32> {
        self.cursor
            .read_f32::<LittleEndian>()
            .map_err(|_| ParserError::UnexpectedEof(self.position()))
    }

    /// Read a 64-bit float (little-endian)
    pub fn read_f64_le(&mut self) -> ParserResult<f64> {
        self.cursor
            .read_f64::<LittleEndian>()
            .map_err(|_| ParserError::UnexpectedEof(self.position()))
    }

    /// Read a string of specific length
    pub fn read_string(&mut self, len: usize) -> ParserResult<String> {
        let mut buf = vec![0u8; len];
        use std::io::Read;
        self.cursor
            .read_exact(&mut buf)
            .map_err(|_| ParserError::UnexpectedEof(self.position()))?;

        String::from_utf8(buf).map_err(|_| {
            ParserError::ParseError {
                offset: self.position(),
                message: "Invalid UTF-8 sequence".to_string(),
            }
        })
    }

    /// Read a null-terminated string
    pub fn read_cstring(&mut self) -> ParserResult<String> {
        let mut result = String::new();
        loop {
            let byte = self.read_u8()?;
            if byte == 0 {
                break;
            }
            result.push(byte as char);
        }
        Ok(result)
    }

    /// Read N bytes into a buffer
    pub fn read_bytes(&mut self, count: usize) -> ParserResult<Vec<u8>> {
        let mut buf = vec![0u8; count];
        use std::io::Read;
        self.cursor
            .read_exact(&mut buf)
            .map_err(|_| ParserError::UnexpectedEof(self.position()))?;
        Ok(buf)
    }

    /// Check if at end of file
    pub fn is_eof(&self) -> bool {
        self.cursor.position() as usize >= self.cursor.get_ref().len()
    }

    /// Get total length
    pub fn len(&self) -> usize {
        self.cursor.get_ref().len()
    }

    /// Check if buffer is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Remaining bytes to read
    pub fn remaining(&self) -> usize {
        self.len() - self.position()
    }
}

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

    #[test]
    fn test_read_u8() {
        let mut reader = BinaryReader::new(vec![42, 43, 44]);
        assert_eq!(reader.read_u8().unwrap(), 42);
        assert_eq!(reader.position(), 1);
    }

    #[test]
    fn test_read_u32_le() {
        let bytes = vec![0x01, 0x02, 0x03, 0x04];
        let mut reader = BinaryReader::new(bytes);
        assert_eq!(reader.read_u32_le().unwrap(), 0x04030201);
    }

    #[test]
    fn test_peek_u8() {
        let mut reader = BinaryReader::new(vec![42]);
        assert_eq!(reader.peek_u8().unwrap(), 42);
        assert_eq!(reader.position(), 0); // Position unchanged
    }

    #[test]
    fn test_eof() {
        let mut reader = BinaryReader::new(vec![42]);
        reader.read_u8().unwrap();
        assert!(reader.is_eof());
    }
}