bevy/crates/bevy_ecs/src/entity/serde.rs
David Sugar 8a8293b266 Renamed Entity::new to Entity::from_raw (#3465)
# Objective

- Rename `Entity::new(id: u32)` to `Entity::from_raw(id: u32)`.
- Add further documentation.
- fixes #3108

## Solution

- Renamed `Entity::new(id: u32)` to `Entity::from_raw(id: u32)`.
- Docs extended.

I derived the examples from the discussion of issue #3108 .

The [first case](https://github.com/bevyengine/bevy/issues/3108#issuecomment-966669781) mentioned in the linked issue is quite obvious but the [second one](https://github.com/bevyengine/bevy/issues/3108#issuecomment-967093902) probably needs further explanation.


Co-authored-by: r4gus <david@thesugar.de>
2021-12-29 20:49:00 +00:00

37 lines
872 B
Rust

use crate::entity::Entity;
use serde::{de::Visitor, Deserialize, Serialize, Serializer};
impl Serialize for Entity {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.id())
}
}
impl<'de> Deserialize<'de> for Entity {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_u32(EntityVisitor)
}
}
struct EntityVisitor;
impl<'de> Visitor<'de> for EntityVisitor {
type Value = Entity;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("expected Entity")
}
fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(Entity::from_raw(v))
}
}