Support for serializing and deserializing a Pokemon
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:
@@ -450,3 +450,51 @@ extern "C" fn pokemon_learn_move(
|
||||
extern "C" fn pokemon_clear_status(handle: FFIHandle<Pokemon>) {
|
||||
handle.from_ffi_handle().clear_status()
|
||||
}
|
||||
|
||||
/// Returns a serialized version of the Pokemon as xml.
|
||||
#[cfg(feature = "serde")]
|
||||
#[no_mangle]
|
||||
extern "C" fn pokemon_serialize_as_xml(handle: FFIHandle<Pokemon>) -> FFIResult<OwnedPtrString> {
|
||||
let serialized = match handle.from_ffi_handle().serialize() {
|
||||
Ok(v) => v,
|
||||
Err(err) => return FFIResult::err(err),
|
||||
};
|
||||
let serialized =
|
||||
match serde_xml_rs::to_string(&serialized).map_err(|err| anyhow!("Could not serialize Pokemon: {}", err)) {
|
||||
Ok(v) => v,
|
||||
Err(err) => return FFIResult::err(err),
|
||||
};
|
||||
let cstring = match CString::new(serialized) {
|
||||
Ok(v) => v,
|
||||
Err(err) => return FFIResult::err(anyhow!("Could not convert serialized Pokemon to CString: {}", err)),
|
||||
};
|
||||
FFIResult::ok(OwnedPtrString(cstring.into_raw()))
|
||||
}
|
||||
|
||||
/// Converts an XML representation of a Pokemon to a Pokemon.
|
||||
#[cfg(feature = "serde")]
|
||||
#[no_mangle]
|
||||
extern "C" fn pokemon_deserialize_from_xml(
|
||||
library: FFIHandle<Arc<dyn DynamicLibrary>>,
|
||||
str: OwnedPtrString,
|
||||
) -> FFIResult<FFIHandle<Pokemon>> {
|
||||
let str = unsafe {
|
||||
match CString::from_raw(str.0).to_str() {
|
||||
Ok(v) => v.to_string(),
|
||||
Err(err) => return FFIResult::err(anyhow!("Could not read CString: {}", err)),
|
||||
}
|
||||
};
|
||||
let deserialized = match serde_xml_rs::from_str::<crate::dynamic_data::serialization::SerializedPokemon>(&str)
|
||||
.map_err(|err| anyhow!("Could not deserialize Pokemon: {}", err))
|
||||
{
|
||||
Ok(v) => v,
|
||||
Err(err) => return FFIResult::err(err),
|
||||
};
|
||||
|
||||
let library = library.from_ffi_handle();
|
||||
let pokemon = match Pokemon::deserialize(&library, &deserialized) {
|
||||
Ok(v) => v,
|
||||
Err(err) => return FFIResult::err(err),
|
||||
};
|
||||
FFIResult::ok(FFIHandle::get_handle(pokemon.into()))
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ mod static_data;
|
||||
pub(self) use ffi_handle::*;
|
||||
|
||||
/// Helper type for clearer functions.
|
||||
#[repr(C)]
|
||||
#[repr(transparent)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
struct OwnedPtrString(*mut c_char);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user