Created
July 6, 2020 16:39
-
-
Save hasenbanck/4a4f3d67117ccfb1acd9e0aade101f92 to your computer and use it in GitHub Desktop.
Simple `upsert` implementation for the rust ECS hecs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Trait to extend hecs to support upsert operations. | |
/// ```rust | |
/// use Upsert; | |
/// let mut world = hecs::World::new(); | |
/// struct s(u32); | |
/// | |
/// world.upsert(player_entity, |mut c| c.0 = 42, s(42))?; | |
/// ``` | |
pub trait Upsert { | |
fn upsert<F, T: 'static>(&mut self, entity: Entity, update: F, insert: T) -> Result<()> | |
where | |
T: Copy + Send + Sync, | |
F: FnOnce(RefMut<T>); | |
} | |
impl Upsert for hecs::World { | |
fn upsert<F, T: 'static>(&mut self, entity: Entity, update: F, insert: T) -> Result<()> | |
where | |
T: Copy + Send + Sync, | |
F: FnOnce(RefMut<T>), | |
{ | |
let present = if let Ok(c) = self.get_mut::<T>(entity) { | |
update(c); | |
true | |
} else { | |
false | |
}; | |
if !present { | |
self.insert(entity, (insert,))?; | |
} | |
Ok(()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment