oc2_hlapi_v2 0.2.0

A client for the new version of OpenComputers II's HLAPI
Documentation
//! The item handler device and its associated types
//!
//! [OC2 Docs](https://fnuecke.github.io/oc2/manual/en_us/device/item_handler.html)

use std::convert::Infallible;

use thiserror::Error;
use uuid::Uuid;

use crate::{
    client::{DeviceBase, HlapiClient, HlapiClientError},
    devices::ItemStack,
};

#[derive(Debug, Clone)]
/// An item handler device
pub struct ItemHandler {
    client: HlapiClient,
    uuid: Uuid,
    slot_count: u32,
}

/// The possible errors for device functions
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum ItemHandlerError {
    #[error("HLAPI client error: {0}")]
    /// HLAPI client error
    HlapiClientError(#[from] HlapiClientError),
    #[error("Slot index out of range")]
    /// Slot index out of range
    SlotIndexOutOfRange,
}

impl ItemHandler {
    /// Gets how many slots the inventory has
    #[must_use]
    pub fn get_item_slot_count(&self) -> u32 {
        self.slot_count
    }

    /// Gets how many items the specified slot can hold. Slots are 0-indexed.
    pub fn get_item_slot_limit(&self, slot: u32) -> Result<u32, ItemHandlerError> {
        if slot >= self.slot_count {
            return Err(ItemHandlerError::SlotIndexOutOfRange);
        }
        Ok(self.call("getItemSlotLimit", &[&slot as _], &[])?.0)
    }

    /// Gets the contents of the specified slot. An empty slot returns [`None`]. Slots are
    /// 0-indexed.
    pub fn get_item_stack_in_slot(&self, slot: u32) -> Result<Option<ItemStack>, ItemHandlerError> {
        if slot >= self.slot_count {
            return Err(ItemHandlerError::SlotIndexOutOfRange);
        }
        Ok(self.call("getItemStackInSlot", &[&slot as _], &[])?.0)
    }
}

impl DeviceBase for ItemHandler {
    const TYPE: &'static str = "item_handler";

    type Event = Infallible;

    fn new(client: HlapiClient, uuid: Uuid) -> Result<Self, HlapiClientError> {
        let mut slf = Self {
            client,
            uuid,
            slot_count: 0,
        };
        slf.slot_count = slf.call("getItemSlotCount", &[], &[])?.0;
        Ok(slf)
    }

    fn uuid_base(&self) -> Uuid {
        self.uuid
    }

    fn client(&self) -> &HlapiClient {
        &self.client
    }
}