bevy_ecs/system/
system_name.rs1use crate::{
2 component::Tick,
3 prelude::World,
4 system::{ExclusiveSystemParam, ReadOnlySystemParam, SystemMeta, SystemParam},
5 world::unsafe_world_cell::UnsafeWorldCell,
6};
7use alloc::borrow::Cow;
8use core::ops::Deref;
9use derive_more::derive::{AsRef, Display, Into};
10
11#[derive(Debug, Into, Display, AsRef)]
38#[as_ref(str)]
39pub struct SystemName<'s>(&'s str);
40
41impl<'s> SystemName<'s> {
42 pub fn name(&self) -> &str {
44 self.0
45 }
46}
47
48impl<'s> Deref for SystemName<'s> {
49 type Target = str;
50 fn deref(&self) -> &Self::Target {
51 self.name()
52 }
53}
54
55unsafe impl SystemParam for SystemName<'_> {
57 type State = Cow<'static, str>;
58 type Item<'w, 's> = SystemName<'s>;
59
60 fn init_state(_world: &mut World, system_meta: &mut SystemMeta) -> Self::State {
61 system_meta.name.clone()
62 }
63
64 #[inline]
65 unsafe fn get_param<'w, 's>(
66 name: &'s mut Self::State,
67 _system_meta: &SystemMeta,
68 _world: UnsafeWorldCell<'w>,
69 _change_tick: Tick,
70 ) -> Self::Item<'w, 's> {
71 SystemName(name)
72 }
73}
74
75unsafe impl<'s> ReadOnlySystemParam for SystemName<'s> {}
77
78impl ExclusiveSystemParam for SystemName<'_> {
79 type State = Cow<'static, str>;
80 type Item<'s> = SystemName<'s>;
81
82 fn init(_world: &mut World, system_meta: &mut SystemMeta) -> Self::State {
83 system_meta.name.clone()
84 }
85
86 fn get_param<'s>(state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> {
87 SystemName(state)
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use crate::{
94 system::{IntoSystem, RunSystemOnce, SystemName},
95 world::World,
96 };
97 use alloc::{borrow::ToOwned, string::String};
98
99 #[test]
100 fn test_system_name_regular_param() {
101 fn testing(name: SystemName) -> String {
102 name.name().to_owned()
103 }
104
105 let mut world = World::default();
106 let id = world.register_system(testing);
107 let name = world.run_system(id).unwrap();
108 assert!(name.ends_with("testing"));
109 }
110
111 #[test]
112 fn test_system_name_exclusive_param() {
113 fn testing(_world: &mut World, name: SystemName) -> String {
114 name.name().to_owned()
115 }
116
117 let mut world = World::default();
118 let id = world.register_system(testing);
119 let name = world.run_system(id).unwrap();
120 assert!(name.ends_with("testing"));
121 }
122
123 #[test]
124 fn test_closure_system_name_regular_param() {
125 let mut world = World::default();
126 let system =
127 IntoSystem::into_system(|name: SystemName| name.name().to_owned()).with_name("testing");
128 let name = world.run_system_once(system).unwrap();
129 assert_eq!(name, "testing");
130 }
131
132 #[test]
133 fn test_exclusive_closure_system_name_regular_param() {
134 let mut world = World::default();
135 let system =
136 IntoSystem::into_system(|_world: &mut World, name: SystemName| name.name().to_owned())
137 .with_name("testing");
138 let name = world.run_system_once(system).unwrap();
139 assert_eq!(name, "testing");
140 }
141}