Skip to content

Instantly share code, notes, and snippets.

@hasenbanck
Created July 6, 2020 16:39
Show Gist options
  • Save hasenbanck/4a4f3d67117ccfb1acd9e0aade101f92 to your computer and use it in GitHub Desktop.
Save hasenbanck/4a4f3d67117ccfb1acd9e0aade101f92 to your computer and use it in GitHub Desktop.
Simple `upsert` implementation for the rust ECS hecs
/// 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