Skip to main content

cranium_core/
entity_identifier.rs

1/* 
2This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. 
3If a copy of the MPL was not distributed with this file, 
4You can obtain one at https://mozilla.org/MPL/2.0/. 
5*/
6
7//! Wrapper for Entities to display them more nicely, mainly for logging purposes.
8
9use bevy::platform::prelude::{String};
10
11/// A convenient type wrapping Entity with an optional Name.
12/// Acts as either an Entity or a Name for Display purposes based on what it holds. 
13/// Otherwise acts as an Entity for any other purpose.
14#[derive(Debug, Clone)]
15pub enum EntityIdentifier {
16    Entity(bevy::prelude::Entity),
17    EntityAndName(bevy::prelude::Entity, String),
18}
19
20impl From<bevy::prelude::Entity> for EntityIdentifier {
21    fn from(value: bevy::prelude::Entity) -> Self {
22        Self::Entity(value)
23    }
24}
25
26impl From<(bevy::prelude::Entity, String)> for EntityIdentifier {
27    fn from(value: (bevy::prelude::Entity, String)) -> Self {
28        Self::EntityAndName(value.0, value.1)
29    }
30}
31
32impl Into<bevy::prelude::Entity> for EntityIdentifier {
33    fn into(self) -> bevy::prelude::Entity {
34        match self {
35            Self::Entity(e) => e,
36            Self::EntityAndName(e, _) => e,
37        }
38    }
39}
40
41impl core::ops::Deref for EntityIdentifier {
42    type Target = bevy::prelude::Entity;
43    
44    fn deref(&self) -> &Self::Target {
45        match self {
46            Self::Entity(e) => e,
47            Self::EntityAndName(e, _) => e,
48        }
49    }
50}
51
52impl core::fmt::Display for EntityIdentifier {
53    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
54        match self {
55            Self::Entity(e) => e.fmt(f),
56            Self::EntityAndName(_, s) => s.fmt(f)
57        }
58    }
59}
60
61impl core::hash::Hash for EntityIdentifier {
62    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
63        match self {
64            Self::Entity(e) => e.hash(state),
65            Self::EntityAndName(e, _) => e.hash(state)
66        }
67    }
68}
69
70impl PartialEq for EntityIdentifier {
71    fn eq(&self, other: &Self) -> bool {
72        match (self, other) {
73            (Self::Entity(l0), Self::Entity(r0)) => l0 == r0,
74            (Self::EntityAndName(l0, _), Self::EntityAndName(r0, _)) => l0 == r0,
75            _ => false,
76        }
77    }
78}
79
80impl Eq for EntityIdentifier {}