Skip to content
34 changes: 30 additions & 4 deletions crates/bevy_core/src/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,26 +100,31 @@ impl std::fmt::Debug for Name {
/// for (name, mut score) in &mut scores {
/// score.0 += 1.0;
/// if score.0.is_nan() {
/// bevy_utils::tracing::error!("Score for {:?} is invalid", name);
/// // use the Display impl to return either the Name
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This kind of implementation information seems a bit too in-depth for an example. Additionally, the part about debug being more verbose is imo implicitly to be expected.

Suggestion: move this information outside of the example (maybe a section # Implementation?) and remove references to Debug

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, have updated the code if you could check its what you meant.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect, thanks :)

/// // where there is one, or {index}v{generation}
/// // for entities which don't have a Name.
/// // You can still use the Debug impl it is just quite verbose.
/// bevy_utils::tracing::error!("Score for {} is invalid", name);
/// }
/// }
/// }
/// # bevy_ecs::system::assert_is_system(increment_score);
/// ```
#[derive(QueryData)]
#[query_data(derive(Debug))]
pub struct DebugName {
/// A [`Name`] that the entity might have that is displayed if available.
pub name: Option<&'static Name>,
/// The unique identifier of the entity as a fallback.
pub entity: Entity,
}

impl<'a> std::fmt::Debug for DebugNameItem<'a> {
impl<'a> std::fmt::Display for DebugNameItem<'a> {
#[inline(always)]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self.name {
Some(name) => write!(f, "{:?} ({:?})", &name, &self.entity),
None => std::fmt::Debug::fmt(&self.entity, f),
Some(name) => std::fmt::Display::fmt(name, f),
None => write!(f, "{}v{}", self.entity.index(), self.entity.generation()),
}
}
}
Expand Down Expand Up @@ -198,3 +203,24 @@ impl Deref for Name {
self.name.as_ref()
}
}

#[cfg(test)]
mod tests {
use super::*;
use bevy_ecs::world::World;

#[test]
fn test_display_of_debug_name() {
let mut world = World::new();
let e1 = world.spawn_empty().id();
let name = Name::new("MyName");
let e2 = world.spawn(name.clone()).id();
let mut query = world.query::<DebugName>();
let d1 = query.get(&world, e1).unwrap();
let d2 = query.get(&world, e2).unwrap();
// DebugName Display for entities without a Name should be {index}v{generation}
assert_eq!(d1.to_string(), "0v1");
// DebugName Display for entiites with a Name should be the Name
assert_eq!(d2.to_string(), "MyName");
}
}