From bb2303a654c08fd295828b3b12e1cfb6daddbc28 Mon Sep 17 00:00:00 2001 From: Nathan Ward Date: Tue, 30 Aug 2022 21:06:32 +0000 Subject: [PATCH] Add `pop` method for `List` trait. (#5797) # Objective - The reflection `List` trait does not have a `pop` function. - Popping elements off a list is a common use case and is almost always supported by `List`-like types. ## Solution - Add the `pop()` method to the `List` trait and add the appropriate implementations of this function. ## Migration Guide - Any custom type that implements the `List` trait will now need to implement the `pop` method. Co-authored-by: Carter Anderson --- crates/bevy_reflect/src/impls/smallvec.rs | 4 ++++ crates/bevy_reflect/src/impls/std.rs | 4 ++++ crates/bevy_reflect/src/list.rs | 7 +++++++ 3 files changed, 15 insertions(+) diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index 918f74d40c..11f3c80012 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -54,6 +54,10 @@ where }); SmallVec::push(self, value); } + + fn pop(&mut self) -> Option> { + self.pop().map(|value| Box::new(value) as Box) + } } impl Reflect for SmallVec diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index b79858d16c..5c48fbabca 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -137,6 +137,10 @@ impl List for Vec { }); Vec::push(self, value); } + + fn pop(&mut self) -> Option> { + self.pop().map(|value| Box::new(value) as Box) + } } impl Reflect for Vec { diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 9e8c0c65f6..26c8840c7f 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -15,6 +15,9 @@ pub trait List: Reflect + Array { /// Appends an element to the list. fn push(&mut self, value: Box); + /// Removes the last element from the list (highest index in the array) and returns it, or [`None`] if it is empty. + fn pop(&mut self) -> Option>; + /// Clones the list, producing a [`DynamicList`]. fn clone_dynamic(&self) -> DynamicList { DynamicList { @@ -151,6 +154,10 @@ impl List for DynamicList { DynamicList::push_box(self, value); } + fn pop(&mut self) -> Option> { + self.values.pop() + } + fn clone_dynamic(&self) -> DynamicList { DynamicList { name: self.name.clone(),