Rework of FFI, adding a value identifier, so we can keep knowledge of data even when data moves.
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Deukhoofd 2022-10-08 13:15:04 +02:00
parent 84ddf0307d
commit 41b40ef98e
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F
38 changed files with 582 additions and 230 deletions

View File

@ -16,13 +16,26 @@ macro_rules! ffi_getter {
}; };
} }
macro_rules! ffi_stringkey_getter { macro_rules! ffi_arc_getter {
(
$type:ty, $func:ident, $returns: ty
) => {
paste::paste! {
#[no_mangle]
extern "C" fn [< $type:snake _ $func >](ptr: ExternPointer<Arc<$type>>) -> $returns {
ptr.as_ref().$func()
}
}
};
}
macro_rules! ffi_arc_stringkey_getter {
( (
$type:ty, $func:ident $type:ty, $func:ident
) => { ) => {
paste::paste! { paste::paste! {
#[no_mangle] #[no_mangle]
extern "C" fn [< $type:lower _ $func >](ptr: ExternPointer<$type>) -> OwnedPtr<c_char> { extern "C" fn [< $type:lower _ $func >](ptr: ExternPointer<Arc<$type>>) -> OwnedPtr<c_char> {
std::ffi::CString::new(ptr.as_ref().$func().str()).unwrap().into_raw() std::ffi::CString::new(ptr.as_ref().$func().str()).unwrap().into_raw()
} }
} }
@ -35,11 +48,11 @@ macro_rules! ffi_vec_value_getters {
) => { ) => {
paste::paste! { paste::paste! {
#[no_mangle] #[no_mangle]
extern "C" fn [< $type:lower _ $func _length>](ptr: ExternPointer<$type>) -> usize { extern "C" fn [< $type:lower _ $func _length>](ptr: ExternPointer<Arc<$type>>) -> usize {
ptr.as_ref().$func().len() ptr.as_ref().$func().len()
} }
#[no_mangle] #[no_mangle]
extern "C" fn [< $type:lower _ $func _get>](ptr: ExternPointer<$type>, index: usize) -> $returns { extern "C" fn [< $type:lower _ $func _get>](ptr: ExternPointer<Arc<$type>>, index: usize) -> $returns {
*ptr.as_ref().$func().get(index).unwrap() *ptr.as_ref().$func().get(index).unwrap()
} }
} }
@ -52,21 +65,24 @@ macro_rules! ffi_vec_stringkey_getters {
) => { ) => {
paste::paste! { paste::paste! {
#[no_mangle] #[no_mangle]
extern "C" fn [< $type:lower _ $func _length>](ptr: ExternPointer<$type>) -> usize { extern "C" fn [< $type:lower _ $func _length>](ptr: ExternPointer<Arc<$type>>) -> usize {
ptr.as_ref().$func().len() ptr.as_ref().$func().len()
} }
#[no_mangle] #[no_mangle]
extern "C" fn [< $type:lower _ $func _get>](ptr: ExternPointer<$type>, index: usize) -> OwnedPtr<c_char> { extern "C" fn [< $type:lower _ $func _get>](ptr: ExternPointer<Arc<$type>>, index: usize) -> OwnedPtr<c_char> {
CString::new(ptr.as_ref().$func().get(index).unwrap().str()).unwrap().into_raw() CString::new(ptr.as_ref().$func().get(index).unwrap().str()).unwrap().into_raw()
} }
} }
}; };
} }
use crate::{ValueIdentifiable, ValueIdentifier};
pub(self) use ffi_arc_getter;
pub(self) use ffi_arc_stringkey_getter;
pub(self) use ffi_getter; pub(self) use ffi_getter;
pub(self) use ffi_stringkey_getter;
pub(self) use ffi_vec_stringkey_getters; pub(self) use ffi_vec_stringkey_getters;
pub(self) use ffi_vec_value_getters; pub(self) use ffi_vec_value_getters;
use std::sync::Arc;
#[repr(C)] #[repr(C)]
pub(self) struct ExternPointer<T: ?Sized> { pub(self) struct ExternPointer<T: ?Sized> {
@ -98,3 +114,45 @@ impl<T> Into<ExternPointer<T>> for *mut T {
ExternPointer { ptr: self } ExternPointer { ptr: self }
} }
} }
#[repr(C)]
pub(self) struct IdentifiablePointer<T> {
pub ptr: *const T,
pub id: ValueIdentifier,
}
impl<T: ValueIdentifiable> From<Arc<T>> for IdentifiablePointer<Arc<T>> {
fn from(v: Arc<T>) -> Self {
let id = v.value_identifier();
Self {
ptr: Box::into_raw(Box::new(v)),
id,
}
}
}
impl<T: ValueIdentifiable> From<Box<T>> for IdentifiablePointer<T> {
fn from(v: Box<T>) -> Self {
let id = v.value_identifier();
Self {
ptr: Box::into_raw(v),
id,
}
}
}
impl<T: ValueIdentifiable> From<*const T> for IdentifiablePointer<T> {
fn from(v: *const T) -> Self {
let id = unsafe { v.as_ref() }.unwrap().value_identifier();
Self { ptr: v, id }
}
}
impl<T> IdentifiablePointer<T> {
pub fn none() -> Self {
Self {
ptr: std::ptr::null(),
id: Default::default(),
}
}
}

View File

@ -1,8 +1,9 @@
use crate::ffi::{BorrowedPtr, ExternPointer, OwnedPtr}; use crate::ffi::{ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{Ability, EffectParameter}; use crate::static_data::{Ability, EffectParameter};
use crate::StringKey; use crate::StringKey;
use std::ffi::{c_char, CStr, CString}; use std::ffi::{c_char, CStr, CString};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
use std::sync::Arc;
#[no_mangle] #[no_mangle]
unsafe extern "C" fn ability_new( unsafe extern "C" fn ability_new(
@ -10,7 +11,7 @@ unsafe extern "C" fn ability_new(
effect: *const c_char, effect: *const c_char,
parameters: *const OwnedPtr<EffectParameter>, parameters: *const OwnedPtr<EffectParameter>,
parameters_length: usize, parameters_length: usize,
) -> OwnedPtr<Ability> { ) -> IdentifiablePointer<Arc<Ability>> {
let parameters = std::slice::from_raw_parts(parameters, parameters_length); let parameters = std::slice::from_raw_parts(parameters, parameters_length);
let mut parameters_vec: Vec<EffectParameter> = Vec::with_capacity(parameters_length); let mut parameters_vec: Vec<EffectParameter> = Vec::with_capacity(parameters_length);
for parameter in parameters { for parameter in parameters {
@ -20,34 +21,37 @@ unsafe extern "C" fn ability_new(
let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into(); let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into();
let effect: StringKey = CStr::from_ptr(effect).to_str().unwrap().into(); let effect: StringKey = CStr::from_ptr(effect).to_str().unwrap().into();
Box::into_raw(Box::new(Ability::new(&name, &effect, parameters_vec))) Arc::new(Ability::new(&name, &effect, parameters_vec)).into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn ability_drop(ptr: OwnedPtr<Ability>) { unsafe extern "C" fn ability_drop(ptr: OwnedPtr<Arc<Ability>>) {
drop_in_place(ptr) drop_in_place(ptr)
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn ability_name(ptr: ExternPointer<Ability>) -> OwnedPtr<c_char> { unsafe extern "C" fn ability_name(ptr: ExternPointer<Arc<Ability>>) -> OwnedPtr<c_char> {
CString::new(ptr.as_ref().name().str()).unwrap().into_raw() CString::new(ptr.as_ref().name().str()).unwrap().into_raw()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn ability_effect(ptr: ExternPointer<Ability>) -> OwnedPtr<c_char> { unsafe extern "C" fn ability_effect(ptr: ExternPointer<Arc<Ability>>) -> OwnedPtr<c_char> {
CString::new(ptr.as_ref().effect().str()).unwrap().into_raw() CString::new(ptr.as_ref().effect().str()).unwrap().into_raw()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn ability_parameter_length(ptr: ExternPointer<Ability>) -> usize { unsafe extern "C" fn ability_parameter_length(ptr: ExternPointer<Arc<Ability>>) -> usize {
ptr.as_ref().parameters().len() ptr.as_ref().parameters().len()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn ability_parameter_get(ptr: ExternPointer<Ability>, index: usize) -> BorrowedPtr<EffectParameter> { unsafe extern "C" fn ability_parameter_get(
ptr: ExternPointer<Arc<Ability>>,
index: usize,
) -> IdentifiablePointer<EffectParameter> {
if let Some(p) = ptr.as_ref().parameters().get(index) { if let Some(p) = ptr.as_ref().parameters().get(index) {
p as *const EffectParameter (p as *const EffectParameter).into()
} else { } else {
std::ptr::null() IdentifiablePointer::none()
} }
} }

View File

@ -1,9 +1,13 @@
use crate::ffi::{ffi_getter, ffi_vec_stringkey_getters, ffi_vec_value_getters, BorrowedPtr, ExternPointer, OwnedPtr}; use crate::ffi::{
ffi_arc_getter, ffi_vec_stringkey_getters, ffi_vec_value_getters, BorrowedPtr, ExternPointer, IdentifiablePointer,
OwnedPtr,
};
use crate::static_data::{Form, LearnableMoves, StaticStatisticSet, TypeIdentifier}; use crate::static_data::{Form, LearnableMoves, StaticStatisticSet, TypeIdentifier};
use crate::StringKey; use crate::StringKey;
use hashbrown::HashSet; use hashbrown::HashSet;
use std::ffi::{c_char, CStr, CString}; use std::ffi::{c_char, CStr, CString};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
use std::sync::Arc;
#[no_mangle] #[no_mangle]
unsafe extern "C" fn form_new( unsafe extern "C" fn form_new(
@ -21,7 +25,7 @@ unsafe extern "C" fn form_new(
moves: OwnedPtr<LearnableMoves>, moves: OwnedPtr<LearnableMoves>,
flags: *const *const c_char, flags: *const *const c_char,
flags_length: usize, flags_length: usize,
) -> OwnedPtr<Form> { ) -> IdentifiablePointer<Arc<Form>> {
let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into(); let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into();
let abilities = std::slice::from_raw_parts(abilities, abilities_length); let abilities = std::slice::from_raw_parts(abilities, abilities_length);
@ -41,7 +45,7 @@ unsafe extern "C" fn form_new(
flags_set.insert(CStr::from_ptr(*flag).to_str().unwrap().into()); flags_set.insert(CStr::from_ptr(*flag).to_str().unwrap().into());
} }
Box::into_raw(Box::new(Form::new( Arc::new(Form::new(
&name, &name,
height, height,
weight, weight,
@ -52,35 +56,39 @@ unsafe extern "C" fn form_new(
hidden_abilities_vec, hidden_abilities_vec,
*Box::from_raw(moves), *Box::from_raw(moves),
flags_set, flags_set,
))) ))
.into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn form_drop(ptr: OwnedPtr<Form>) { unsafe extern "C" fn form_drop(ptr: OwnedPtr<Arc<Form>>) {
drop_in_place(ptr) drop_in_place(ptr)
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn form_name(ptr: ExternPointer<Form>) -> OwnedPtr<c_char> { unsafe extern "C" fn form_name(ptr: ExternPointer<Arc<Form>>) -> OwnedPtr<c_char> {
let name = ptr.as_ref().name(); let name = ptr.as_ref().name();
CString::new(name.str()).unwrap().into_raw() CString::new(name.str()).unwrap().into_raw()
} }
ffi_getter!(Form, height, f32); ffi_arc_getter!(Form, height, f32);
ffi_getter!(Form, weight, f32); ffi_arc_getter!(Form, weight, f32);
ffi_getter!(Form, base_experience, u32); ffi_arc_getter!(Form, base_experience, u32);
ffi_vec_value_getters!(Form, types, TypeIdentifier); ffi_vec_value_getters!(Form, types, TypeIdentifier);
ffi_getter!(Form, base_stats, BorrowedPtr<StaticStatisticSet<u16>>); #[no_mangle]
unsafe extern "C" fn form_base_stats(ptr: ExternPointer<Arc<Form>>) -> IdentifiablePointer<StaticStatisticSet<u16>> {
(ptr.as_ref().base_stats() as *const StaticStatisticSet<u16>).into()
}
ffi_vec_stringkey_getters!(Form, abilities); ffi_vec_stringkey_getters!(Form, abilities);
ffi_vec_stringkey_getters!(Form, hidden_abilities); ffi_vec_stringkey_getters!(Form, hidden_abilities);
ffi_getter!(Form, moves, BorrowedPtr<LearnableMoves>); ffi_arc_getter!(Form, moves, BorrowedPtr<LearnableMoves>);
#[no_mangle] #[no_mangle]
unsafe extern "C" fn form_has_flag(ptr: ExternPointer<Form>, flag: *const c_char) -> u8 { unsafe extern "C" fn form_has_flag(ptr: ExternPointer<Arc<Form>>, flag: *const c_char) -> u8 {
let flag = CStr::from_ptr(flag).into(); let flag = CStr::from_ptr(flag).into();
if ptr.as_ref().has_flag(&flag) { if ptr.as_ref().has_flag(&flag) {
1 1

View File

@ -1,9 +1,10 @@
use crate::ffi::{ffi_getter, ExternPointer, OwnedPtr}; use crate::ffi::{ffi_arc_getter, ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{BattleItemCategory, Item, ItemCategory}; use crate::static_data::{BattleItemCategory, Item, ItemCategory};
use crate::StringKey; use crate::StringKey;
use hashbrown::HashSet; use hashbrown::HashSet;
use std::ffi::{c_char, CStr, CString}; use std::ffi::{c_char, CStr, CString};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
use std::sync::Arc;
#[no_mangle] #[no_mangle]
unsafe extern "C" fn item_new( unsafe extern "C" fn item_new(
@ -13,33 +14,33 @@ unsafe extern "C" fn item_new(
price: i32, price: i32,
flags: *const *const c_char, flags: *const *const c_char,
flags_length: usize, flags_length: usize,
) -> OwnedPtr<Item> { ) -> IdentifiablePointer<Arc<Item>> {
let flags = std::slice::from_raw_parts(flags, flags_length); let flags = std::slice::from_raw_parts(flags, flags_length);
let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into(); let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into();
let mut flags_set: HashSet<StringKey> = HashSet::with_capacity(flags_length); let mut flags_set: HashSet<StringKey> = HashSet::with_capacity(flags_length);
for flag in flags { for flag in flags {
flags_set.insert(CStr::from_ptr(*flag).to_str().unwrap().into()); flags_set.insert(CStr::from_ptr(*flag).to_str().unwrap().into());
} }
Box::into_raw(Box::new(Item::new(&name, category, battle_category, price, flags_set))) Arc::new(Item::new(&name, category, battle_category, price, flags_set)).into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn item_drop(ptr: OwnedPtr<Item>) { unsafe extern "C" fn item_drop(ptr: OwnedPtr<Arc<Item>>) {
drop_in_place(ptr) drop_in_place(ptr)
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn item_name(ptr: ExternPointer<Item>) -> OwnedPtr<c_char> { unsafe extern "C" fn item_name(ptr: ExternPointer<Arc<Item>>) -> OwnedPtr<c_char> {
let name = ptr.as_ref().name(); let name = ptr.as_ref().name();
CString::new(name.str()).unwrap().into_raw() CString::new(name.str()).unwrap().into_raw()
} }
ffi_getter!(Item, category, ItemCategory); ffi_arc_getter!(Item, category, ItemCategory);
ffi_getter!(Item, battle_category, BattleItemCategory); ffi_arc_getter!(Item, battle_category, BattleItemCategory);
ffi_getter!(Item, price, i32); ffi_arc_getter!(Item, price, i32);
#[no_mangle] #[no_mangle]
unsafe extern "C" fn item_has_flag(ptr: ExternPointer<Item>, flag: *const c_char) -> u8 { unsafe extern "C" fn item_has_flag(ptr: ExternPointer<Arc<Item>>, flag: *const c_char) -> u8 {
let flag = CStr::from_ptr(flag).into(); let flag = CStr::from_ptr(flag).into();
if ptr.as_ref().has_flag(&flag) { if ptr.as_ref().has_flag(&flag) {
1 1

View File

@ -1,12 +1,12 @@
use crate::defines::LevelInt; use crate::defines::LevelInt;
use crate::ffi::{BorrowedPtr, ExternPointer, OwnedPtr}; use crate::ffi::{BorrowedPtr, ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{GrowthRate, GrowthRateLibrary}; use crate::static_data::{GrowthRate, GrowthRateLibrary};
use std::ffi::{c_char, CStr}; use std::ffi::{c_char, CStr};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
#[no_mangle] #[no_mangle]
extern "C" fn growth_rate_library_new(capacity: usize) -> OwnedPtr<GrowthRateLibrary> { extern "C" fn growth_rate_library_new(capacity: usize) -> IdentifiablePointer<GrowthRateLibrary> {
Box::into_raw(Box::new(GrowthRateLibrary::new(capacity))) Box::new(GrowthRateLibrary::new(capacity)).into()
} }
#[no_mangle] #[no_mangle]

View File

@ -1,11 +1,11 @@
use crate::defines::LevelInt; use crate::defines::LevelInt;
use crate::ffi::{ExternPointer, OwnedPtr}; use crate::ffi::{ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::LibrarySettings; use crate::static_data::LibrarySettings;
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
#[no_mangle] #[no_mangle]
extern "C" fn library_settings_new(max_level: LevelInt) -> OwnedPtr<LibrarySettings> { extern "C" fn library_settings_new(max_level: LevelInt) -> IdentifiablePointer<LibrarySettings> {
Box::into_raw(Box::new(LibrarySettings::new(max_level))) Box::new(LibrarySettings::new(max_level)).into()
} }
#[no_mangle] #[no_mangle]

View File

@ -4,7 +4,7 @@ mod nature_library;
mod static_data; mod static_data;
mod type_library; mod type_library;
use crate::ffi::{BorrowedPtr, OwnedPtr}; use crate::ffi::{BorrowedPtr, IdentifiablePointer, OwnedPtr};
use crate::static_data::*; use crate::static_data::*;
use std::ffi::{c_char, CStr}; use std::ffi::{c_char, CStr};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
@ -14,8 +14,8 @@ macro_rules! library_interface {
($library_type:ty, $return_type:ty) => { ($library_type:ty, $return_type:ty) => {
paste::paste! { paste::paste! {
#[no_mangle] #[no_mangle]
extern "C" fn [< $library_type:snake _new >](capacity: usize) -> OwnedPtr<$library_type> { extern "C" fn [< $library_type:snake _new >](capacity: usize) -> IdentifiablePointer<$library_type> {
Box::into_raw(Box::new($library_type::new(capacity))) Box::new($library_type::new(capacity)).into()
} }
#[no_mangle] #[no_mangle]
@ -24,7 +24,7 @@ macro_rules! library_interface {
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn [< $library_type:snake _add >](ptr: OwnedPtr<$library_type>, key: BorrowedPtr<c_char>, value: OwnedPtr<$return_type>) { unsafe extern "C" fn [< $library_type:snake _add >](ptr: OwnedPtr<$library_type>, key: BorrowedPtr<c_char>, value: OwnedPtr<Arc<$return_type>>) {
let lib = ptr.as_mut().unwrap(); let lib = ptr.as_mut().unwrap();
lib.add(&CStr::from_ptr(key).into(), *Box::from_raw(value)); lib.add(&CStr::from_ptr(key).into(), *Box::from_raw(value));
} }
@ -36,13 +36,13 @@ macro_rules! library_interface {
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn [< $library_type:snake _get >](ptr: OwnedPtr<$library_type>, key: BorrowedPtr<c_char>) -> BorrowedPtr<$return_type> { unsafe extern "C" fn [< $library_type:snake _get >](ptr: OwnedPtr<$library_type>, key: BorrowedPtr<c_char>) -> IdentifiablePointer<Arc<$return_type>> {
let lib = ptr.as_mut().unwrap(); let lib = ptr.as_mut().unwrap();
let v = lib.get(&CStr::from_ptr(key).into()); let v = lib.get(&CStr::from_ptr(key).into());
if let Some(value) = v { if let Some(value) = v {
Arc::as_ptr(value) value.clone().into()
} else { } else {
std::ptr::null() IdentifiablePointer::none()
} }
} }

View File

@ -1,12 +1,12 @@
use crate::ffi::{BorrowedPtr, ExternPointer, OwnedPtr}; use crate::ffi::{BorrowedPtr, ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{Nature, NatureLibrary}; use crate::static_data::{Nature, NatureLibrary};
use std::ffi::{c_char, CStr, CString}; use std::ffi::{c_char, CStr, CString};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
use std::sync::Arc; use std::sync::Arc;
#[no_mangle] #[no_mangle]
extern "C" fn nature_library_new(capacity: usize) -> OwnedPtr<NatureLibrary> { extern "C" fn nature_library_new(capacity: usize) -> IdentifiablePointer<NatureLibrary> {
Box::into_raw(Box::new(NatureLibrary::new(capacity))) Box::new(NatureLibrary::new(capacity)).into()
} }
#[no_mangle] #[no_mangle]
@ -18,31 +18,30 @@ unsafe extern "C" fn nature_library_drop(ptr: OwnedPtr<NatureLibrary>) {
unsafe extern "C" fn nature_library_load_nature( unsafe extern "C" fn nature_library_load_nature(
ptr: ExternPointer<NatureLibrary>, ptr: ExternPointer<NatureLibrary>,
name: BorrowedPtr<c_char>, name: BorrowedPtr<c_char>,
nature: OwnedPtr<Nature>, nature: OwnedPtr<Arc<Nature>>,
) { ) {
ptr.as_mut() ptr.as_mut()
.load_nature(CStr::from_ptr(name).into(), *Box::from_raw(nature)) .load_nature(CStr::from_ptr(name).into(), nature.as_ref().unwrap().clone())
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn nature_library_get_nature( unsafe extern "C" fn nature_library_get_nature(
ptr: ExternPointer<NatureLibrary>, ptr: ExternPointer<NatureLibrary>,
name: BorrowedPtr<c_char>, name: BorrowedPtr<c_char>,
) -> BorrowedPtr<Nature> { ) -> IdentifiablePointer<Arc<Nature>> {
if let Some(nature) = ptr.as_ref().get_nature(&CStr::from_ptr(name).into()) { if let Some(nature) = ptr.as_ref().get_nature(&CStr::from_ptr(name).into()) {
Arc::into_raw(nature.clone()) nature.clone().into()
} else { } else {
std::ptr::null() IdentifiablePointer::none()
} }
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn nature_library_get_nature_name( unsafe extern "C" fn nature_library_get_nature_name(
ptr: ExternPointer<NatureLibrary>, ptr: ExternPointer<NatureLibrary>,
nature: BorrowedPtr<Nature>, nature: BorrowedPtr<Arc<Nature>>,
) -> OwnedPtr<c_char> { ) -> OwnedPtr<c_char> {
let arc = Arc::from_raw(nature); CString::new(ptr.as_ref().get_nature_name(nature.as_ref().unwrap()).str())
CString::new(ptr.as_ref().get_nature_name(&arc).str())
.unwrap() .unwrap()
.into_raw() .into_raw()
} }

View File

@ -1,4 +1,4 @@
use crate::ffi::{BorrowedPtr, ExternPointer, OwnedPtr}; use crate::ffi::{ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{ use crate::static_data::{
AbilityLibrary, GrowthRateLibrary, ItemLibrary, LibrarySettings, MoveLibrary, NatureLibrary, SpeciesLibrary, AbilityLibrary, GrowthRateLibrary, ItemLibrary, LibrarySettings, MoveLibrary, NatureLibrary, SpeciesLibrary,
StaticData, TypeLibrary, StaticData, TypeLibrary,
@ -6,8 +6,8 @@ use crate::static_data::{
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
#[no_mangle] #[no_mangle]
unsafe extern "C" fn static_data_new(settings: OwnedPtr<LibrarySettings>) -> OwnedPtr<StaticData> { unsafe extern "C" fn static_data_new(settings: OwnedPtr<LibrarySettings>) -> IdentifiablePointer<StaticData> {
Box::into_raw(Box::new(StaticData::new(*Box::from_raw(settings)))) Box::new(StaticData::new(*Box::from_raw(settings))).into()
} }
#[no_mangle] #[no_mangle]
@ -16,41 +16,43 @@ unsafe extern "C" fn static_data_drop(ptr: OwnedPtr<StaticData>) {
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn static_data_settings(data: ExternPointer<StaticData>) -> BorrowedPtr<LibrarySettings> { unsafe extern "C" fn static_data_settings(data: ExternPointer<StaticData>) -> IdentifiablePointer<LibrarySettings> {
data.as_mut().settings() as *const LibrarySettings (data.as_mut().settings() as *const LibrarySettings).into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn static_data_species(data: ExternPointer<StaticData>) -> BorrowedPtr<SpeciesLibrary> { unsafe extern "C" fn static_data_species(data: ExternPointer<StaticData>) -> IdentifiablePointer<SpeciesLibrary> {
data.as_mut().species_mut() as *mut SpeciesLibrary (data.as_mut().species_mut() as *const SpeciesLibrary).into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn static_data_moves(data: ExternPointer<StaticData>) -> BorrowedPtr<MoveLibrary> { unsafe extern "C" fn static_data_moves(data: ExternPointer<StaticData>) -> IdentifiablePointer<MoveLibrary> {
data.as_mut().moves_mut() as *mut MoveLibrary (data.as_mut().moves_mut() as *const MoveLibrary).into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn static_data_items(data: ExternPointer<StaticData>) -> BorrowedPtr<ItemLibrary> { unsafe extern "C" fn static_data_items(data: ExternPointer<StaticData>) -> IdentifiablePointer<ItemLibrary> {
data.as_mut().items_mut() as *mut ItemLibrary (data.as_mut().items_mut() as *const ItemLibrary).into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn static_data_growth_rates(data: ExternPointer<StaticData>) -> BorrowedPtr<GrowthRateLibrary> { unsafe extern "C" fn static_data_growth_rates(
data.as_mut().growth_rates_mut() as *mut GrowthRateLibrary data: ExternPointer<StaticData>,
) -> IdentifiablePointer<GrowthRateLibrary> {
(data.as_mut().growth_rates_mut() as *const GrowthRateLibrary).into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn static_data_types(data: ExternPointer<StaticData>) -> BorrowedPtr<TypeLibrary> { unsafe extern "C" fn static_data_types(data: ExternPointer<StaticData>) -> IdentifiablePointer<TypeLibrary> {
data.as_mut().types_mut() as *mut TypeLibrary (data.as_mut().types_mut() as *const TypeLibrary).into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn static_data_natures(data: ExternPointer<StaticData>) -> BorrowedPtr<NatureLibrary> { unsafe extern "C" fn static_data_natures(data: ExternPointer<StaticData>) -> IdentifiablePointer<NatureLibrary> {
data.as_mut().natures_mut() as *mut NatureLibrary (data.as_mut().natures_mut() as *const NatureLibrary).into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn static_data_abilities(data: ExternPointer<StaticData>) -> BorrowedPtr<AbilityLibrary> { unsafe extern "C" fn static_data_abilities(data: ExternPointer<StaticData>) -> IdentifiablePointer<AbilityLibrary> {
data.as_mut().abilities_mut() as *mut AbilityLibrary (data.as_mut().abilities_mut() as *const AbilityLibrary).into()
} }

View File

@ -1,11 +1,11 @@
use crate::ffi::{BorrowedPtr, ExternPointer, OwnedPtr}; use crate::ffi::{BorrowedPtr, ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{TypeIdentifier, TypeLibrary}; use crate::static_data::{TypeIdentifier, TypeLibrary};
use std::ffi::{c_char, CStr, CString}; use std::ffi::{c_char, CStr, CString};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
#[no_mangle] #[no_mangle]
extern "C" fn type_library_new(capacity: usize) -> OwnedPtr<TypeLibrary> { extern "C" fn type_library_new(capacity: usize) -> IdentifiablePointer<TypeLibrary> {
Box::into_raw(Box::new(TypeLibrary::new(capacity))) Box::new(TypeLibrary::new(capacity)).into()
} }
#[no_mangle] #[no_mangle]

View File

@ -1,5 +1,6 @@
use crate::ffi::{ExternPointer, OwnedPtr}; use crate::ffi::{ExternPointer, OwnedPtr};
use crate::static_data::EffectParameter; use crate::static_data::EffectParameter;
use crate::StringKey;
use std::ffi::{c_char, CStr, CString}; use std::ffi::{c_char, CStr, CString};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
@ -8,32 +9,31 @@ mod form;
mod growth_rate; mod growth_rate;
mod item; mod item;
mod learnable_moves; mod learnable_moves;
mod libraries;
mod move_data; mod move_data;
mod nature; mod nature;
mod species; mod species;
mod statistic_set; mod statistic_set;
mod libraries;
#[no_mangle] #[no_mangle]
extern "C" fn effect_parameter_new_bool(value: u8) -> OwnedPtr<EffectParameter> { extern "C" fn effect_parameter_new_bool(value: u8) -> OwnedPtr<EffectParameter> {
Box::into_raw(Box::new(EffectParameter::Bool(value == 1))) Box::into_raw(Box::new((value == 1).into()))
} }
#[no_mangle] #[no_mangle]
extern "C" fn effect_parameter_new_int(value: i64) -> OwnedPtr<EffectParameter> { extern "C" fn effect_parameter_new_int(value: i64) -> OwnedPtr<EffectParameter> {
Box::into_raw(Box::new(EffectParameter::Int(value))) Box::into_raw(Box::new(value.into()))
} }
#[no_mangle] #[no_mangle]
extern "C" fn effect_parameter_new_float(value: f32) -> OwnedPtr<EffectParameter> { extern "C" fn effect_parameter_new_float(value: f32) -> OwnedPtr<EffectParameter> {
Box::into_raw(Box::new(EffectParameter::Float(value))) Box::into_raw(Box::new(value.into()))
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn effect_parameter_new_string(value: *const c_char) -> OwnedPtr<EffectParameter> { unsafe extern "C" fn effect_parameter_new_string(value: *const c_char) -> OwnedPtr<EffectParameter> {
Box::into_raw(Box::new(EffectParameter::String( let sk: StringKey = CStr::from_ptr(value).to_str().unwrap().into();
CStr::from_ptr(value).to_str().unwrap().into(), Box::into_raw(Box::new(sk.into()))
)))
} }
#[no_mangle] #[no_mangle]
@ -44,17 +44,17 @@ unsafe extern "C" fn effect_parameter_drop(ptr: OwnedPtr<EffectParameter>) {
#[no_mangle] #[no_mangle]
extern "C" fn effect_parameter_get_type(ptr: ExternPointer<EffectParameter>) -> u8 { extern "C" fn effect_parameter_get_type(ptr: ExternPointer<EffectParameter>) -> u8 {
match ptr.as_ref() { match ptr.as_ref() {
EffectParameter::Bool(_) => 0, EffectParameter::Bool(_, _) => 0,
EffectParameter::Int(_) => 1, EffectParameter::Int(_, _) => 1,
EffectParameter::Float(_) => 2, EffectParameter::Float(_, _) => 2,
EffectParameter::String(_) => 3, EffectParameter::String(_, _) => 3,
} }
} }
#[no_mangle] #[no_mangle]
extern "C" fn effect_parameter_get_as_bool(ptr: ExternPointer<EffectParameter>) -> u8 { extern "C" fn effect_parameter_get_as_bool(ptr: ExternPointer<EffectParameter>) -> u8 {
let p = ptr.as_ref(); let p = ptr.as_ref();
if let EffectParameter::Bool(b) = p { if let EffectParameter::Bool(_, b) = p {
return if *b { 1 } else { 0 }; return if *b { 1 } else { 0 };
} }
panic!("Unexpected effect parameter. Expected bool, was: {}", p); panic!("Unexpected effect parameter. Expected bool, was: {}", p);
@ -63,7 +63,7 @@ extern "C" fn effect_parameter_get_as_bool(ptr: ExternPointer<EffectParameter>)
#[no_mangle] #[no_mangle]
extern "C" fn effect_parameter_get_as_int(ptr: ExternPointer<EffectParameter>) -> i64 { extern "C" fn effect_parameter_get_as_int(ptr: ExternPointer<EffectParameter>) -> i64 {
let p = ptr.as_ref(); let p = ptr.as_ref();
if let EffectParameter::Int(b) = p { if let EffectParameter::Int(_, b) = p {
return *b; return *b;
} }
panic!("Unexpected effect parameter. Expected int, was: {}", p); panic!("Unexpected effect parameter. Expected int, was: {}", p);
@ -72,7 +72,7 @@ extern "C" fn effect_parameter_get_as_int(ptr: ExternPointer<EffectParameter>) -
#[no_mangle] #[no_mangle]
extern "C" fn effect_parameter_get_as_float(ptr: ExternPointer<EffectParameter>) -> f32 { extern "C" fn effect_parameter_get_as_float(ptr: ExternPointer<EffectParameter>) -> f32 {
let p = ptr.as_ref(); let p = ptr.as_ref();
if let EffectParameter::Float(b) = p { if let EffectParameter::Float(_, b) = p {
return *b; return *b;
} }
panic!("Unexpected effect parameter. Expected float, was: {}", p); panic!("Unexpected effect parameter. Expected float, was: {}", p);
@ -81,7 +81,7 @@ extern "C" fn effect_parameter_get_as_float(ptr: ExternPointer<EffectParameter>)
#[no_mangle] #[no_mangle]
extern "C" fn effect_parameter_get_as_string(ptr: ExternPointer<EffectParameter>) -> OwnedPtr<c_char> { extern "C" fn effect_parameter_get_as_string(ptr: ExternPointer<EffectParameter>) -> OwnedPtr<c_char> {
let p = ptr.as_ref(); let p = ptr.as_ref();
if let EffectParameter::String(b) = p { if let EffectParameter::String(_, b) = p {
return CString::new(b.str().to_string()).unwrap().into_raw(); return CString::new(b.str().to_string()).unwrap().into_raw();
} }
panic!("Unexpected effect parameter. Expected string, was: {}", p); panic!("Unexpected effect parameter. Expected string, was: {}", p);

View File

@ -1,9 +1,10 @@
use crate::ffi::{ffi_getter, BorrowedPtr, ExternPointer, OwnedPtr}; use crate::ffi::{ffi_arc_getter, ffi_getter, BorrowedPtr, ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{EffectParameter, MoveCategory, MoveData, MoveTarget, SecondaryEffect, TypeIdentifier}; use crate::static_data::{EffectParameter, MoveCategory, MoveData, MoveTarget, SecondaryEffect, TypeIdentifier};
use crate::StringKey; use crate::StringKey;
use hashbrown::HashSet; use hashbrown::HashSet;
use std::ffi::{c_char, CStr, CString}; use std::ffi::{c_char, CStr, CString};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
use std::sync::Arc;
#[no_mangle] #[no_mangle]
unsafe extern "C" fn move_data_new( unsafe extern "C" fn move_data_new(
@ -18,7 +19,7 @@ unsafe extern "C" fn move_data_new(
secondary_effect: *mut SecondaryEffect, secondary_effect: *mut SecondaryEffect,
flags: *const *const c_char, flags: *const *const c_char,
flags_length: usize, flags_length: usize,
) -> OwnedPtr<MoveData> { ) -> IdentifiablePointer<Arc<MoveData>> {
let flags = std::slice::from_raw_parts(flags, flags_length); let flags = std::slice::from_raw_parts(flags, flags_length);
let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into(); let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into();
let mut flags_set: HashSet<StringKey> = HashSet::with_capacity(flags_length); let mut flags_set: HashSet<StringKey> = HashSet::with_capacity(flags_length);
@ -30,7 +31,7 @@ unsafe extern "C" fn move_data_new(
} else { } else {
Some(*Box::from_raw(secondary_effect)) Some(*Box::from_raw(secondary_effect))
}; };
Box::into_raw(Box::new(MoveData::new( Arc::new(MoveData::new(
&name, &name,
move_type, move_type,
category, category,
@ -41,40 +42,43 @@ unsafe extern "C" fn move_data_new(
priority, priority,
secondary_effect, secondary_effect,
flags_set, flags_set,
))) ))
.into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn move_data_drop(ptr: OwnedPtr<MoveData>) { unsafe extern "C" fn move_data_drop(ptr: OwnedPtr<Arc<MoveData>>) {
drop_in_place(ptr) drop_in_place(ptr)
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn move_data_name(ptr: ExternPointer<MoveData>) -> OwnedPtr<c_char> { unsafe extern "C" fn move_data_name(ptr: ExternPointer<Arc<MoveData>>) -> OwnedPtr<c_char> {
let name = ptr.as_ref().name(); let name = ptr.as_ref().name();
CString::new(name.str()).unwrap().into_raw() CString::new(name.str()).unwrap().into_raw()
} }
ffi_getter!(MoveData, move_type, TypeIdentifier); ffi_arc_getter!(MoveData, move_type, TypeIdentifier);
ffi_getter!(MoveData, category, MoveCategory); ffi_arc_getter!(MoveData, category, MoveCategory);
ffi_getter!(MoveData, base_power, u8); ffi_arc_getter!(MoveData, base_power, u8);
ffi_getter!(MoveData, accuracy, u8); ffi_arc_getter!(MoveData, accuracy, u8);
ffi_getter!(MoveData, base_usages, u8); ffi_arc_getter!(MoveData, base_usages, u8);
ffi_getter!(MoveData, target, MoveTarget); ffi_arc_getter!(MoveData, target, MoveTarget);
ffi_getter!(MoveData, priority, i8); ffi_arc_getter!(MoveData, priority, i8);
#[no_mangle] #[no_mangle]
unsafe extern "C" fn move_data_secondary_effect(ptr: ExternPointer<MoveData>) -> BorrowedPtr<SecondaryEffect> { unsafe extern "C" fn move_data_secondary_effect(
ptr: ExternPointer<Arc<MoveData>>,
) -> IdentifiablePointer<SecondaryEffect> {
let effect = ptr.as_ref().secondary_effect(); let effect = ptr.as_ref().secondary_effect();
if let Some(v) = effect { if let Some(v) = effect {
v as *const SecondaryEffect (v as *const SecondaryEffect).into()
} else { } else {
std::ptr::null() IdentifiablePointer::none()
} }
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn move_data_has_flag(ptr: ExternPointer<MoveData>, flag: *const c_char) -> u8 { unsafe extern "C" fn move_data_has_flag(ptr: ExternPointer<Arc<MoveData>>, flag: *const c_char) -> u8 {
let flag = CStr::from_ptr(flag).into(); let flag = CStr::from_ptr(flag).into();
if ptr.as_ref().has_flag(&flag) { if ptr.as_ref().has_flag(&flag) {
1 1
@ -89,18 +93,19 @@ unsafe extern "C" fn secondary_effect_new(
effect_name: BorrowedPtr<c_char>, effect_name: BorrowedPtr<c_char>,
parameters: *mut OwnedPtr<EffectParameter>, parameters: *mut OwnedPtr<EffectParameter>,
parameters_length: usize, parameters_length: usize,
) -> OwnedPtr<SecondaryEffect> { ) -> IdentifiablePointer<SecondaryEffect> {
let parameter_slice = std::slice::from_raw_parts(parameters, parameters_length); let parameter_slice = std::slice::from_raw_parts(parameters, parameters_length);
let mut parameters = Vec::with_capacity(parameters_length); let mut parameters = Vec::with_capacity(parameters_length);
for parameter in parameter_slice { for parameter in parameter_slice {
parameters.push(*Box::from_raw(*parameter)) parameters.push(*Box::from_raw(*parameter))
} }
Box::into_raw(Box::new(SecondaryEffect::new( Box::new(SecondaryEffect::new(
chance, chance,
CStr::from_ptr(effect_name).into(), CStr::from_ptr(effect_name).into(),
parameters, parameters,
))) ))
.into()
} }
#[no_mangle] #[no_mangle]
@ -124,10 +129,10 @@ unsafe extern "C" fn secondary_effect_parameter_length(ptr: ExternPointer<Second
unsafe extern "C" fn secondary_effect_parameter_get( unsafe extern "C" fn secondary_effect_parameter_get(
ptr: ExternPointer<SecondaryEffect>, ptr: ExternPointer<SecondaryEffect>,
index: usize, index: usize,
) -> BorrowedPtr<EffectParameter> { ) -> IdentifiablePointer<EffectParameter> {
if let Some(v) = ptr.as_ref().parameters().get(index) { if let Some(v) = ptr.as_ref().parameters().get(index) {
v as *const EffectParameter (v as *const EffectParameter).into()
} else { } else {
std::ptr::null() IdentifiablePointer::none()
} }
} }

View File

@ -1,6 +1,7 @@
use crate::ffi::{ffi_getter, ExternPointer, OwnedPtr}; use crate::ffi::{ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{Nature, Statistic}; use crate::static_data::{Nature, Statistic};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
use std::sync::Arc;
#[no_mangle] #[no_mangle]
extern "C" fn nature_new( extern "C" fn nature_new(
@ -8,24 +9,26 @@ extern "C" fn nature_new(
decrease_stat: Statistic, decrease_stat: Statistic,
increase_modifier: f32, increase_modifier: f32,
decrease_modifier: f32, decrease_modifier: f32,
) -> OwnedPtr<Nature> { ) -> IdentifiablePointer<Arc<Nature>> {
Box::into_raw(Box::new(Nature::new( Nature::new(increase_stat, decrease_stat, increase_modifier, decrease_modifier).into()
increase_stat,
decrease_stat,
increase_modifier,
decrease_modifier,
)))
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn nature_drop(ptr: OwnedPtr<Nature>) { unsafe extern "C" fn nature_drop(ptr: OwnedPtr<Arc<Nature>>) {
drop_in_place(ptr) drop_in_place(ptr)
} }
ffi_getter!(Nature, increased_stat, Statistic); #[no_mangle]
ffi_getter!(Nature, decreased_stat, Statistic); extern "C" fn nature_increased_stat(ptr: ExternPointer<Arc<Nature>>) -> Statistic {
ptr.as_ref().increased_stat()
}
#[no_mangle] #[no_mangle]
extern "C" fn nature_get_stat_modifier(ptr: ExternPointer<Nature>, stat: Statistic) -> f32 { extern "C" fn nature_decreased_stat(ptr: ExternPointer<Arc<Nature>>) -> Statistic {
ptr.as_ref().decreased_stat()
}
#[no_mangle]
extern "C" fn nature_get_stat_modifier(ptr: ExternPointer<Arc<Nature>>, stat: Statistic) -> f32 {
ptr.as_ref().get_stat_modifier(stat) ptr.as_ref().get_stat_modifier(stat)
} }

View File

@ -1,4 +1,4 @@
use crate::ffi::{ffi_getter, ffi_stringkey_getter, BorrowedPtr, ExternPointer, OwnedPtr}; use crate::ffi::{ffi_arc_getter, ffi_arc_stringkey_getter, BorrowedPtr, ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{Form, Species}; use crate::static_data::{Form, Species};
use crate::StringKey; use crate::StringKey;
use hashbrown::HashSet; use hashbrown::HashSet;
@ -13,10 +13,10 @@ unsafe extern "C" fn species_new(
gender_rate: f32, gender_rate: f32,
growth_rate: BorrowedPtr<c_char>, growth_rate: BorrowedPtr<c_char>,
capture_rate: u8, capture_rate: u8,
default_form: OwnedPtr<Form>, default_form: OwnedPtr<Arc<Form>>,
flags: *const *const c_char, flags: *const *const c_char,
flags_length: usize, flags_length: usize,
) -> OwnedPtr<Species> { ) -> IdentifiablePointer<Arc<Species>> {
let name: StringKey = CStr::from_ptr(name).to_str().unwrap().into(); 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 growth_rate: StringKey = CStr::from_ptr(growth_rate).to_str().unwrap().into();
@ -25,44 +25,48 @@ unsafe extern "C" fn species_new(
for flag in flags { for flag in flags {
flags_set.insert(CStr::from_ptr(*flag).to_str().unwrap().into()); flags_set.insert(CStr::from_ptr(*flag).to_str().unwrap().into());
} }
Box::into_raw(Box::new(Species::new( Arc::new(Species::new(
id, id,
&name, &name,
gender_rate, gender_rate,
&growth_rate, &growth_rate,
capture_rate, capture_rate,
*Box::from_raw(default_form), default_form.as_ref().unwrap().clone(),
flags_set, flags_set,
))) ))
.into()
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn species_drop(ptr: OwnedPtr<Species>) { unsafe extern "C" fn species_drop(ptr: OwnedPtr<Arc<Species>>) {
drop_in_place(ptr); drop_in_place(ptr);
} }
ffi_getter!(Species, id, u16); ffi_arc_getter!(Species, id, u16);
ffi_stringkey_getter!(Species, name); ffi_arc_stringkey_getter!(Species, name);
ffi_getter!(Species, gender_rate, f32); ffi_arc_getter!(Species, gender_rate, f32);
ffi_stringkey_getter!(Species, growth_rate); ffi_arc_stringkey_getter!(Species, growth_rate);
ffi_getter!(Species, capture_rate, u8); ffi_arc_getter!(Species, capture_rate, u8);
#[no_mangle] #[no_mangle]
unsafe extern "C" fn species_add_form( unsafe extern "C" fn species_add_form(
species: ExternPointer<Species>, species: ExternPointer<Arc<Species>>,
name: BorrowedPtr<c_char>, name: BorrowedPtr<c_char>,
form: OwnedPtr<Form>, form: OwnedPtr<Arc<Form>>,
) { ) {
let form = *Box::from_raw(form); let form = form.as_ref().unwrap().clone();
species.as_mut().add_form(CStr::from_ptr(name).into(), form) species.as_mut().add_form(CStr::from_ptr(name).into(), form)
} }
#[no_mangle] #[no_mangle]
unsafe extern "C" fn species_get_form(species: ExternPointer<Species>, name: BorrowedPtr<c_char>) -> BorrowedPtr<Form> { unsafe extern "C" fn species_get_form(
species: ExternPointer<Arc<Species>>,
name: BorrowedPtr<c_char>,
) -> IdentifiablePointer<Arc<Form>> {
let form = species.as_ref().get_form(&CStr::from_ptr(name).into()); let form = species.as_ref().get_form(&CStr::from_ptr(name).into());
if let Some(form) = form { if let Some(form) = form {
Arc::as_ptr(form) form.into()
} else { } else {
std::ptr::null() IdentifiablePointer::none()
} }
} }

View File

@ -1,4 +1,4 @@
use crate::ffi::{ExternPointer, OwnedPtr}; use crate::ffi::{ExternPointer, IdentifiablePointer, OwnedPtr};
use crate::static_data::{StaticStatisticSet, Statistic, StatisticSet}; use crate::static_data::{StaticStatisticSet, Statistic, StatisticSet};
use std::ptr::drop_in_place; use std::ptr::drop_in_place;
@ -14,15 +14,15 @@ extern "C" fn [<statistic_set_ $num_type _new>](
special_attack: $num_type, special_attack: $num_type,
special_defense: $num_type, special_defense: $num_type,
speed: $num_type, speed: $num_type,
) -> OwnedPtr<StatisticSet<$num_type>> { ) -> IdentifiablePointer<StatisticSet<$num_type>> {
Box::into_raw(Box::new(StatisticSet::new( Box::new(StatisticSet::new(
hp, hp,
attack, attack,
defense, defense,
special_attack, special_attack,
special_defense, special_defense,
speed, speed,
))) )).into()
} }
#[no_mangle] #[no_mangle]
@ -73,15 +73,15 @@ extern "C" fn [<static_statistic_set_ $num_type _new>](
special_attack: $num_type, special_attack: $num_type,
special_defense: $num_type, special_defense: $num_type,
speed: $num_type, speed: $num_type,
) -> OwnedPtr<StaticStatisticSet<$num_type>> { ) -> IdentifiablePointer<StaticStatisticSet<$num_type>> {
Box::into_raw(Box::new(StaticStatisticSet::new( Box::new(StaticStatisticSet::new(
hp, hp,
attack, attack,
defense, defense,
special_attack, special_attack,
special_defense, special_defense,
speed, speed,
))) )).into()
} }
#[no_mangle] #[no_mangle]

View File

@ -138,10 +138,10 @@ fn string_key_get_str(env: FunctionEnvMut<WebAssemblyEnv>, string_key: ExternRef
fn effect_parameter_get_type(env: FunctionEnvMut<WebAssemblyEnv>, parameter: ExternRef<EffectParameter>) -> u8 { fn effect_parameter_get_type(env: FunctionEnvMut<WebAssemblyEnv>, parameter: ExternRef<EffectParameter>) -> u8 {
let v = parameter.value_func(&env).unwrap(); let v = parameter.value_func(&env).unwrap();
match v { match v {
EffectParameter::Bool(_) => 1, EffectParameter::Bool(_, _) => 1,
EffectParameter::Int(_) => 2, EffectParameter::Int(_, _) => 2,
EffectParameter::Float(_) => 3, EffectParameter::Float(_, _) => 3,
EffectParameter::String(_) => 4, EffectParameter::String(_, _) => 4,
} }
} }
@ -149,7 +149,7 @@ fn effect_parameter_get_type(env: FunctionEnvMut<WebAssemblyEnv>, parameter: Ext
fn effect_parameter_as_bool(env: FunctionEnvMut<WebAssemblyEnv>, parameter: ExternRef<EffectParameter>) -> u8 { fn effect_parameter_as_bool(env: FunctionEnvMut<WebAssemblyEnv>, parameter: ExternRef<EffectParameter>) -> u8 {
let v = parameter.value_func(&env).unwrap(); let v = parameter.value_func(&env).unwrap();
match v { match v {
EffectParameter::Bool(b) => { EffectParameter::Bool(_, b) => {
if *b { if *b {
1 1
} else { } else {
@ -164,7 +164,7 @@ fn effect_parameter_as_bool(env: FunctionEnvMut<WebAssemblyEnv>, parameter: Exte
fn effect_parameter_as_int(env: FunctionEnvMut<WebAssemblyEnv>, parameter: ExternRef<EffectParameter>) -> i64 { fn effect_parameter_as_int(env: FunctionEnvMut<WebAssemblyEnv>, parameter: ExternRef<EffectParameter>) -> i64 {
let v = parameter.value_func(&env).unwrap(); let v = parameter.value_func(&env).unwrap();
match v { match v {
EffectParameter::Int(i) => *i, EffectParameter::Int(_, i) => *i,
_ => panic!("Unexpected parameter type!"), _ => panic!("Unexpected parameter type!"),
} }
} }
@ -173,7 +173,7 @@ fn effect_parameter_as_int(env: FunctionEnvMut<WebAssemblyEnv>, parameter: Exter
fn effect_parameter_as_float(env: FunctionEnvMut<WebAssemblyEnv>, parameter: ExternRef<EffectParameter>) -> f32 { fn effect_parameter_as_float(env: FunctionEnvMut<WebAssemblyEnv>, parameter: ExternRef<EffectParameter>) -> f32 {
let v = parameter.value_func(&env).unwrap(); let v = parameter.value_func(&env).unwrap();
match v { match v {
EffectParameter::Float(f) => *f, EffectParameter::Float(_, f) => *f,
_ => panic!("Unexpected parameter type!"), _ => panic!("Unexpected parameter type!"),
} }
} }
@ -185,7 +185,7 @@ fn effect_parameter_as_string(
) -> ExternRef<StringKey> { ) -> ExternRef<StringKey> {
let v = parameter.value_func(&env).unwrap(); let v = parameter.value_func(&env).unwrap();
match v { match v {
EffectParameter::String(s) => ExternRef::func_new(&env, s), EffectParameter::String(_, s) => ExternRef::func_new(&env, s),
_ => panic!("Unexpected parameter type!"), _ => panic!("Unexpected parameter type!"),
} }
} }

View File

@ -2,7 +2,7 @@ use hashbrown::HashSet;
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// An item category defines which bag slot items are stored in. /// An item category defines which bag slot items are stored in.
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
@ -48,6 +48,8 @@ pub enum BattleItemCategory {
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub struct Item { pub struct Item {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The name of the item. /// The name of the item.
name: StringKey, name: StringKey,
/// Which bag slot items are stored in. /// Which bag slot items are stored in.
@ -70,6 +72,7 @@ impl Item {
flags: HashSet<StringKey>, flags: HashSet<StringKey>,
) -> Item { ) -> Item {
Item { Item {
identifier: Default::default(),
name: name.clone(), name: name.clone(),
category, category,
battle_category, battle_category,
@ -104,3 +107,9 @@ impl Item {
self.flags.contains(key) self.flags.contains(key)
} }
} }
impl ValueIdentifiable for Item {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}

View File

@ -4,11 +4,13 @@ use indexmap::IndexMap;
use crate::static_data::Ability; use crate::static_data::Ability;
use crate::static_data::DataLibrary; use crate::static_data::DataLibrary;
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// A storage for all abilities that can be used in this data library. /// A storage for all abilities that can be used in this data library.
#[derive(Debug)] #[derive(Debug)]
pub struct AbilityLibrary { pub struct AbilityLibrary {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The underlying map for the library. /// The underlying map for the library.
map: IndexMap<StringKey, Arc<Ability>>, map: IndexMap<StringKey, Arc<Ability>>,
} }
@ -17,6 +19,7 @@ impl AbilityLibrary {
/// Instantiates a new ability library. /// Instantiates a new ability library.
pub fn new(capacity: usize) -> AbilityLibrary { pub fn new(capacity: usize) -> AbilityLibrary {
AbilityLibrary { AbilityLibrary {
identifier: Default::default(),
map: IndexMap::with_capacity(capacity), map: IndexMap::with_capacity(capacity),
} }
} }
@ -31,18 +34,25 @@ impl DataLibrary<'_, Ability> for AbilityLibrary {
} }
} }
impl ValueIdentifiable for AbilityLibrary {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use crate::static_data::Ability; use crate::static_data::Ability;
use crate::static_data::AbilityLibrary; use crate::static_data::AbilityLibrary;
use crate::static_data::DataLibrary; use crate::static_data::DataLibrary;
use crate::StringKey; use crate::StringKey;
use std::sync::Arc;
pub fn build() -> AbilityLibrary { pub fn build() -> AbilityLibrary {
let mut lib = AbilityLibrary::new(1); let mut lib = AbilityLibrary::new(1);
lib.add( lib.add(
&StringKey::new("test_ability".into()), &StringKey::new("test_ability".into()),
Ability::new(&"test_ability".into(), &"test_ability".into(), Vec::new()), Arc::new(Ability::new(&"test_ability".into(), &"test_ability".into(), Vec::new())),
); );
// Drops borrow as mut // Drops borrow as mut

View File

@ -14,8 +14,8 @@ pub trait DataLibrary<'a, T: 'a> {
fn get_modify(&mut self) -> &mut IndexMap<StringKey, Arc<T>>; fn get_modify(&mut self) -> &mut IndexMap<StringKey, Arc<T>>;
/// Adds a new value to the library. /// Adds a new value to the library.
fn add(&mut self, key: &StringKey, value: T) { fn add(&mut self, key: &StringKey, value: Arc<T>) {
self.get_modify().insert(key.clone(), Arc::new(value)); self.get_modify().insert(key.clone(), value);
} }
/// Removes a value from the library. /// Removes a value from the library.

View File

@ -5,10 +5,12 @@ use hashbrown::HashMap;
use crate::defines::LevelInt; use crate::defines::LevelInt;
use crate::static_data::GrowthRate; use crate::static_data::GrowthRate;
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// A library to store all growth rates. /// A library to store all growth rates.
pub struct GrowthRateLibrary { pub struct GrowthRateLibrary {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The underlying data structure. /// The underlying data structure.
growth_rates: HashMap<StringKey, Box<dyn GrowthRate>>, growth_rates: HashMap<StringKey, Box<dyn GrowthRate>>,
} }
@ -17,6 +19,7 @@ impl GrowthRateLibrary {
/// Instantiates a new growth rate library with a capacity. /// Instantiates a new growth rate library with a capacity.
pub fn new(capacity: usize) -> GrowthRateLibrary { pub fn new(capacity: usize) -> GrowthRateLibrary {
GrowthRateLibrary { GrowthRateLibrary {
identifier: Default::default(),
growth_rates: HashMap::with_capacity(capacity), growth_rates: HashMap::with_capacity(capacity),
} }
} }
@ -36,6 +39,12 @@ impl GrowthRateLibrary {
} }
} }
impl ValueIdentifiable for GrowthRateLibrary {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
impl Debug for GrowthRateLibrary { impl Debug for GrowthRateLibrary {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("GrowthRateLibrary").finish() f.debug_struct("GrowthRateLibrary").finish()

View File

@ -4,12 +4,14 @@ use indexmap::IndexMap;
use crate::static_data::DataLibrary; use crate::static_data::DataLibrary;
use crate::static_data::Item; use crate::static_data::Item;
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// A library to store all items. /// A library to store all items.
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub struct ItemLibrary { pub struct ItemLibrary {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The underlying data structure. /// The underlying data structure.
map: IndexMap<StringKey, Arc<Item>>, map: IndexMap<StringKey, Arc<Item>>,
} }
@ -18,6 +20,7 @@ impl ItemLibrary {
/// Instantiates a new Item Library. /// Instantiates a new Item Library.
pub fn new(capacity: usize) -> ItemLibrary { pub fn new(capacity: usize) -> ItemLibrary {
ItemLibrary { ItemLibrary {
identifier: Default::default(),
map: IndexMap::with_capacity(capacity), map: IndexMap::with_capacity(capacity),
} }
} }
@ -33,9 +36,16 @@ impl DataLibrary<'_, Item> for ItemLibrary {
} }
} }
impl ValueIdentifiable for ItemLibrary {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use hashbrown::HashSet; use hashbrown::HashSet;
use std::sync::Arc;
use crate::static_data::libraries::data_library::DataLibrary; use crate::static_data::libraries::data_library::DataLibrary;
use crate::static_data::libraries::item_library::ItemLibrary; use crate::static_data::libraries::item_library::ItemLibrary;
@ -57,7 +67,7 @@ pub mod tests {
let m = build_item(); let m = build_item();
// Borrow as mut so we can insert // Borrow as mut so we can insert
let w = &mut lib; let w = &mut lib;
w.add(&"foo".into(), m); w.add(&"foo".into(), Arc::new(m));
// Drops borrow as mut // Drops borrow as mut
lib lib

View File

@ -1,9 +1,12 @@
use crate::defines::LevelInt; use crate::defines::LevelInt;
use crate::{ValueIdentifiable, ValueIdentifier};
/// This library holds several misc settings for the library. /// This library holds several misc settings for the library.
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub struct LibrarySettings { pub struct LibrarySettings {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The highest level a Pokemon can be. /// The highest level a Pokemon can be.
maximum_level: LevelInt, maximum_level: LevelInt,
} }
@ -11,7 +14,10 @@ pub struct LibrarySettings {
impl LibrarySettings { impl LibrarySettings {
/// Creates a new settings library. /// Creates a new settings library.
pub fn new(maximum_level: LevelInt) -> Self { pub fn new(maximum_level: LevelInt) -> Self {
Self { maximum_level } Self {
identifier: Default::default(),
maximum_level,
}
} }
/// The highest level a Pokemon can be. /// The highest level a Pokemon can be.
@ -19,3 +25,9 @@ impl LibrarySettings {
self.maximum_level self.maximum_level
} }
} }
impl ValueIdentifiable for LibrarySettings {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}

View File

@ -4,12 +4,14 @@ use indexmap::IndexMap;
use crate::static_data::DataLibrary; use crate::static_data::DataLibrary;
use crate::static_data::MoveData; use crate::static_data::MoveData;
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// A library to store all data for moves. /// A library to store all data for moves.
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub struct MoveLibrary { pub struct MoveLibrary {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The underlying map. /// The underlying map.
map: IndexMap<StringKey, Arc<MoveData>>, map: IndexMap<StringKey, Arc<MoveData>>,
} }
@ -18,6 +20,7 @@ impl MoveLibrary {
/// Instantiates a new Move Library. /// Instantiates a new Move Library.
pub fn new(capacity: usize) -> MoveLibrary { pub fn new(capacity: usize) -> MoveLibrary {
MoveLibrary { MoveLibrary {
identifier: Default::default(),
map: IndexMap::with_capacity(capacity), map: IndexMap::with_capacity(capacity),
} }
} }
@ -32,9 +35,16 @@ impl DataLibrary<'_, MoveData> for MoveLibrary {
} }
} }
impl ValueIdentifiable for MoveLibrary {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use hashbrown::HashSet; use hashbrown::HashSet;
use std::sync::Arc;
use crate::static_data::libraries::data_library::DataLibrary; use crate::static_data::libraries::data_library::DataLibrary;
use crate::static_data::libraries::move_library::MoveLibrary; use crate::static_data::libraries::move_library::MoveLibrary;
@ -61,7 +71,7 @@ pub mod tests {
let m = build_move(); let m = build_move();
// Borrow as mut so we can insert // Borrow as mut so we can insert
let w = &mut lib; let w = &mut lib;
w.add(&StringKey::new("foo".into()), m); w.add(&StringKey::new("foo".into()), Arc::new(m));
// Drops borrow as mut // Drops borrow as mut
lib lib

View File

@ -1,11 +1,13 @@
use crate::static_data::Nature; use crate::static_data::Nature;
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
use hashbrown::HashMap; use hashbrown::HashMap;
use std::sync::Arc; use std::sync::Arc;
/// A library of all natures that can be used, stored by their names. /// A library of all natures that can be used, stored by their names.
#[derive(Debug)] #[derive(Debug)]
pub struct NatureLibrary { pub struct NatureLibrary {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The underlying data structure. /// The underlying data structure.
map: HashMap<StringKey, Arc<Nature>>, map: HashMap<StringKey, Arc<Nature>>,
} }
@ -14,13 +16,14 @@ impl NatureLibrary {
/// Creates a new nature library with a given capacity. /// Creates a new nature library with a given capacity.
pub fn new(capacity: usize) -> Self { pub fn new(capacity: usize) -> Self {
NatureLibrary { NatureLibrary {
identifier: Default::default(),
map: HashMap::with_capacity(capacity), map: HashMap::with_capacity(capacity),
} }
} }
/// Adds a new nature with name to the library. /// Adds a new nature with name to the library.
pub fn load_nature(&mut self, name: StringKey, nature: Nature) { pub fn load_nature(&mut self, name: StringKey, nature: Arc<Nature>) {
self.map.insert(name, Arc::new(nature)); self.map.insert(name, nature);
} }
/// Gets a nature by name. /// Gets a nature by name.
@ -29,11 +32,11 @@ impl NatureLibrary {
} }
/// Finds a nature name by nature. /// Finds a nature name by nature.
pub fn get_nature_name(&self, nature: &Arc<Nature>) -> StringKey { pub fn get_nature_name(&self, nature: &Nature) -> StringKey {
for kv in &self.map { for kv in &self.map {
// As natures can't be copied, and should always be the same reference as the value // As natures can't be copied, and should always be the same reference as the value
// in the map, we just compare by reference. // in the map, we just compare by reference.
if Arc::ptr_eq(kv.1, nature) { if std::ptr::eq(Arc::as_ptr(kv.1), nature) {
return kv.0.clone(); return kv.0.clone();
} }
} }
@ -41,6 +44,12 @@ impl NatureLibrary {
} }
} }
impl ValueIdentifiable for NatureLibrary {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use crate::static_data::statistics::Statistic; use crate::static_data::statistics::Statistic;

View File

@ -4,12 +4,14 @@ use indexmap::IndexMap;
use crate::static_data::DataLibrary; use crate::static_data::DataLibrary;
use crate::static_data::Species; use crate::static_data::Species;
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// A library to store all data for Pokemon species. /// A library to store all data for Pokemon species.
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub struct SpeciesLibrary { pub struct SpeciesLibrary {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The underlying map. /// The underlying map.
map: IndexMap<StringKey, Arc<Species>>, map: IndexMap<StringKey, Arc<Species>>,
} }
@ -18,6 +20,7 @@ impl SpeciesLibrary {
/// Instantiates a new Species Library. /// Instantiates a new Species Library.
pub fn new(capacity: usize) -> SpeciesLibrary { pub fn new(capacity: usize) -> SpeciesLibrary {
SpeciesLibrary { SpeciesLibrary {
identifier: Default::default(),
map: IndexMap::with_capacity(capacity), map: IndexMap::with_capacity(capacity),
} }
} }
@ -32,9 +35,16 @@ impl<'a> DataLibrary<'a, Species> for SpeciesLibrary {
} }
} }
impl ValueIdentifiable for SpeciesLibrary {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use hashbrown::HashSet; use hashbrown::HashSet;
use std::sync::Arc;
use crate::static_data::libraries::data_library::DataLibrary; use crate::static_data::libraries::data_library::DataLibrary;
use crate::static_data::libraries::species_library::SpeciesLibrary; use crate::static_data::libraries::species_library::SpeciesLibrary;
@ -50,7 +60,7 @@ pub mod tests {
0.5, 0.5,
&"test_growthrate".into(), &"test_growthrate".into(),
0, 0,
Form::new( Arc::new(Form::new(
&"default".into(), &"default".into(),
0.0, 0.0,
0.0, 0.0,
@ -61,7 +71,7 @@ pub mod tests {
Vec::new(), Vec::new(),
LearnableMoves::new(), LearnableMoves::new(),
HashSet::new(), HashSet::new(),
), )),
HashSet::new(), HashSet::new(),
) )
} }
@ -71,7 +81,7 @@ pub mod tests {
let species = build_species(); let species = build_species();
// Borrow as mut so we can insert // Borrow as mut so we can insert
let w = &mut lib; let w = &mut lib;
w.add(&"foo".into(), species); w.add(&"foo".into(), Arc::new(species));
// Drops borrow as mut // Drops borrow as mut
lib lib

View File

@ -6,11 +6,14 @@ use crate::static_data::MoveLibrary;
use crate::static_data::NatureLibrary; use crate::static_data::NatureLibrary;
use crate::static_data::SpeciesLibrary; use crate::static_data::SpeciesLibrary;
use crate::static_data::TypeLibrary; use crate::static_data::TypeLibrary;
use crate::{ValueIdentifiable, ValueIdentifier};
/// The storage for all different libraries. /// The storage for all different libraries.
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub struct StaticData { pub struct StaticData {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// Several misc settings for the library. /// Several misc settings for the library.
settings: LibrarySettings, settings: LibrarySettings,
/// All data for Pokemon species. /// All data for Pokemon species.
@ -33,6 +36,7 @@ impl StaticData {
/// Instantiates a new data collection. /// Instantiates a new data collection.
pub fn new(settings: LibrarySettings) -> Self { pub fn new(settings: LibrarySettings) -> Self {
Self { Self {
identifier: Default::default(),
settings, settings,
species: SpeciesLibrary::new(0), species: SpeciesLibrary::new(0),
moves: MoveLibrary::new(0), moves: MoveLibrary::new(0),
@ -106,6 +110,12 @@ impl StaticData {
} }
} }
impl ValueIdentifiable for StaticData {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)] #[cfg(test)]
pub mod test { pub mod test {
use crate::static_data::libraries::library_settings::LibrarySettings; use crate::static_data::libraries::library_settings::LibrarySettings;
@ -116,6 +126,7 @@ pub mod test {
pub fn build() -> StaticData { pub fn build() -> StaticData {
StaticData { StaticData {
identifier: Default::default(),
settings: LibrarySettings::new(100), settings: LibrarySettings::new(100),
species: species_library::tests::build(), species: species_library::tests::build(),
moves: move_library::tests::build(), moves: move_library::tests::build(),

View File

@ -1,7 +1,7 @@
use atomig::Atom; use atomig::Atom;
use hashbrown::HashMap; use hashbrown::HashMap;
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// A unique key that can be used to store a reference to a type. Opaque reference to a byte /// A unique key that can be used to store a reference to a type. Opaque reference to a byte
/// internally. /// internally.
@ -28,6 +28,8 @@ impl From<TypeIdentifier> for u8 {
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub struct TypeLibrary { pub struct TypeLibrary {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// A list of types /// A list of types
types: HashMap<StringKey, TypeIdentifier>, types: HashMap<StringKey, TypeIdentifier>,
/// The effectiveness of the different types against each other. /// The effectiveness of the different types against each other.
@ -38,6 +40,7 @@ impl TypeLibrary {
/// Instantiates a new type library with a specific capacity. /// Instantiates a new type library with a specific capacity.
pub fn new(capacity: usize) -> TypeLibrary { pub fn new(capacity: usize) -> TypeLibrary {
TypeLibrary { TypeLibrary {
identifier: Default::default(),
types: HashMap::with_capacity(capacity), types: HashMap::with_capacity(capacity),
effectiveness: vec![], effectiveness: vec![],
} }
@ -93,6 +96,12 @@ impl TypeLibrary {
} }
} }
impl ValueIdentifiable for TypeLibrary {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use assert_approx_eq::assert_approx_eq; use assert_approx_eq::assert_approx_eq;

View File

@ -1,4 +1,4 @@
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
#[doc(inline)] #[doc(inline)]
pub use growth_rates::*; pub use growth_rates::*;
#[doc(inline)] #[doc(inline)]
@ -40,22 +40,57 @@ mod statistics;
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub enum EffectParameter { pub enum EffectParameter {
/// A boolean value. /// A boolean value.
Bool(bool), Bool(ValueIdentifier, bool),
/// An integer value. Stored as a 64 bit int to deal with potentially large numbers. /// An integer value. Stored as a 64 bit int to deal with potentially large numbers.
Int(i64), Int(ValueIdentifier, i64),
/// A float value. Stored as a 32 bit float. /// A float value. Stored as a 32 bit float.
Float(f32), Float(ValueIdentifier, f32),
/// A string value. /// A string value.
String(StringKey), String(ValueIdentifier, StringKey),
}
impl Into<EffectParameter> for bool {
fn into(self) -> EffectParameter {
EffectParameter::Bool(Default::default(), self)
}
}
impl Into<EffectParameter> for i64 {
fn into(self) -> EffectParameter {
EffectParameter::Int(Default::default(), self)
}
}
impl Into<EffectParameter> for f32 {
fn into(self) -> EffectParameter {
EffectParameter::Float(Default::default(), self)
}
}
impl Into<EffectParameter> for StringKey {
fn into(self) -> EffectParameter {
EffectParameter::String(Default::default(), self)
}
} }
impl Display for EffectParameter { impl Display for EffectParameter {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self { match self {
EffectParameter::Bool(v) => f.write_fmt(format_args!("EffectParameter::Bool({})", v)), EffectParameter::Bool(_, v) => f.write_fmt(format_args!("EffectParameter::Bool({})", v)),
EffectParameter::Int(v) => f.write_fmt(format_args!("EffectParameter::Int({})", v)), EffectParameter::Int(_, v) => f.write_fmt(format_args!("EffectParameter::Int({})", v)),
EffectParameter::Float(v) => f.write_fmt(format_args!("EffectParameter::Float({})", v)), EffectParameter::Float(_, v) => f.write_fmt(format_args!("EffectParameter::Float({})", v)),
EffectParameter::String(v) => f.write_fmt(format_args!("EffectParameter::String({})", v)), EffectParameter::String(_, v) => f.write_fmt(format_args!("EffectParameter::String({})", v)),
}
}
}
impl ValueIdentifiable for EffectParameter {
fn value_identifier(&self) -> ValueIdentifier {
match self {
EffectParameter::Bool(i, _) => *i,
EffectParameter::Int(i, _) => *i,
EffectParameter::Float(i, _) => *i,
EffectParameter::String(i, _) => *i,
} }
} }
} }

View File

@ -3,7 +3,7 @@ use hashbrown::HashSet;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::static_data::{SecondaryEffect, TypeIdentifier}; use crate::static_data::{SecondaryEffect, TypeIdentifier};
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// The move category defines what global kind of move this move is. /// The move category defines what global kind of move this move is.
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
@ -63,6 +63,8 @@ pub enum MoveTarget {
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub struct MoveData { pub struct MoveData {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The name of the move. /// The name of the move.
name: StringKey, name: StringKey,
/// The attacking type of the move. /// The attacking type of the move.
@ -101,6 +103,7 @@ impl MoveData {
flags: HashSet<StringKey>, flags: HashSet<StringKey>,
) -> MoveData { ) -> MoveData {
MoveData { MoveData {
identifier: Default::default(),
name: name.clone(), name: name.clone(),
move_type, move_type,
category, category,
@ -163,3 +166,9 @@ impl MoveData {
self.flags.contains::<u32>(&key_hash) self.flags.contains::<u32>(&key_hash)
} }
} }
impl ValueIdentifiable for MoveData {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}

View File

@ -1,9 +1,11 @@
use crate::static_data::EffectParameter; use crate::static_data::EffectParameter;
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// A secondary effect is an effect on a move that happens after it hits. /// A secondary effect is an effect on a move that happens after it hits.
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub struct SecondaryEffect { pub struct SecondaryEffect {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The chance in percentages that the effect triggers. -1 to make it always trigger. /// The chance in percentages that the effect triggers. -1 to make it always trigger.
chance: f32, chance: f32,
/// The name of the effect. /// The name of the effect.
@ -16,6 +18,7 @@ impl SecondaryEffect {
/// Instantiates a new Secondary Effect. /// Instantiates a new Secondary Effect.
pub fn new(chance: f32, effect_name: StringKey, parameters: Vec<EffectParameter>) -> SecondaryEffect { pub fn new(chance: f32, effect_name: StringKey, parameters: Vec<EffectParameter>) -> SecondaryEffect {
SecondaryEffect { SecondaryEffect {
identifier: Default::default(),
chance, chance,
effect_name, effect_name,
parameters, parameters,
@ -36,6 +39,12 @@ impl SecondaryEffect {
} }
} }
impl ValueIdentifiable for SecondaryEffect {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use assert_approx_eq::assert_approx_eq; use assert_approx_eq::assert_approx_eq;

View File

@ -1,9 +1,13 @@
use crate::static_data::Statistic; use crate::static_data::Statistic;
use crate::{ValueIdentifiable, ValueIdentifier};
use std::sync::Arc;
/// A nature is an attribute on a Pokemon that modifies the effective base stats on a Pokemon. They /// A nature is an attribute on a Pokemon that modifies the effective base stats on a Pokemon. They
/// can have an increased statistic and a decreased statistic, or be neutral. /// can have an increased statistic and a decreased statistic, or be neutral.
#[derive(Debug)] #[derive(Debug)]
pub struct Nature { pub struct Nature {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The stat that should receive the increased modifier. /// The stat that should receive the increased modifier.
increase_stat: Statistic, increase_stat: Statistic,
/// The stat that should receive the decreased modifier. /// The stat that should receive the decreased modifier.
@ -21,13 +25,14 @@ impl Nature {
decrease_stat: Statistic, decrease_stat: Statistic,
increase_modifier: f32, increase_modifier: f32,
decrease_modifier: f32, decrease_modifier: f32,
) -> Self { ) -> Arc<Self> {
Self { Arc::new(Self {
identifier: Default::default(),
increase_stat, increase_stat,
decrease_stat, decrease_stat,
increase_modifier, increase_modifier,
decrease_modifier, decrease_modifier,
} })
} }
/// The stat that should receive the increased modifier. /// The stat that should receive the increased modifier.
@ -52,3 +57,9 @@ impl Nature {
} }
} }
} }
impl ValueIdentifiable for Nature {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}

View File

@ -1,9 +1,11 @@
use crate::static_data::EffectParameter; use crate::static_data::EffectParameter;
use crate::StringKey; use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
/// An ability is a passive effect in battle that is attached to a Pokemon. /// An ability is a passive effect in battle that is attached to a Pokemon.
#[derive(Debug)] #[derive(Debug)]
pub struct Ability { pub struct Ability {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The name of the ability. /// The name of the ability.
name: StringKey, name: StringKey,
/// The name of the script effect of the ability. /// The name of the script effect of the ability.
@ -16,6 +18,7 @@ impl Ability {
/// Instantiates a new ability. /// Instantiates a new ability.
pub fn new(name: &StringKey, effect: &StringKey, parameters: Vec<EffectParameter>) -> Self { pub fn new(name: &StringKey, effect: &StringKey, parameters: Vec<EffectParameter>) -> Self {
Self { Self {
identifier: Default::default(),
name: name.clone(), name: name.clone(),
effect: effect.clone(), effect: effect.clone(),
parameters, parameters,
@ -36,6 +39,12 @@ impl Ability {
} }
} }
impl ValueIdentifiable for Ability {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
/// An ability index allows us to find an ability on a form. It combines a bool for whether the /// An ability index allows us to find an ability on a form. It combines a bool for whether the
/// ability is hidden or not, and then an index of the ability. /// ability is hidden or not, and then an index of the ability.
#[derive(Copy, Clone, Debug, Eq, PartialEq)] #[derive(Copy, Clone, Debug, Eq, PartialEq)]

View File

@ -4,13 +4,15 @@ use crate::static_data::Statistic;
use crate::static_data::TypeIdentifier; use crate::static_data::TypeIdentifier;
use crate::static_data::{Ability, StaticStatisticSet}; use crate::static_data::{Ability, StaticStatisticSet};
use crate::static_data::{AbilityIndex, LearnableMoves}; use crate::static_data::{AbilityIndex, LearnableMoves};
use crate::Random;
use crate::StringKey; use crate::StringKey;
use crate::{Random, ValueIdentifiable, ValueIdentifier};
/// A form is a variant of a specific species. A species always has at least one form, but can have /// A form is a variant of a specific species. A species always has at least one form, but can have
/// many more. /// many more.
#[derive(Debug)] #[derive(Debug)]
pub struct Form { pub struct Form {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The name of the form. /// The name of the form.
name: StringKey, name: StringKey,
/// The height of the form in meters. /// The height of the form in meters.
@ -48,6 +50,7 @@ impl Form {
flags: HashSet<StringKey>, flags: HashSet<StringKey>,
) -> Form { ) -> Form {
Form { Form {
identifier: Default::default(),
name: name.clone(), name: name.clone(),
height, height,
weight, weight,
@ -156,3 +159,9 @@ impl Form {
self.flags.contains(key) self.flags.contains(key)
} }
} }
impl ValueIdentifiable for Form {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}

View File

@ -1,16 +1,20 @@
use std::sync::{Arc, LazyLock}; use std::sync::{Arc, LazyLock};
use hashbrown::{HashMap, HashSet}; use hashbrown::{HashMap, HashSet};
use parking_lot::lock_api::RwLockReadGuard;
use parking_lot::{RawRwLock, RwLock};
use crate::static_data::Form; use crate::static_data::Form;
use crate::static_data::Gender; use crate::static_data::Gender;
use crate::Random;
use crate::StringKey; use crate::StringKey;
use crate::{Random, ValueIdentifiable, ValueIdentifier};
/// The data belonging to a Pokemon with certain characteristics. /// The data belonging to a Pokemon with certain characteristics.
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))]
pub struct Species { pub struct Species {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The national dex identifier of the Pokemon. /// The national dex identifier of the Pokemon.
id: u16, id: u16,
/// The name of the Pokemon. /// The name of the Pokemon.
@ -23,7 +27,7 @@ pub struct Species {
/// uncatchable. /// uncatchable.
capture_rate: u8, capture_rate: u8,
/// The forms that belong to this Pokemon. /// The forms that belong to this Pokemon.
forms: HashMap<StringKey, Arc<Form>>, forms: RwLock<HashMap<StringKey, Arc<Form>>>,
/// The arbitrary flags that can be set on a Pokemon for script use. /// The arbitrary flags that can be set on a Pokemon for script use.
flags: HashSet<StringKey>, flags: HashSet<StringKey>,
} }
@ -44,18 +48,19 @@ impl Species {
gender_rate: f32, gender_rate: f32,
growth_rate: &StringKey, growth_rate: &StringKey,
capture_rate: u8, capture_rate: u8,
default_form: Form, default_form: Arc<Form>,
flags: HashSet<StringKey>, flags: HashSet<StringKey>,
) -> Species { ) -> Species {
let mut forms = HashMap::with_capacity(1); let mut forms = HashMap::with_capacity(1);
forms.insert_unique_unchecked(get_default_key(), Arc::new(default_form)); forms.insert_unique_unchecked(get_default_key(), default_form);
Species { Species {
identifier: Default::default(),
id, id,
name: name.clone(), name: name.clone(),
gender_rate, gender_rate,
growth_rate: growth_rate.clone(), growth_rate: growth_rate.clone(),
capture_rate, capture_rate,
forms, forms: RwLock::new(forms),
flags, flags,
} }
} }
@ -82,8 +87,8 @@ impl Species {
self.capture_rate self.capture_rate
} }
/// The forms that belong to this Pokemon. /// The forms that belong to this Pokemon.
pub fn forms(&self) -> &HashMap<StringKey, Arc<Form>> { pub fn forms(&self) -> RwLockReadGuard<'_, RawRwLock, HashMap<StringKey, Arc<Form>>> {
&self.forms self.forms.read()
} }
/// The arbitrary flags that can be set on a Pokemon for script use. /// The arbitrary flags that can be set on a Pokemon for script use.
pub fn flags(&self) -> &HashSet<StringKey> { pub fn flags(&self) -> &HashSet<StringKey> {
@ -91,18 +96,18 @@ impl Species {
} }
/// Adds a new form to the species. /// Adds a new form to the species.
pub fn add_form(&mut self, id: StringKey, form: Form) { pub fn add_form(&self, id: StringKey, form: Arc<Form>) {
self.forms.insert(id, Arc::new(form)); self.forms.write().insert(id, form);
} }
/// Gets a form by name. /// Gets a form by name.
pub fn get_form(&self, id: &StringKey) -> Option<&Arc<Form>> { pub fn get_form(&self, id: &StringKey) -> Option<Arc<Form>> {
self.forms.get(id) self.forms.read().get(id).cloned()
} }
/// Gets the form the Pokemon will have by default, if no other form is specified. /// Gets the form the Pokemon will have by default, if no other form is specified.
pub fn get_default_form(&self) -> &Arc<Form> { pub fn get_default_form(&self) -> Arc<Form> {
self.forms.get(&get_default_key()).unwrap() self.forms.read().get(&get_default_key()).unwrap().clone()
} }
/// Gets a random gender. /// Gets a random gender.
@ -121,3 +126,9 @@ impl Species {
self.flags.contains(key) self.flags.contains(key)
} }
} }
impl ValueIdentifiable for Species {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}

View File

@ -1,5 +1,6 @@
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
use crate::{ValueIdentifiable, ValueIdentifier};
use atomig::impls::{PrimitiveAtom, PrimitiveAtomInteger}; use atomig::impls::{PrimitiveAtom, PrimitiveAtomInteger};
use atomig::{Atom, AtomInteger, Atomic}; use atomig::{Atom, AtomInteger, Atomic};
use num_traits::{clamp, NumCast, PrimInt}; use num_traits::{clamp, NumCast, PrimInt};
@ -20,6 +21,8 @@ where
<T as Atom>::Repr: PrimitiveAtomInteger, <T as Atom>::Repr: PrimitiveAtomInteger,
T: AtomInteger, T: AtomInteger,
{ {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The health point stat value. /// The health point stat value.
hp: Atomic<T>, hp: Atomic<T>,
/// The physical attack stat value. /// The physical attack stat value.
@ -45,6 +48,7 @@ where
/// Creates a new statistic set with given stats. /// Creates a new statistic set with given stats.
pub fn new(hp: T, attack: T, defense: T, special_attack: T, special_defense: T, speed: T) -> Self { pub fn new(hp: T, attack: T, defense: T, special_attack: T, special_defense: T, speed: T) -> Self {
Self { Self {
identifier: Default::default(),
hp: Atomic::<T>::new(hp), hp: Atomic::<T>::new(hp),
attack: Atomic::<T>::new(attack), attack: Atomic::<T>::new(attack),
defense: Atomic::<T>::new(defense), defense: Atomic::<T>::new(defense),
@ -128,6 +132,19 @@ where
} }
} }
impl<T> ValueIdentifiable for StatisticSet<T>
where
T: PrimitiveAtom,
T: Atom,
T: PrimitiveAtomInteger,
<T as Atom>::Repr: PrimitiveAtomInteger,
T: AtomInteger,
{
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
/// A collection of statistics that can not be modified after creation. /// A collection of statistics that can not be modified after creation.
/// ///
/// As no modifications happen, this struct does not use atomics. /// As no modifications happen, this struct does not use atomics.
@ -136,6 +153,8 @@ pub struct StaticStatisticSet<T>
where where
T: PrimInt, T: PrimInt,
{ {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The health point stat value. /// The health point stat value.
hp: T, hp: T,
/// The physical attack stat value. /// The physical attack stat value.
@ -155,8 +174,9 @@ where
T: PrimInt, T: PrimInt,
{ {
/// Create a new static statistic set. /// Create a new static statistic set.
pub const fn new(hp: T, attack: T, defense: T, special_attack: T, special_defense: T, speed: T) -> Self { pub fn new(hp: T, attack: T, defense: T, special_attack: T, special_defense: T, speed: T) -> Self {
Self { Self {
identifier: Default::default(),
hp, hp,
attack, attack,
defense, defense,
@ -204,6 +224,15 @@ where
} }
} }
impl<T> ValueIdentifiable for StaticStatisticSet<T>
where
T: PrimInt,
{
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
/// A clamped statistic set holds the 6 normal stats for a Pokemon, but ensures it always remains /// A clamped statistic set holds the 6 normal stats for a Pokemon, but ensures it always remains
/// between two values (inclusive on the two values). /// between two values (inclusive on the two values).
#[derive(Default, Debug)] #[derive(Default, Debug)]
@ -218,6 +247,8 @@ where
T: NumCast, T: NumCast,
T: PrimInt, T: PrimInt,
{ {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
/// The health point stat value. /// The health point stat value.
hp: Atomic<T>, hp: Atomic<T>,
/// The physical attack stat value. /// The physical attack stat value.
@ -264,6 +295,7 @@ where
/// Instantiates a new clamped statistic set. /// Instantiates a new clamped statistic set.
pub fn new(hp: T, attack: T, defense: T, special_attack: T, special_defense: T, speed: T) -> Self { pub fn new(hp: T, attack: T, defense: T, special_attack: T, special_defense: T, speed: T) -> Self {
Self { Self {
identifier: Default::default(),
hp: Self::clamped_cast(hp), hp: Self::clamped_cast(hp),
attack: Self::clamped_cast(attack), attack: Self::clamped_cast(attack),
defense: Self::clamped_cast(defense), defense: Self::clamped_cast(defense),
@ -377,6 +409,21 @@ where
} }
} }
impl<T, const MIN: i64, const MAX: i64> ValueIdentifiable for ClampedStatisticSet<T, MIN, MAX>
where
T: PrimitiveAtom,
T: Atom,
T: PrimitiveAtomInteger,
<T as Atom>::Repr: PrimitiveAtomInteger,
T: AtomInteger,
T: NumCast,
T: PrimInt,
{
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;

View File

@ -2,9 +2,12 @@
pub use random::Random; pub use random::Random;
#[doc(inline)] #[doc(inline)]
pub use string_key::StringKey; pub use string_key::StringKey;
#[doc(inline)]
pub use value_identifier::*;
/// The random module defines a RNG implementation used in pkmn_lib /// The random module defines a RNG implementation used in pkmn_lib
mod random; mod random;
/// The string_key module defines a custom string handling for reduced allocations and fast lookups /// The string_key module defines a custom string handling for reduced allocations and fast lookups
/// and equality checks. /// and equality checks.
mod string_key; mod string_key;
mod value_identifier;

View File

@ -0,0 +1,22 @@
use std::sync::atomic::{AtomicUsize, Ordering};
static CURRENT: AtomicUsize = AtomicUsize::new(1);
/// An extremely basic way to identify a piece of data.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
#[repr(C)]
pub struct ValueIdentifier(usize);
impl Default for ValueIdentifier {
fn default() -> Self {
Self {
0: CURRENT.fetch_add(1, Ordering::SeqCst),
}
}
}
/// An object with a specific identifier.
pub trait ValueIdentifiable {
/// Get the identifier for the current object.
fn value_identifier(&self) -> ValueIdentifier;
}

View File

@ -2,6 +2,7 @@ use std::convert::TryFrom;
use std::fmt::Debug; use std::fmt::Debug;
use std::fs::File; use std::fs::File;
use std::io::{BufReader, Read}; use std::io::{BufReader, Read};
use std::sync::Arc;
use hashbrown::HashSet; use hashbrown::HashSet;
use num_traits::PrimInt; use num_traits::PrimInt;
@ -116,7 +117,10 @@ pub fn load_items(path: &String, lib: &mut ItemLibrary) {
} }
} }
lib.add(&name, Item::new(&name, category, battle_category, price as i32, flags)); lib.add(
&name,
Arc::new(Item::new(&name, category, battle_category, price as i32, flags)),
);
} }
} }
@ -159,7 +163,7 @@ pub fn load_abilities(path: &String, ability_library: &mut AbilityLibrary) {
} }
} }
ability_library.add(&name, Ability::new(&name, &effect, parameters)); ability_library.add(&name, Arc::new(Ability::new(&name, &effect, parameters)));
} }
} }
@ -212,7 +216,7 @@ pub fn load_moves(path: &String, lib: &mut StaticData) {
lib.moves_mut().add( lib.moves_mut().add(
&move_name, &move_name,
MoveData::new( Arc::new(MoveData::new(
&move_name.clone(), &move_name.clone(),
move_type_id, move_type_id,
move_category, move_category,
@ -223,7 +227,7 @@ pub fn load_moves(path: &String, lib: &mut StaticData) {
priority, priority,
secondary_effect, secondary_effect,
flags, flags,
), )),
); );
} }
} }
@ -269,7 +273,7 @@ pub fn load_species(path: &String, library: &mut StaticData) {
default_form, default_form,
Default::default(), Default::default(),
); );
library.species_mut().add(&name, species); library.species_mut().add(&name, Arc::new(species));
} }
} }
@ -282,7 +286,7 @@ fn load_wasm(path: &String, library: &mut WebAssemblyScriptResolver) {
library.finalize(); library.finalize();
} }
fn parse_form(name: StringKey, value: &Value, library: &mut StaticData) -> Form { fn parse_form(name: StringKey, value: &Value, library: &mut StaticData) -> Arc<Form> {
let mut abilities = Vec::new(); let mut abilities = Vec::new();
for a in value.get("abilities").unwrap().as_array().unwrap() { for a in value.get("abilities").unwrap().as_array().unwrap() {
abilities.push(StringKey::new(a.as_str().unwrap().into())); abilities.push(StringKey::new(a.as_str().unwrap().into()));
@ -312,7 +316,7 @@ fn parse_form(name: StringKey, value: &Value, library: &mut StaticData) -> Form
let moves = parse_moves(&value.get("moves").unwrap(), library.moves()); let moves = parse_moves(&value.get("moves").unwrap(), library.moves());
Form::new( Arc::new(Form::new(
&name, &name,
height as f32, height as f32,
weight as f32, weight as f32,
@ -323,7 +327,7 @@ fn parse_form(name: StringKey, value: &Value, library: &mut StaticData) -> Form
hidden_abilities, hidden_abilities,
moves, moves,
Default::default(), Default::default(),
) ))
} }
fn parse_statistics<T>(value: &Value) -> StaticStatisticSet<T> fn parse_statistics<T>(value: &Value) -> StaticStatisticSet<T>
@ -389,15 +393,15 @@ fn parse_effect_parameter(value: &Value) -> EffectParameter {
Value::Null => { Value::Null => {
panic!("Unexpected type") panic!("Unexpected type")
} }
Value::Bool(b) => EffectParameter::Bool(*b), Value::Bool(b) => (*b).into(),
Value::Number(n) => { Value::Number(n) => {
if n.is_f64() { if n.is_f64() {
EffectParameter::Float(n.as_f64().unwrap() as f32) (n.as_f64().unwrap() as f32).into()
} else { } else {
EffectParameter::Int(n.as_i64().unwrap()) n.as_i64().unwrap().into()
} }
} }
Value::String(s) => EffectParameter::String(StringKey::new(s.as_str().into())), Value::String(s) => StringKey::new(s.as_str().into()).into(),
Value::Array(_) => { Value::Array(_) => {
panic!("Unexpected type") panic!("Unexpected type")
} }