pub trait ConvertSaveload<M>: Sized {
    type Data: Serialize + DeserializeOwned;
    type Error;

    fn convert_from<F>(data: Self::Data, ids: F) -> Result<Self, Self::Error>
    where
        F: FnMut(M) -> Option<Entity>
; fn convert_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::{Deserialize, Serialize};
use specs::{
    prelude::*,
    saveload::{ConvertSaveload, Marker},
};
use std::convert::Infallible;

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 = Infallible;

    fn convert_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 convert_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

(De)Serializable data representation for data type

Error may occur during serialization or deserialization of component

Required Methods

Convert this data from a deserializable form (Data) using entity to marker mapping function

Convert this data type into serializable form (Data) using entity to marker mapping function

Implementors