Implement Debug for UnsafeWorldCell (#9460)

# Objective

* Add more ways to use `UnsafeWorldCell` in safe code -- you no longer
need to call `.world_metadata()` to format it.
This commit is contained in:
Joseph 2023-08-20 18:00:12 -04:00 committed by GitHub
parent 140d9612e6
commit 69750a03ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 10 deletions

View File

@ -336,14 +336,15 @@ pub struct Query<'world, 'state, Q: WorldQuery, F: ReadOnlyWorldQuery = ()> {
force_read_only_component_access: bool,
}
impl<'w, 's, Q: WorldQuery, F: ReadOnlyWorldQuery> std::fmt::Debug for Query<'w, 's, Q, F> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f, "Query {{ matched entities: {}, world: {:?}, state: {:?}, last_run: {:?}, this_run: {:?} }}",
self.iter().count(),
// SAFETY: World's Debug implementation only accesses metadata.
unsafe { self.world.world_metadata() },
self.state, self.last_run, self.this_run)
impl<Q: WorldQuery, F: ReadOnlyWorldQuery> std::fmt::Debug for Query<'_, '_, Q, F> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Query")
.field("matched_entities", &self.iter().count())
.field("state", &self.state)
.field("last_run", &self.last_run)
.field("this_run", &self.this_run)
.field("world", &self.world)
.finish()
}
}

View File

@ -1867,7 +1867,9 @@ impl World {
}
impl fmt::Debug for World {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// SAFETY: `UnsafeWorldCell` requires that this must only access metadata.
// Accessing any data stored in the world would be unsound.
f.debug_struct("World")
.field("id", &self.id)
.field("entity_count", &self.entities.len())

View File

@ -16,7 +16,7 @@ use crate::{
system::Resource,
};
use bevy_ptr::Ptr;
use std::{any::TypeId, cell::UnsafeCell, marker::PhantomData};
use std::{any::TypeId, cell::UnsafeCell, fmt::Debug, marker::PhantomData};
/// Variant of the [`World`] where resource and component accesses take `&self`, and the responsibility to avoid
/// aliasing violations are given to the caller instead of being checked at compile-time by rust's unique XOR shared rule.
@ -560,6 +560,13 @@ impl<'w> UnsafeWorldCell<'w> {
}
}
impl Debug for UnsafeWorldCell<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
// SAFETY: World's Debug implementation only accesses metadata.
Debug::fmt(unsafe { self.world_metadata() }, f)
}
}
/// A interior-mutable reference to a particular [`Entity`] and all of its components
#[derive(Copy, Clone)]
pub struct UnsafeEntityCell<'w> {