Skip to main content

bevy_ecs/
name.rs

1//! Provides the [`Name`] [`Component`], used for identifying an [`Entity`].
2
3use crate::{component::Component, entity::Entity, query::QueryData};
4
5use alloc::{
6    borrow::{Cow, ToOwned},
7    string::String,
8};
9use bevy_platform::hash::Hashed;
10use core::{
11    hash::{Hash, Hasher},
12    ops::Deref,
13};
14
15#[cfg(feature = "serialize")]
16use {
17    alloc::string::ToString,
18    serde::{
19        de::{Error, Visitor},
20        Deserialize, Deserializer, Serialize, Serializer,
21    },
22};
23
24#[cfg(feature = "bevy_reflect")]
25use {
26    crate::reflect::ReflectComponent,
27    bevy_reflect::{std_traits::ReflectDefault, Reflect},
28};
29
30#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
31use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
32
33/// Component used to identify an entity. Stores a hash for faster comparisons.
34///
35/// The hash is eagerly re-computed upon each update to the name.
36///
37/// [`Name`] should not be treated as a globally unique identifier for entities,
38/// as multiple entities can have the same name.  [`Entity`] should be
39/// used instead as the default unique identifier.
40#[derive(impl bevy_ecs::component::Component for Name where
    Self: ::core::marker::Send + ::core::marker::Sync + 'static {
    const STORAGE_TYPE: bevy_ecs::component::StorageType =
        bevy_ecs::component::StorageType::Table;
    type Mutability = bevy_ecs::component::Mutable;
    fn register_required_components(_requiree:
            bevy_ecs::component::ComponentId,
        required_components:
            &mut bevy_ecs::component::RequiredComponentsRegistrator) {}
    fn clone_behavior() -> bevy_ecs::component::ComponentCloneBehavior {
        use bevy_ecs::component::{
            DefaultCloneBehaviorBase, DefaultCloneBehaviorViaClone,
        };
        (&&&bevy_ecs::component::DefaultCloneBehaviorSpecialization::<Self>::default()).default_clone_behavior()
    }
    fn relationship_accessor()
        ->
            ::core::option::Option<bevy_ecs::relationship::ComponentRelationshipAccessor<Self>> {
        ::core::option::Option::None
    }
}Component, #[automatically_derived]impl ::core::clone::Clone for Name {
    #[inline]
    fn clone(&self) -> Self { Name(::core::clone::Clone::clone(&self.0)) }
}Clone)]
41#[cfg_attr(
42    feature = "bevy_reflect",
43    derive(const _: () =
    {
        impl bevy_reflect::GetTypeRegistration for Name where  {
            fn get_type_registration() -> bevy_reflect::TypeRegistration {
                let mut registration =
                    bevy_reflect::TypeRegistration::of::<Self>();
                registration.insert(<bevy_reflect::ReflectFromPtr as
                            bevy_reflect::CreateTypeData<Self>>::create_type_data(()));
                registration.insert(<bevy_reflect::ReflectFromReflect as
                            bevy_reflect::CreateTypeData<Self>>::create_type_data(()));
                registration.register_type_data_with::<ReflectComponent, Self,
                    _>(());
                registration.register_type_data_with::<ReflectDefault, Self,
                    _>(());
                registration.register_type_data_with::<ReflectDeserialize,
                    Self, _>(());
                registration.register_type_data_with::<ReflectSerialize, Self,
                    _>(());
                registration
            }
            #[inline(never)]
            fn register_type_dependencies(registry:
                    &mut bevy_reflect::TypeRegistry) {
                <HashedStr as
                        bevy_reflect::__macro_exports::RegisterForReflection>::__register(registry);
            }
        }
        impl bevy_reflect::Typed for Name where  {
            #[inline(never)]
            fn type_info() -> &'static bevy_reflect::TypeInfo {
                static CELL: bevy_reflect::utility::NonGenericTypeInfoCell =
                    bevy_reflect::utility::NonGenericTypeInfoCell::new();
                CELL.get_or_set(#[inline(never)] ||
                        {
                            bevy_reflect::TypeInfo::TupleStruct(bevy_reflect::tuple_struct::TupleStructInfo::new::<Self>(&[bevy_reflect::UnnamedField::new::<HashedStr>(0usize)]))
                        })
            }
        }
        #[allow(deprecated, reason =
        "derives on a deprecated type shouldn't be considered a usage")]
        impl bevy_reflect::TypePath for Name where  {
            fn type_path() -> &'static str { "bevy_ecs::name::Name" }
            fn short_type_path() -> &'static str { "Name" }
            fn type_ident() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("Name")
            }
            fn crate_name() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("bevy_ecs::name".split(':').next().unwrap())
            }
            fn module_path() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("bevy_ecs::name")
            }
        }
        impl bevy_reflect::Reflect for Name where  {
            #[inline]
            fn into_any(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn ::core::any::Any> {
                self
            }
            #[inline]
            fn as_any(&self) -> &dyn ::core::any::Any { self }
            #[inline]
            fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any { self }
            #[inline]
            fn into_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect> {
                self
            }
            #[inline]
            fn as_reflect(&self) -> &dyn bevy_reflect::Reflect { self }
            #[inline]
            fn as_reflect_mut(&mut self) -> &mut dyn bevy_reflect::Reflect {
                self
            }
            #[inline]
            fn set(&mut self,
                value:
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>)
                ->
                    ::core::result::Result<(),
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>> {
                *self = <dyn bevy_reflect::Reflect>::take(value)?;
                ::core::result::Result::Ok(())
            }
        }
        impl bevy_reflect::func::args::GetOwnership for Name where  {
            fn ownership() -> bevy_reflect::func::args::Ownership {
                bevy_reflect::func::args::Ownership::Owned
            }
        }
        impl bevy_reflect::func::args::FromArg for Name where  {
            type This<'from_arg> = Name;
            fn from_arg(arg: bevy_reflect::func::args::Arg)
                ->
                    ::core::result::Result<Self::This<'_>,
                    bevy_reflect::func::args::ArgError> {
                arg.take_owned()
            }
        }
        impl bevy_reflect::func::IntoReturn for Name where  {
            fn into_return<'into_return>(self)
                -> bevy_reflect::func::Return<'into_return> where
                Self: 'into_return {
                bevy_reflect::func::Return::Owned(bevy_reflect::__macro_exports::alloc_utils::Box::new(self))
            }
        }
        impl bevy_reflect::tuple_struct::TupleStruct for Name where  {
            fn field(&self, index: usize)
                -> ::core::option::Option<&dyn bevy_reflect::PartialReflect> {
                match index {
                    0usize => ::core::option::Option::Some(&self.0),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_mut(&mut self, index: usize)
                ->
                    ::core::option::Option<&mut dyn bevy_reflect::PartialReflect> {
                match index {
                    0usize => ::core::option::Option::Some(&mut self.0),
                    _ => ::core::option::Option::None,
                }
            }
            #[inline]
            fn field_len(&self) -> usize { 1usize }
            #[inline]
            fn iter_fields(&self)
                -> bevy_reflect::tuple_struct::TupleStructFieldIter {
                bevy_reflect::tuple_struct::TupleStructFieldIter::new(self)
            }
            fn to_dynamic_tuple_struct(&self)
                ->
                    ::core::result::Result<bevy_reflect::tuple_struct::DynamicTupleStruct,
                    bevy_reflect::ReflectCloneError> {
                let mut dynamic:
                        bevy_reflect::tuple_struct::DynamicTupleStruct =
                    ::core::default::Default::default();
                dynamic.set_represented_type(bevy_reflect::PartialReflect::get_represented_type_info(self));
                dynamic.insert_boxed(bevy_reflect::PartialReflect::to_dynamic(&self.0)?);
                ::core::result::Result::Ok(dynamic)
            }
        }
        impl bevy_reflect::PartialReflect for Name where  {
            #[inline]
            fn get_represented_type_info(&self)
                -> ::core::option::Option<&'static bevy_reflect::TypeInfo> {
                ::core::option::Option::Some(<Self as
                            bevy_reflect::Typed>::type_info())
            }
            #[inline]
            fn try_apply(&mut self, value: &dyn bevy_reflect::PartialReflect)
                -> ::core::result::Result<(), bevy_reflect::ApplyError> {
                if let bevy_reflect::ReflectRef::TupleStruct(struct_value) =
                        bevy_reflect::PartialReflect::reflect_ref(value) {
                    for (i, value) in
                        ::core::iter::Iterator::enumerate(bevy_reflect::tuple_struct::TupleStruct::iter_fields(struct_value))
                        {
                        if let ::core::option::Option::Some(v) =
                                bevy_reflect::tuple_struct::TupleStruct::field_mut(self, i)
                            {
                            bevy_reflect::PartialReflect::try_apply(v, value)?;
                        }
                    }
                } else {
                    return ::core::result::Result::Err(bevy_reflect::ApplyError::MismatchedKinds {
                                from_kind: bevy_reflect::PartialReflect::reflect_kind(value),
                                to_kind: bevy_reflect::ReflectKind::TupleStruct,
                            });
                }
                ::core::result::Result::Ok(())
            }
            #[inline]
            fn reflect_kind(&self) -> bevy_reflect::ReflectKind {
                bevy_reflect::ReflectKind::TupleStruct
            }
            #[inline]
            fn reflect_ref(&self) -> bevy_reflect::ReflectRef {
                bevy_reflect::ReflectRef::TupleStruct(self)
            }
            #[inline]
            fn reflect_mut(&mut self) -> bevy_reflect::ReflectMut {
                bevy_reflect::ReflectMut::TupleStruct(self)
            }
            #[inline]
            fn reflect_owned(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                -> bevy_reflect::ReflectOwned {
                bevy_reflect::ReflectOwned::TupleStruct(self)
            }
            #[inline]
            fn try_into_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    ::core::result::Result<bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>,
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::PartialReflect>> {
                ::core::result::Result::Ok(self)
            }
            #[inline]
            fn try_as_reflect(&self)
                -> ::core::option::Option<&dyn bevy_reflect::Reflect> {
                ::core::option::Option::Some(self)
            }
            #[inline]
            fn try_as_reflect_mut(&mut self)
                -> ::core::option::Option<&mut dyn bevy_reflect::Reflect> {
                ::core::option::Option::Some(self)
            }
            #[inline]
            fn into_partial_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::PartialReflect> {
                self
            }
            #[inline]
            fn as_partial_reflect(&self)
                -> &dyn bevy_reflect::PartialReflect {
                self
            }
            #[inline]
            fn as_partial_reflect_mut(&mut self)
                -> &mut dyn bevy_reflect::PartialReflect {
                self
            }
            fn reflect_hash(&self) -> ::core::option::Option<u64> {
                use ::core::hash::{Hash, Hasher};
                let mut hasher = bevy_reflect::utility::reflect_hasher();
                Hash::hash(&::core::any::Any::type_id(self), &mut hasher);
                Hash::hash(self, &mut hasher);
                ::core::option::Option::Some(Hasher::finish(&hasher))
            }
            fn reflect_partial_eq(&self,
                value: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<bool> {
                let value =
                    <dyn bevy_reflect::PartialReflect>::try_downcast_ref::<Self>(value);
                if let ::core::option::Option::Some(value) = value {
                    ::core::option::Option::Some(::core::cmp::PartialEq::eq(self,
                            value))
                } else { ::core::option::Option::Some(false) }
            }
            fn reflect_partial_cmp(&self,
                value: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<::core::cmp::Ordering> {
                (bevy_reflect::tuple_struct::tuple_struct_partial_cmp)(self,
                    value)
            }
            fn debug(&self, f: &mut ::core::fmt::Formatter<'_>)
                -> ::core::fmt::Result {
                ::core::fmt::Debug::fmt(self, f)
            }
            #[inline]
            fn reflect_clone(&self)
                ->
                    ::core::result::Result<bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>,
                    bevy_reflect::ReflectCloneError> {
                ::core::result::Result::Ok(bevy_reflect::__macro_exports::alloc_utils::Box::new(::core::clone::Clone::clone(self)))
            }
        }
        impl bevy_reflect::FromReflect for Name where  {
            fn from_reflect(reflect: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<Self> {
                if let bevy_reflect::ReflectRef::TupleStruct(__ref_struct) =
                        bevy_reflect::PartialReflect::reflect_ref(reflect) {
                    let mut __this =
                        <Self as ::core::default::Default>::default();
                    if let ::core::option::Option::Some(__field) =
                            (||
                                        <HashedStr as
                                                bevy_reflect::FromReflect>::from_reflect(bevy_reflect::tuple_struct::TupleStruct::field(__ref_struct,
                                                    0)?))() {
                        __this.0 = __field;
                    }
                    ::core::option::Option::Some(__this)
                } else { ::core::option::Option::None }
            }
        }
    };Reflect),
44    reflect(Component, Default, Debug, Clone, Hash, PartialEq)
45)]
46#[cfg_attr(
47    all(feature = "serialize", feature = "bevy_reflect"),
48    reflect(Deserialize, Serialize)
49)]
50pub struct Name(pub HashedStr);
51
52impl Default for Name {
53    fn default() -> Self {
54        Name::new("")
55    }
56}
57
58/// A wrapper over Hashed. This exists to make Name("value".into()) possible, which plays nicely with contexts like the `bsn!` macro.
59#[derive(#[automatically_derived]impl ::core::clone::Clone for HashedStr {
    #[inline]
    fn clone(&self) -> Self {
        HashedStr(::core::clone::Clone::clone(&self.0))
    }
}Clone)]
60#[cfg_attr(feature = "bevy_reflect", derive(const _: () =
    {
        impl bevy_reflect::GetTypeRegistration for HashedStr where  {
            fn get_type_registration() -> bevy_reflect::TypeRegistration {
                let mut registration =
                    bevy_reflect::TypeRegistration::of::<Self>();
                registration.insert(<bevy_reflect::ReflectFromPtr as
                            bevy_reflect::CreateTypeData<Self>>::create_type_data(()));
                registration.insert(<bevy_reflect::ReflectFromReflect as
                            bevy_reflect::CreateTypeData<Self>>::create_type_data(()));
                registration
            }
            #[inline(never)]
            fn register_type_dependencies(registry:
                    &mut bevy_reflect::TypeRegistry) {
                <Hashed<Cow<'static, str>> as
                        bevy_reflect::__macro_exports::RegisterForReflection>::__register(registry);
            }
        }
        impl bevy_reflect::Typed for HashedStr where  {
            #[inline(never)]
            fn type_info() -> &'static bevy_reflect::TypeInfo {
                static CELL: bevy_reflect::utility::NonGenericTypeInfoCell =
                    bevy_reflect::utility::NonGenericTypeInfoCell::new();
                CELL.get_or_set(#[inline(never)] ||
                        {
                            bevy_reflect::TypeInfo::TupleStruct(bevy_reflect::tuple_struct::TupleStructInfo::new::<Self>(&[bevy_reflect::UnnamedField::new::<Hashed<Cow<'static,
                                                        str>>>(0usize)]))
                        })
            }
        }
        #[allow(deprecated, reason =
        "derives on a deprecated type shouldn't be considered a usage")]
        impl bevy_reflect::TypePath for HashedStr where  {
            fn type_path() -> &'static str { "bevy_ecs::name::HashedStr" }
            fn short_type_path() -> &'static str { "HashedStr" }
            fn type_ident() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("HashedStr")
            }
            fn crate_name() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("bevy_ecs::name".split(':').next().unwrap())
            }
            fn module_path() -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some("bevy_ecs::name")
            }
        }
        impl bevy_reflect::Reflect for HashedStr where  {
            #[inline]
            fn into_any(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn ::core::any::Any> {
                self
            }
            #[inline]
            fn as_any(&self) -> &dyn ::core::any::Any { self }
            #[inline]
            fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any { self }
            #[inline]
            fn into_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect> {
                self
            }
            #[inline]
            fn as_reflect(&self) -> &dyn bevy_reflect::Reflect { self }
            #[inline]
            fn as_reflect_mut(&mut self) -> &mut dyn bevy_reflect::Reflect {
                self
            }
            #[inline]
            fn set(&mut self,
                value:
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>)
                ->
                    ::core::result::Result<(),
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>> {
                *self = <dyn bevy_reflect::Reflect>::take(value)?;
                ::core::result::Result::Ok(())
            }
        }
        impl bevy_reflect::func::args::GetOwnership for HashedStr where  {
            fn ownership() -> bevy_reflect::func::args::Ownership {
                bevy_reflect::func::args::Ownership::Owned
            }
        }
        impl bevy_reflect::func::args::FromArg for HashedStr where  {
            type This<'from_arg> = HashedStr;
            fn from_arg(arg: bevy_reflect::func::args::Arg)
                ->
                    ::core::result::Result<Self::This<'_>,
                    bevy_reflect::func::args::ArgError> {
                arg.take_owned()
            }
        }
        impl bevy_reflect::func::IntoReturn for HashedStr where  {
            fn into_return<'into_return>(self)
                -> bevy_reflect::func::Return<'into_return> where
                Self: 'into_return {
                bevy_reflect::func::Return::Owned(bevy_reflect::__macro_exports::alloc_utils::Box::new(self))
            }
        }
        impl bevy_reflect::tuple_struct::TupleStruct for HashedStr where  {
            fn field(&self, index: usize)
                -> ::core::option::Option<&dyn bevy_reflect::PartialReflect> {
                match index {
                    0usize => ::core::option::Option::Some(&self.0),
                    _ => ::core::option::Option::None,
                }
            }
            fn field_mut(&mut self, index: usize)
                ->
                    ::core::option::Option<&mut dyn bevy_reflect::PartialReflect> {
                match index {
                    0usize => ::core::option::Option::Some(&mut self.0),
                    _ => ::core::option::Option::None,
                }
            }
            #[inline]
            fn field_len(&self) -> usize { 1usize }
            #[inline]
            fn iter_fields(&self)
                -> bevy_reflect::tuple_struct::TupleStructFieldIter {
                bevy_reflect::tuple_struct::TupleStructFieldIter::new(self)
            }
            fn to_dynamic_tuple_struct(&self)
                ->
                    ::core::result::Result<bevy_reflect::tuple_struct::DynamicTupleStruct,
                    bevy_reflect::ReflectCloneError> {
                let mut dynamic:
                        bevy_reflect::tuple_struct::DynamicTupleStruct =
                    ::core::default::Default::default();
                dynamic.set_represented_type(bevy_reflect::PartialReflect::get_represented_type_info(self));
                dynamic.insert_boxed(bevy_reflect::PartialReflect::to_dynamic(&self.0)?);
                ::core::result::Result::Ok(dynamic)
            }
        }
        impl bevy_reflect::PartialReflect for HashedStr where  {
            #[inline]
            fn get_represented_type_info(&self)
                -> ::core::option::Option<&'static bevy_reflect::TypeInfo> {
                ::core::option::Option::Some(<Self as
                            bevy_reflect::Typed>::type_info())
            }
            #[inline]
            fn try_apply(&mut self, value: &dyn bevy_reflect::PartialReflect)
                -> ::core::result::Result<(), bevy_reflect::ApplyError> {
                if let bevy_reflect::ReflectRef::TupleStruct(struct_value) =
                        bevy_reflect::PartialReflect::reflect_ref(value) {
                    for (i, value) in
                        ::core::iter::Iterator::enumerate(bevy_reflect::tuple_struct::TupleStruct::iter_fields(struct_value))
                        {
                        if let ::core::option::Option::Some(v) =
                                bevy_reflect::tuple_struct::TupleStruct::field_mut(self, i)
                            {
                            bevy_reflect::PartialReflect::try_apply(v, value)?;
                        }
                    }
                } else {
                    return ::core::result::Result::Err(bevy_reflect::ApplyError::MismatchedKinds {
                                from_kind: bevy_reflect::PartialReflect::reflect_kind(value),
                                to_kind: bevy_reflect::ReflectKind::TupleStruct,
                            });
                }
                ::core::result::Result::Ok(())
            }
            #[inline]
            fn reflect_kind(&self) -> bevy_reflect::ReflectKind {
                bevy_reflect::ReflectKind::TupleStruct
            }
            #[inline]
            fn reflect_ref(&self) -> bevy_reflect::ReflectRef {
                bevy_reflect::ReflectRef::TupleStruct(self)
            }
            #[inline]
            fn reflect_mut(&mut self) -> bevy_reflect::ReflectMut {
                bevy_reflect::ReflectMut::TupleStruct(self)
            }
            #[inline]
            fn reflect_owned(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                -> bevy_reflect::ReflectOwned {
                bevy_reflect::ReflectOwned::TupleStruct(self)
            }
            #[inline]
            fn try_into_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    ::core::result::Result<bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>,
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::PartialReflect>> {
                ::core::result::Result::Ok(self)
            }
            #[inline]
            fn try_as_reflect(&self)
                -> ::core::option::Option<&dyn bevy_reflect::Reflect> {
                ::core::option::Option::Some(self)
            }
            #[inline]
            fn try_as_reflect_mut(&mut self)
                -> ::core::option::Option<&mut dyn bevy_reflect::Reflect> {
                ::core::option::Option::Some(self)
            }
            #[inline]
            fn into_partial_reflect(self:
                    bevy_reflect::__macro_exports::alloc_utils::Box<Self>)
                ->
                    bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::PartialReflect> {
                self
            }
            #[inline]
            fn as_partial_reflect(&self)
                -> &dyn bevy_reflect::PartialReflect {
                self
            }
            #[inline]
            fn as_partial_reflect_mut(&mut self)
                -> &mut dyn bevy_reflect::PartialReflect {
                self
            }
            fn reflect_partial_eq(&self,
                value: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<bool> {
                (bevy_reflect::tuple_struct::tuple_struct_partial_eq)(self,
                    value)
            }
            fn reflect_partial_cmp(&self,
                value: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<::core::cmp::Ordering> {
                (bevy_reflect::tuple_struct::tuple_struct_partial_cmp)(self,
                    value)
            }
            #[inline]
            #[allow(unreachable_code, reason =
            "Ignored fields without a `clone` attribute will early-return with an error")]
            fn reflect_clone(&self)
                ->
                    ::core::result::Result<bevy_reflect::__macro_exports::alloc_utils::Box<dyn bevy_reflect::Reflect>,
                    bevy_reflect::ReflectCloneError> {
                ::core::result::Result::Ok(bevy_reflect::__macro_exports::alloc_utils::Box::new(Self {
                            0: <Hashed<Cow<'static, str>> as
                                        bevy_reflect::PartialReflect>::reflect_clone_and_take(&self.0)?,
                        }))
            }
        }
        impl bevy_reflect::FromReflect for HashedStr where  {
            fn from_reflect(reflect: &dyn bevy_reflect::PartialReflect)
                -> ::core::option::Option<Self> {
                if let bevy_reflect::ReflectRef::TupleStruct(__ref_struct) =
                        bevy_reflect::PartialReflect::reflect_ref(reflect) {
                    let __this =
                        Self {
                            0: <Hashed<Cow<'static, str>> as
                                        bevy_reflect::FromReflect>::from_reflect(bevy_reflect::tuple_struct::TupleStruct::field(__ref_struct,
                                            0)?)?,
                        };
                    ::core::option::Option::Some(__this)
                } else { ::core::option::Option::None }
            }
        }
    };Reflect))]
61pub struct HashedStr(Hashed<Cow<'static, str>>);
62
63impl From<&'static str> for HashedStr {
64    fn from(value: &'static str) -> Self {
65        Self(Hashed::new(Cow::Borrowed(value)))
66    }
67}
68
69impl From<String> for HashedStr {
70    fn from(value: String) -> Self {
71        Self(Hashed::new(Cow::Owned(value)))
72    }
73}
74
75impl Name {
76    /// Creates a new [`Name`] from any string-like type.
77    ///
78    /// The internal hash will be computed immediately.
79    pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
80        Self(HashedStr(Hashed::new(name.into())))
81    }
82
83    /// Sets the entity's name.
84    ///
85    /// The internal hash will be re-computed.
86    #[inline(always)]
87    pub fn set(&mut self, name: impl Into<Cow<'static, str>>) {
88        *self = Name::new(name);
89    }
90
91    /// Updates the name of the entity in place.
92    ///
93    /// This will allocate a new string if the name was previously
94    /// created from a borrow.
95    #[inline(always)]
96    pub fn mutate(&mut self, func: impl FnOnce(&mut String)) {
97        self.0 .0.mutate(|cow_str| match cow_str {
98            Cow::Borrowed(borrowed) => {
99                let mut owned = borrowed.to_owned();
100                func(&mut owned);
101                *cow_str = Cow::Owned(owned);
102            }
103            Cow::Owned(owned) => {
104                func(owned);
105            }
106        });
107    }
108
109    /// Gets the name of the entity as a `&str`.
110    #[inline(always)]
111    pub fn as_str(&self) -> &str {
112        &self.0 .0
113    }
114    /// Get the precomputed hash of this names string, useful for raw entry operations on [`PreHashMap`](bevy_utils::PreHashMap)
115    #[inline(always)]
116    pub fn pre_hash(&self) -> u64 {
117        self.0 .0.hash()
118    }
119}
120
121impl core::fmt::Display for Name {
122    #[inline(always)]
123    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
124        core::fmt::Display::fmt(&*self.0 .0, f)
125    }
126}
127
128impl core::fmt::Debug for Name {
129    #[inline(always)]
130    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
131        core::fmt::Debug::fmt(&self.0 .0, f)
132    }
133}
134
135/// Convenient query for giving a human friendly name to an entity.
136///
137/// ```
138/// # use bevy_ecs::prelude::*;
139/// # #[derive(Component)] pub struct Score(f32);
140/// fn increment_score(mut scores: Query<(NameOrEntity, &mut Score)>) {
141///     for (name, mut score) in &mut scores {
142///         score.0 += 1.0;
143///         if score.0.is_nan() {
144///             log::error!("Score for {name} is invalid");
145///         }
146///     }
147/// }
148/// # bevy_ecs::system::assert_is_system(increment_score);
149/// ```
150///
151/// # Implementation
152///
153/// The `Display` impl for `NameOrEntity` returns the `Name` where there is one
154/// or {index}v{generation} for entities without one.
155#[derive(#[doc =
"Automatically generated [`WorldQuery`](bevy_ecs::query::WorldQuery) item type for [`NameOrEntity`], returned when iterating over query results."]
#[automatically_derived]
pub struct NameOrEntityItem<'__w, '__s> {
    #[doc =
    " A [`Name`] that the entity might have that is displayed if available."]
    pub name: <Option<&'static Name> as
    bevy_ecs::query::QueryData>::Item<'__w, '__s>,
    #[doc = " The unique identifier of the entity as a fallback."]
    pub entity: <Entity as bevy_ecs::query::QueryData>::Item<'__w, '__s>,
}
const _: () =
    {
        #[doc(hidden)]
        #[doc =
        "Automatically generated internal [`WorldQuery`](bevy_ecs::query::WorldQuery) state type for [`NameOrEntity`], used for caching."]
        #[automatically_derived]
        pub struct NameOrEntityState {
            fieldname: <Option<&'static Name> as
            bevy_ecs::query::WorldQuery>::State,
            fieldentity: <Entity as bevy_ecs::query::WorldQuery>::State,
        }
        #[doc(hidden)]
        #[doc =
        "Automatically generated internal [`WorldQuery`](bevy_ecs::query::WorldQuery) fetch type for [`NameOrEntity`], used to define the world data accessed by this query."]
        #[automatically_derived]
        pub struct NameOrEntityFetch<'__w> {
            fieldname: <Option<&'static Name> as
            bevy_ecs::query::WorldQuery>::Fetch<'__w>,
            fieldentity: <Entity as bevy_ecs::query::WorldQuery>::Fetch<'__w>,
            _world_query_derive_marker: &'__w (),
        }
        impl<'__w> ::core::clone::Clone for NameOrEntityFetch<'__w> {
            fn clone(&self) -> Self {
                Self {
                    fieldname: self.fieldname.clone(),
                    fieldentity: self.fieldentity.clone(),
                    _world_query_derive_marker: &(),
                }
            }
        }
        unsafe impl bevy_ecs::query::WorldQuery for NameOrEntity {
            type Fetch<'__w> = NameOrEntityFetch<'__w>;
            type State = NameOrEntityState;
            fn shrink_fetch<'__wlong: '__wshort,
                '__wshort>(fetch:
                    <NameOrEntity as
                    bevy_ecs::query::WorldQuery>::Fetch<'__wlong>)
                ->
                    <NameOrEntity as
                    bevy_ecs::query::WorldQuery>::Fetch<'__wshort> {
                NameOrEntityFetch {
                    fieldname: <Option<&'static Name>>::shrink_fetch(fetch.fieldname),
                    fieldentity: <Entity>::shrink_fetch(fetch.fieldentity),
                    _world_query_derive_marker: &(),
                }
            }
            unsafe fn init_fetch<'__w,
                '__s>(_world:
                    bevy_ecs::world::unsafe_world_cell::UnsafeWorldCell<'__w>,
                state: &'__s Self::State,
                _last_run: bevy_ecs::change_detection::Tick,
                _this_run: bevy_ecs::change_detection::Tick)
                -> <Self as bevy_ecs::query::WorldQuery>::Fetch<'__w> {
                NameOrEntityFetch {
                    fieldname: <Option<&'static Name>>::init_fetch(_world,
                        &state.fieldname, _last_run, _this_run),
                    fieldentity: <Entity>::init_fetch(_world,
                        &state.fieldentity, _last_run, _this_run),
                    _world_query_derive_marker: &(),
                }
            }
            const IS_DENSE: bool =
                true && <Option<&'static Name>>::IS_DENSE &&
                    <Entity>::IS_DENSE;
            #[doc =
            r" SAFETY: we call `set_archetype` for each member that implements `Fetch`"]
            #[inline]
            unsafe fn set_archetype<'__w,
                '__s>(_fetch:
                    &mut <Self as bevy_ecs::query::WorldQuery>::Fetch<'__w>,
                _state: &'__s Self::State,
                _archetype: &'__w bevy_ecs::archetype::Archetype,
                _table: &'__w bevy_ecs::storage::Table) {
                <Option<&'static Name>>::set_archetype(&mut _fetch.fieldname,
                    &_state.fieldname, _archetype, _table);
                <Entity>::set_archetype(&mut _fetch.fieldentity,
                    &_state.fieldentity, _archetype, _table);
            }
            #[doc =
            r" SAFETY: we call `set_table` for each member that implements `Fetch`"]
            #[inline]
            unsafe fn set_table<'__w,
                '__s>(_fetch:
                    &mut <Self as bevy_ecs::query::WorldQuery>::Fetch<'__w>,
                _state: &'__s Self::State,
                _table: &'__w bevy_ecs::storage::Table) {
                <Option<&'static Name>>::set_table(&mut _fetch.fieldname,
                    &_state.fieldname, _table);
                <Entity>::set_table(&mut _fetch.fieldentity,
                    &_state.fieldentity, _table);
            }
            fn update_component_access(state: &Self::State,
                _access: &mut bevy_ecs::query::FilteredAccess) {
                <Option<&'static Name>>::update_component_access(&state.fieldname,
                    _access);
                <Entity>::update_component_access(&state.fieldentity,
                    _access);
            }
            fn init_nested_access(state: &Self::State,
                _system_name: ::core::option::Option<&str>,
                _component_access_set:
                    &mut bevy_ecs::query::FilteredAccessSet,
                _world: bevy_ecs::world::unsafe_world_cell::UnsafeWorldCell) {
                <Option<&'static Name>>::init_nested_access(&state.fieldname,
                    _system_name, _component_access_set, _world);
                <Entity>::init_nested_access(&state.fieldentity, _system_name,
                    _component_access_set, _world);
            }
            fn init_state(world: &mut bevy_ecs::world::World)
                -> NameOrEntityState {
                NameOrEntityState {
                    fieldname: <Option<&'static Name>>::init_state(world),
                    fieldentity: <Entity>::init_state(world),
                }
            }
            fn get_state(components: &bevy_ecs::component::Components)
                -> ::core::option::Option<NameOrEntityState> {
                ::core::option::Option::Some(NameOrEntityState {
                        fieldname: <Option<&'static Name>>::get_state(components)?,
                        fieldentity: <Entity>::get_state(components)?,
                    })
            }
            fn matches_component_set(state: &Self::State,
                _set_contains_id:
                    &impl ::core::ops::Fn(bevy_ecs::component::ComponentId)
                    -> bool) -> bool {
                true &&
                        <Option<&'static Name>>::matches_component_set(&state.fieldname,
                            _set_contains_id) &&
                    <Entity>::matches_component_set(&state.fieldentity,
                        _set_contains_id)
            }
            fn update_archetypes(_state: &mut Self::State,
                _world: bevy_ecs::world::unsafe_world_cell::UnsafeWorldCell) {
                <Option<&'static Name>>::update_archetypes(&mut _state.fieldname,
                    _world);
                <Entity>::update_archetypes(&mut _state.fieldentity, _world);
            }
        }
        unsafe impl bevy_ecs::query::QueryData for NameOrEntity {
            const IS_READ_ONLY: bool = true;
            const IS_ARCHETYPAL: bool =
                true &&
                        <Option<&'static Name> as
                            bevy_ecs::query::QueryData>::IS_ARCHETYPAL &&
                    <Entity as bevy_ecs::query::QueryData>::IS_ARCHETYPAL;
            type ReadOnly = NameOrEntity;
            type Item<'__w, '__s> = NameOrEntityItem<'__w, '__s>;
            fn shrink<'__wlong: '__wshort, '__wshort,
                '__s>(item: Self::Item<'__wlong, '__s>)
                -> Self::Item<'__wshort, '__s> {
                NameOrEntityItem {
                    name: <Option<&'static Name>>::shrink(item.name),
                    entity: <Entity>::shrink(item.entity),
                }
            }
            fn provide_extra_access(state: &mut Self::State,
                access: &mut bevy_ecs::query::Access,
                available_access: &bevy_ecs::query::Access) {
                <Option<&'static Name>>::provide_extra_access(&mut state.fieldname,
                    access, available_access);
                <Entity>::provide_extra_access(&mut state.fieldentity, access,
                    available_access);
            }
            #[doc =
            r" SAFETY: we call `fetch` for each member that implements `Fetch`."]
            #[inline(always)]
            unsafe fn fetch<'__w,
                '__s>(_state: &'__s Self::State,
                _fetch:
                    &mut <Self as bevy_ecs::query::WorldQuery>::Fetch<'__w>,
                _entity: bevy_ecs::entity::Entity,
                _table_row: bevy_ecs::storage::TableRow)
                -> ::core::option::Option<Self::Item<'__w, '__s>> {
                ::core::option::Option::Some(Self::Item {
                        name: <Option<&'static Name>>::fetch(&_state.fieldname,
                                &mut _fetch.fieldname, _entity, _table_row)?,
                        entity: <Entity>::fetch(&_state.fieldentity,
                                &mut _fetch.fieldentity, _entity, _table_row)?,
                    })
            }
            fn iter_access(_state: &Self::State)
                ->
                    impl ::core::iter::Iterator<Item =
                    bevy_ecs::query::EcsAccessType<'_>> {
                ::core::iter::empty().chain(<Option<&'static Name>>::iter_access(&_state.fieldname)).chain(<Entity>::iter_access(&_state.fieldentity))
            }
        }
        unsafe impl bevy_ecs::query::IterQueryData for NameOrEntity where
            for<'__a> Option<&'static Name>: bevy_ecs::query::IterQueryData,
            for<'__a> Entity: bevy_ecs::query::IterQueryData {}
        unsafe impl bevy_ecs::query::SingleEntityQueryData for NameOrEntity
            where
            for<'__a> Option<&'static Name>: bevy_ecs::query::SingleEntityQueryData,
            for<'__a> Entity: bevy_ecs::query::SingleEntityQueryData {}
        impl bevy_ecs::query::ReleaseStateQueryData for NameOrEntity where
            for<'__a> Option<&'static Name>: bevy_ecs::query::ReleaseStateQueryData,
            for<'__a> Entity: bevy_ecs::query::ReleaseStateQueryData {
            fn release_state<'__w>(_item: Self::Item<'__w, '_>)
                -> Self::Item<'__w, 'static> {
                Self::Item {
                    name: <Option<&'static Name>>::release_state(_item.name),
                    entity: <Entity>::release_state(_item.entity),
                }
            }
        }
        impl bevy_ecs::query::ArchetypeQueryData for NameOrEntity where
            for<'__a> Option<&'static Name>: bevy_ecs::query::ArchetypeQueryData,
            for<'__a> Entity: bevy_ecs::query::ArchetypeQueryData {}
        unsafe impl bevy_ecs::query::ReadOnlyQueryData for NameOrEntity {}
    };
#[allow(dead_code)]
const _: () =
    {
        fn assert_readonly<T>() where T: bevy_ecs::query::ReadOnlyQueryData {}
        fn assert_data<T>() where T: bevy_ecs::query::QueryData {}
        fn assert_all<'__w>() {
            assert_readonly::<Option<&'static Name>>();
            assert_readonly::<Entity>();
            assert_data::<Option<&'static Name>>();
            assert_data::<Entity>();
        }
    };
#[allow(dead_code)]
const _: () =
    {
        fn dead_code_workaround(q: NameOrEntity, q2: NameOrEntity) {
            q.name;
            q.entity;
            q2.name;
            q2.entity;
        }
    };QueryData)]
156#[query_data(derive(#[automatically_derived]impl<'__w, '__s> ::core::fmt::Debug for
    NameOrEntityItem<'__w, '__s> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "NameOrEntityItem", "name", &self.name, "entity", &&self.entity)
    }
}Debug))]
157pub struct NameOrEntity {
158    /// A [`Name`] that the entity might have that is displayed if available.
159    pub name: Option<&'static Name>,
160    /// The unique identifier of the entity as a fallback.
161    pub entity: Entity,
162}
163
164impl<'w, 's> core::fmt::Display for NameOrEntityItem<'w, 's> {
165    #[inline(always)]
166    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
167        match self.name {
168            Some(name) => core::fmt::Display::fmt(name, f),
169            None => core::fmt::Display::fmt(&self.entity, f),
170        }
171    }
172}
173
174// Conversions from strings
175
176impl From<&'static str> for Name {
177    #[inline(always)]
178    fn from(name: &'static str) -> Self {
179        Name::new(name)
180    }
181}
182
183impl From<String> for Name {
184    #[inline(always)]
185    fn from(name: String) -> Self {
186        Name::new(name)
187    }
188}
189
190// Conversions to strings
191
192impl AsRef<str> for Name {
193    #[inline(always)]
194    fn as_ref(&self) -> &str {
195        &self.0 .0
196    }
197}
198
199impl From<&Name> for String {
200    #[inline(always)]
201    fn from(val: &Name) -> String {
202        val.as_str().to_owned()
203    }
204}
205
206impl From<Name> for String {
207    #[inline(always)]
208    fn from(val: Name) -> String {
209        val.as_str().to_owned()
210    }
211}
212
213impl Hash for Name {
214    fn hash<H: Hasher>(&self, state: &mut H) {
215        Hash::hash(&self.0 .0, state);
216    }
217}
218
219impl PartialEq for Name {
220    fn eq(&self, other: &Self) -> bool {
221        if self.0 .0.hash() != other.0 .0.hash() {
222            // Makes the common case of two strings not been equal very fast
223            return false;
224        }
225
226        self.0 .0.eq(&other.0 .0)
227    }
228}
229
230impl Eq for Name {}
231
232impl PartialOrd for Name {
233    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
234        Some(self.cmp(other))
235    }
236}
237
238impl Ord for Name {
239    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
240        self.0 .0.cmp(&other.0 .0)
241    }
242}
243
244impl Deref for Name {
245    type Target = str;
246
247    fn deref(&self) -> &Self::Target {
248        self.as_str()
249    }
250}
251
252#[cfg(feature = "serialize")]
253impl Serialize for Name {
254    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
255        serializer.serialize_str(self.as_str())
256    }
257}
258
259#[cfg(feature = "serialize")]
260impl<'de> Deserialize<'de> for Name {
261    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
262        deserializer.deserialize_str(NameVisitor)
263    }
264}
265
266#[cfg(feature = "serialize")]
267struct NameVisitor;
268
269#[cfg(feature = "serialize")]
270impl<'de> Visitor<'de> for NameVisitor {
271    type Value = Name;
272
273    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
274        formatter.write_str(core::any::type_name::<Name>())
275    }
276
277    fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
278        Ok(Name::new(v.to_string()))
279    }
280
281    fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> {
282        Ok(Name::new(v))
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289    use crate::world::World;
290    use alloc::string::ToString;
291    use bevy_platform::hash::fixed_hash_one;
292
293    #[test]
294    fn test_display_of_debug_name() {
295        let mut world = World::new();
296        let e1 = world.spawn_empty().id();
297        let name = Name::new("MyName");
298        let e2 = world.spawn(name.clone()).id();
299        let mut query = world.query::<NameOrEntity>();
300        let d1 = query.get(&world, e1).unwrap();
301        // NameOrEntity Display for entities without a Name should be {index}v{generation}
302        assert_eq!(d1.to_string(), "1v0");
303        let d2 = query.get(&world, e2).unwrap();
304        // NameOrEntity Display for entities with a Name should be the Name
305        assert_eq!(d2.to_string(), "MyName");
306    }
307    #[test]
308    fn test_name_hash_is_fixed() {
309        let str = "foobar";
310        assert_eq!(Name::from(str).pre_hash(), fixed_hash_one(str));
311    }
312}
313
314#[cfg(all(test, feature = "serialize"))]
315mod serde_tests {
316    use super::Name;
317
318    use serde_test::{assert_tokens, Token};
319
320    #[test]
321    fn test_serde_name() {
322        let name = Name::new("MyComponent");
323        assert_tokens(&name, &[Token::String("MyComponent")]);
324    }
325}