use crate::ffi::FFIHandle; use crate::ffi::FromFFIHandle; use crate::ffi::{FFIResult, OwnedPtrString}; use crate::static_data::{Ability, AbilityImpl, EffectParameter}; use crate::StringKey; use anyhow::anyhow; use std::ffi::{c_char, CStr, CString}; use std::sync::Arc; /// Instantiates a new ability. #[no_mangle] unsafe extern "C" fn ability_new( name: *const c_char, effect: *const c_char, parameters: *const FFIHandle>, parameters_length: usize, ) -> FFIResult>> { let parameters = std::slice::from_raw_parts(parameters, parameters_length); let mut parameters_vec: Vec> = Vec::with_capacity(parameters_length); for parameter in parameters { parameters_vec.push(parameter.from_ffi_handle()); } let name: StringKey = match CStr::from_ptr(name).to_str() { Ok(s) => s.into(), Err(_) => return FFIResult::err(anyhow!("Failed to convert name to CStr")), }; let effect: StringKey = match CStr::from_ptr(effect).to_str() { Ok(s) => s.into(), Err(_) => return FFIResult::err(anyhow!("Failed to convert effect to CStr")), }; let arc: Arc = Arc::new(AbilityImpl::new(&name, &effect, parameters_vec)); FFIResult::ok(FFIHandle::get_handle(arc.into())) } /// The name of the ability. #[no_mangle] unsafe extern "C" fn ability_name(handle: FFIHandle>) -> FFIResult { match CString::new(handle.from_ffi_handle().name().str()) { Ok(s) => FFIResult::ok(OwnedPtrString(s.into_raw())), Err(_) => FFIResult::err(anyhow!("Failed to convert name to CString")), } } /// The name of the script effect of the ability. #[no_mangle] unsafe extern "C" fn ability_effect(ptr: FFIHandle>) -> FFIResult { match CString::new(ptr.from_ffi_handle().effect().str()) { Ok(s) => FFIResult::ok(OwnedPtrString(s.into_raw())), Err(_) => FFIResult::err(anyhow!("Failed to convert effect to CString")), } } /// The length of the parameters for the script effect of the ability. #[no_mangle] unsafe extern "C" fn ability_parameter_length(ptr: FFIHandle>) -> usize { ptr.from_ffi_handle().parameters().len() } /// Gets a parameter for the script effect of the ability. #[no_mangle] unsafe extern "C" fn ability_parameter_get( ptr: FFIHandle>, index: usize, ) -> FFIHandle> { if let Some(p) = ptr.from_ffi_handle().parameters().get(index) { FFIHandle::get_handle(p.clone().into()) } else { FFIHandle::none() } }