Trait specs::saveload::ConvertSaveload
source · pub trait ConvertSaveload<M>: Sized {
type Data: Serialize + DeserializeOwned;
type Error;
fn from<F>(data: Self::Data, ids: F) -> Result<Self, Self::Error>
where
F: FnMut(M) -> Option<Entity>;
fn into<F>(&self, ids: F) -> Result<Self::Data, Self::Error>
where
F: FnMut(Entity) -> Option<M>;
}
Expand description
Converts a data type (usually a Component
) into its serializable form
and back to actual data from it’s deserialized form.
This is automatically implemented for any type that is
Clone
, Serialize
and DeserializeOwned
.
Implementing this yourself is usually only needed if you
have a component that points to another Entity
, or has a field which does,
and you wish to Serialize
it.
Note: if you’re using specs_derive
you can use #[derive(Saveload)]
to automatically derive this.
You must add the derive
to any type that your component holds which does
not auto-implement this traits, including the component itself (similar to how
normal Serialize
and Deserialize
work).
Example
use serde::{Serialize, Deserialize};
use specs::prelude::*;
use specs::error::NoError;
use specs::saveload::{Marker, ConvertSaveload};
struct Target(Entity);
impl Component for Target {
type Storage = VecStorage<Self>;
}
// We need a matching "data" struct to hold our
// marker. In general, you just need a single struct
// per component you want to make `Serialize`/`Deserialize` with each
// instance of `Entity` replaced with a generic "M".
#[derive(Serialize, Deserialize)]
struct TargetData<M>(M);
impl<M: Marker + Serialize> ConvertSaveload<M> for Target
where for<'de> M: Deserialize<'de>,
{
type Data = TargetData<M>;
type Error = NoError;
fn into<F>(&self, mut ids: F) -> Result<Self::Data, Self::Error>
where
F: FnMut(Entity) -> Option<M>
{
let marker = ids(self.0).unwrap();
Ok(TargetData(marker))
}
fn from<F>(data: Self::Data, mut ids: F) -> Result<Self, Self::Error>
where
F: FnMut(M) -> Option<Entity>
{
let entity = ids(data.0).unwrap();
Ok(Target(entity))
}
}
Required Associated Types
sourcetype Data: Serialize + DeserializeOwned
type Data: Serialize + DeserializeOwned
(De)Serializable data representation for data type