Rework of FFI, adding a value identifier, so we can keep knowledge of data even when data moves.
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
@@ -1,11 +1,13 @@
|
||||
use crate::static_data::Nature;
|
||||
use crate::StringKey;
|
||||
use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
|
||||
use hashbrown::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A library of all natures that can be used, stored by their names.
|
||||
#[derive(Debug)]
|
||||
pub struct NatureLibrary {
|
||||
/// A unique identifier so we know what value this is.
|
||||
identifier: ValueIdentifier,
|
||||
/// The underlying data structure.
|
||||
map: HashMap<StringKey, Arc<Nature>>,
|
||||
}
|
||||
@@ -14,13 +16,14 @@ impl NatureLibrary {
|
||||
/// Creates a new nature library with a given capacity.
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
NatureLibrary {
|
||||
identifier: Default::default(),
|
||||
map: HashMap::with_capacity(capacity),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a new nature with name to the library.
|
||||
pub fn load_nature(&mut self, name: StringKey, nature: Nature) {
|
||||
self.map.insert(name, Arc::new(nature));
|
||||
pub fn load_nature(&mut self, name: StringKey, nature: Arc<Nature>) {
|
||||
self.map.insert(name, nature);
|
||||
}
|
||||
|
||||
/// Gets a nature by name.
|
||||
@@ -29,11 +32,11 @@ impl NatureLibrary {
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
// As natures can't be copied, and should always be the same reference as the value
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
@@ -41,6 +44,12 @@ impl NatureLibrary {
|
||||
}
|
||||
}
|
||||
|
||||
impl ValueIdentifiable for NatureLibrary {
|
||||
fn value_identifier(&self) -> ValueIdentifier {
|
||||
self.identifier
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use crate::static_data::statistics::Statistic;
|
||||
|
||||
Reference in New Issue
Block a user