java-serialization 0.1.0

Java object serialization stream parser written in Rust
Documentation
use crate::constants::BASE_WIRE_HANDLE;
use crate::types::StreamObject;

/// Manages handle assignments during deserialization.
/// Handles are assigned sequentially starting from BASE_WIRE_HANDLE (0x7E0000).
#[derive(Debug, Clone)]
pub struct HandleTable {
    next_handle: u32,
    objects: Vec<Option<StreamObject>>,
}

impl HandleTable {
    pub fn new() -> Self {
        HandleTable {
            next_handle: BASE_WIRE_HANDLE,
            objects: Vec::new(),
        }
    }

    /// Assign a new handle and store the object.
    /// Returns the assigned handle value.
    pub fn assign(&mut self, obj: StreamObject) -> u32 {
        let handle = self.next_handle;
        self.objects.push(Some(obj));
        self.next_handle += 1;
        handle
    }

    /// Assign a new handle without storing an object (placeholder).
    /// Useful when the object is being built and will be filled later.
    pub fn assign_handle(&mut self) -> u32 {
        let handle = self.next_handle;
        self.objects.push(None);
        self.next_handle += 1;
        handle
    }

    /// Update the object at the given handle.
    pub fn update(&mut self, handle: u32, obj: StreamObject) {
        let index = (handle - BASE_WIRE_HANDLE) as usize;
        if index < self.objects.len() {
            self.objects[index] = Some(obj);
        }
    }

    /// Get a reference to the object at the given handle.
    pub fn get(&self, handle: u32) -> Option<&StreamObject> {
        let index = (handle - BASE_WIRE_HANDLE) as usize;
        self.objects.get(index).and_then(|opt| opt.as_ref())
    }

    /// Reset the handle table (TC_RESET).
    pub fn reset(&mut self) {
        self.next_handle = BASE_WIRE_HANDLE;
        self.objects.clear();
    }

    /// Save the current state for potential rollback.
    pub fn snapshot(&self) -> HandleSnapshot {
        HandleSnapshot {
            next_handle: self.next_handle,
            objects_len: self.objects.len(),
        }
    }

    /// Restore to a previously saved snapshot.
    pub fn rollback(&mut self, snapshot: HandleSnapshot) {
        self.next_handle = snapshot.next_handle;
        self.objects.truncate(snapshot.objects_len);
    }
}

/// Snapshot of handle table state for rollback.
#[derive(Debug)]
pub struct HandleSnapshot {
    next_handle: u32,
    objects_len: usize,
}

impl Default for HandleTable {
    fn default() -> Self {
        Self::new()
    }
}