PkmnLib_rs/src/ffi/static_data/libraries/mod.rs

73 lines
2.7 KiB
Rust
Raw Normal View History

2022-10-01 13:40:15 +00:00
mod growth_rate_library;
mod library_settings;
mod nature_library;
mod static_data;
mod type_library;
use crate::ffi::{BorrowedPtr, IdentifiablePointer, OwnedPtr};
2022-10-01 13:40:15 +00:00
use crate::static_data::*;
use std::ffi::{c_char, CStr};
use std::ptr::drop_in_place;
use std::sync::Arc;
macro_rules! library_interface {
($library_type:ty, $return_type:ty) => {
paste::paste! {
#[no_mangle]
extern "C" fn [< $library_type:snake _new >](capacity: usize) -> IdentifiablePointer<$library_type> {
Box::new($library_type::new(capacity)).into()
2022-10-01 13:40:15 +00:00
}
#[no_mangle]
unsafe extern "C" fn [< $library_type:snake _drop >](ptr: OwnedPtr<$library_type>) {
drop_in_place(ptr);
}
#[no_mangle]
unsafe extern "C" fn [< $library_type:snake _add >](ptr: OwnedPtr<$library_type>, key: BorrowedPtr<c_char>, value: OwnedPtr<Arc<$return_type>>) {
2022-10-01 13:40:15 +00:00
let lib = ptr.as_mut().unwrap();
lib.add(&CStr::from_ptr(key).into(), *Box::from_raw(value));
}
#[no_mangle]
unsafe extern "C" fn [< $library_type:snake _remove >](ptr: OwnedPtr<$library_type>, key: BorrowedPtr<c_char>) {
let lib = ptr.as_mut().unwrap();
lib.remove(&CStr::from_ptr(key).into());
}
#[no_mangle]
unsafe extern "C" fn [< $library_type:snake _get >](ptr: OwnedPtr<$library_type>, key: BorrowedPtr<c_char>) -> IdentifiablePointer<Arc<$return_type>> {
2022-10-01 13:40:15 +00:00
let lib = ptr.as_mut().unwrap();
let v = lib.get(&CStr::from_ptr(key).into());
if let Some(value) = v {
value.clone().into()
2022-10-01 13:40:15 +00:00
} else {
IdentifiablePointer::none()
2022-10-01 13:40:15 +00:00
}
}
#[no_mangle]
unsafe extern "C" fn [< $library_type:snake _get_key_by_index >](ptr: OwnedPtr<$library_type>, index: usize) -> OwnedPtr<c_char> {
let lib = ptr.as_mut().unwrap();
let v = lib.get_key_by_index(index);
if let Some(value) = v {
std::ffi::CString::new(value.str()).unwrap().into_raw()
} else {
std::ptr::null_mut()
}
}
#[no_mangle]
unsafe extern "C" fn [< $library_type:snake _len >](ptr: OwnedPtr<$library_type>) -> usize {
let lib = ptr.as_mut().unwrap();
lib.len()
}
}
};
}
library_interface!(SpeciesLibrary, Species);
library_interface!(MoveLibrary, MoveData);
library_interface!(AbilityLibrary, Ability);
library_interface!(ItemLibrary, Item);