PkmnLib_rs/src/ffi/static_data/item.rs

59 lines
2.2 KiB
Rust

use crate::ffi::ffi_handle::{FFIHandle, FromFFIHandle};
use crate::ffi::{ffi_handle_arc_dyn_getter, FFIResult, OwnedPtrString};
use crate::static_data::{BattleItemCategory, Item, ItemCategory, ItemImpl};
use crate::StringKey;
use anyhow::anyhow;
use hashbrown::HashSet;
use std::ffi::{c_char, CStr, CString};
use std::sync::Arc;
/// Instantiates an item.
#[no_mangle]
unsafe extern "C" fn item_new(
name: *const c_char,
category: ItemCategory,
battle_category: BattleItemCategory,
price: i32,
flags: *const *const c_char,
flags_length: usize,
) -> FFIResult<FFIHandle<Arc<dyn Item>>> {
let flags = std::slice::from_raw_parts(flags, flags_length);
let name: StringKey = match CStr::from_ptr(name).to_str() {
Ok(name) => name.into(),
Err(_) => return FFIResult::err(anyhow!("Unable to convert name to string")),
};
let mut flags_set: HashSet<StringKey> = HashSet::with_capacity(flags_length);
for flag in flags {
let flag = match CStr::from_ptr(*flag).to_str() {
Ok(flag) => flag,
Err(_) => return FFIResult::err(anyhow!("Unable to convert flag to string")),
};
flags_set.insert(flag.into());
}
let item: Arc<dyn Item> = Arc::new(ItemImpl::new(&name, category, battle_category, price, flags_set));
FFIResult::ok(FFIHandle::get_handle(item.into()))
}
/// The name of the item.
#[no_mangle]
unsafe extern "C" fn item_name(ptr: FFIHandle<Arc<dyn Item>>) -> FFIResult<OwnedPtrString> {
let item = ptr.from_ffi_handle();
let name = item.name();
match CString::new(name.str()) {
Ok(name) => FFIResult::ok(OwnedPtrString(name.into_raw())),
Err(_) => FFIResult::err(anyhow!("Unable to convert name `{}` to CString", name.str())),
}
}
ffi_handle_arc_dyn_getter!(Item, category, ItemCategory);
ffi_handle_arc_dyn_getter!(Item, battle_category, BattleItemCategory);
ffi_handle_arc_dyn_getter!(Item, price, i32);
/// Checks whether the item has a specific flag.
#[no_mangle]
unsafe extern "C" fn item_has_flag(ptr: FFIHandle<Arc<dyn Item>>, flag: *const c_char) -> u8 {
let flag = CStr::from_ptr(flag).into();
u8::from(ptr.from_ffi_handle().has_flag(&flag))
}