PkmnLib_rs/src/ffi/static_data/item.rs

59 lines
2.1 KiB
Rust
Raw Normal View History

use crate::ffi::ffi_handle::{FFIHandle, FromFFIHandle};
use crate::ffi::{ffi_handle_arc_dyn_getter, FFIResult, OwnedPtrString};
2022-11-27 16:29:29 +00:00
use crate::static_data::{BattleItemCategory, Item, ItemCategory, ItemImpl};
2022-09-18 16:02:13 +00:00
use crate::StringKey;
use anyhow::anyhow;
2022-09-18 16:02:13 +00:00
use hashbrown::HashSet;
use std::ffi::{c_char, CStr, CString};
use std::sync::Arc;
2022-09-18 16:02:13 +00:00
2022-10-14 14:53:30 +00:00
/// Instantiates an item.
2022-09-18 16:02:13 +00:00
#[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>>> {
2022-09-18 16:02:13 +00:00
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")),
};
2022-09-18 16:02:13 +00:00
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());
2022-09-18 16:02:13 +00:00
}
2022-11-27 16:29:29 +00:00
let item: Arc<dyn Item> = Arc::new(ItemImpl::new(&name, category, battle_category, price, flags_set));
FFIResult::ok(FFIHandle::get_handle(item.into()))
2022-09-18 16:02:13 +00:00
}
2022-10-14 14:53:30 +00:00
/// The name of the item.
2022-09-18 16:02:13 +00:00
#[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(name.into_raw()),
Err(_) => FFIResult::err(anyhow!("Unable to convert name `{}` to CString", name.str())),
}
2022-09-18 16:02:13 +00:00
}
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);
2022-09-18 16:02:13 +00:00
2022-10-14 14:53:30 +00:00
/// Checks whether the item has a specific flag.
2022-09-18 16:02:13 +00:00
#[no_mangle]
unsafe extern "C" fn item_has_flag(ptr: FFIHandle<Arc<dyn Item>>, flag: *const c_char) -> u8 {
2022-09-18 16:02:13 +00:00
let flag = CStr::from_ptr(flag).into();
u8::from(ptr.from_ffi_handle().has_flag(&flag))
2022-09-18 16:02:13 +00:00
}