PkmnLib_rs/src/ffi/static_data/species.rs

69 lines
2.0 KiB
Rust

use crate::ffi::{ffi_getter, ffi_stringkey_getter, BorrowedPtr, ExternPointer, OwnedPtr};
use crate::static_data::{Form, Species};
use crate::StringKey;
use hashbrown::HashSet;
use std::ffi::{c_char, CStr};
use std::ptr::drop_in_place;
use std::sync::Arc;
#[no_mangle]
unsafe extern "C" fn species_new(
id: u16,
name: BorrowedPtr<c_char>,
gender_rate: f32,
growth_rate: BorrowedPtr<c_char>,
capture_rate: u8,
default_form: OwnedPtr<Form>,
flags: *const *const c_char,
flags_length: usize,
) -> OwnedPtr<Species> {
let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into();
let growth_rate: StringKey = CStr::from_ptr(growth_rate).to_str().unwrap().into();
let flags = std::slice::from_raw_parts(flags, flags_length);
let mut flags_set: HashSet<StringKey> = HashSet::with_capacity(flags_length);
for flag in flags {
flags_set.insert(CStr::from_ptr(*flag).to_str().unwrap().into());
}
Box::into_raw(Box::new(Species::new(
id,
&name,
gender_rate,
&growth_rate,
capture_rate,
*Box::from_raw(default_form),
flags_set,
)))
}
#[no_mangle]
unsafe extern "C" fn species_drop(ptr: OwnedPtr<Species>) {
drop_in_place(ptr);
}
ffi_getter!(Species, id, u16);
ffi_stringkey_getter!(Species, name);
ffi_getter!(Species, gender_rate, f32);
ffi_stringkey_getter!(Species, growth_rate);
ffi_getter!(Species, capture_rate, u8);
#[no_mangle]
unsafe extern "C" fn species_add_form(
species: ExternPointer<Species>,
name: BorrowedPtr<c_char>,
form: OwnedPtr<Form>,
) {
let form = *Box::from_raw(form);
species.as_mut().add_form(CStr::from_ptr(name).into(), form)
}
#[no_mangle]
unsafe extern "C" fn species_get_form(species: ExternPointer<Species>, name: BorrowedPtr<c_char>) -> BorrowedPtr<Form> {
let form = species.as_ref().get_form(&CStr::from_ptr(name).into());
if let Some(form) = form {
Arc::as_ptr(form)
} else {
std::ptr::null()
}
}