From bc3b3f5394e90e983e2a72afdd9427cdfcdfbb78 Mon Sep 17 00:00:00 2001 From: copygirl Date: Thu, 26 Sep 2024 23:53:36 +0200 Subject: [PATCH] impl Debug for Component --- src/ecs/component.rs | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/ecs/component.rs b/src/ecs/component.rs index c309a62..1b56262 100644 --- a/src/ecs/component.rs +++ b/src/ecs/component.rs @@ -95,8 +95,25 @@ impl std::hash::Hash for Component { } } +impl std::fmt::Debug for Component { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.is_entity() { + use super::entity::Entity; + unsafe { Entity::from_bits_unchecked(self.to_bits()).fmt(f) } + } else if self.is_relation() { + use super::relation::Relation; + unsafe { Relation::from_bits_unchecked(self.to_bits()).fmt(f) } + } else { + f.debug_struct("Component") + .field("low", &self.low) + .field("high", &self.high) + .finish() + } + } +} + impl Flags { - // NOTE: When changing this be sure to update documentation below. + // NOTE: When changing this be sure to update documentation. pub(crate) const MASK: u32 = 0xF0000000; /// Extracts only the flags from the specified `u32`. @@ -162,4 +179,27 @@ mod tests { let back_to_relation: Relation = component.try_into().unwrap(); assert_eq!(relation, back_to_relation); } + + #[test] + fn debug() { + // Component, as long as it's a valid Entity or Relation, will format as such. + // In cases where it's neither (not a valid Component), it has a default formatting. + + let entity: Component = Entity::new_checked(69, 1337).unwrap().into(); + let relation: Component = Relation::new_checked(420, 9001).unwrap().into(); + let invalid = unsafe { Component::from_bits_unchecked(0x20000000_00000001) }; + + assert_eq!( + "Entity { id: 69, gen: Generation(1337) }", + format!("{entity:?}") + ); + assert_eq!( + "Relation { target: 9001, kind: 420 }", + format!("{relation:?}") + ); + assert_eq!( + "Component { low: 1, high: 536870912 }", + format!("{invalid:?}") + ); + } }