Skip to content

Commit

Permalink
add a pop method to arrayvec (#963)
Browse files Browse the repository at this point in the history
* add a pop method to arrayvec

* rustfmt
  • Loading branch information
akuzni2 authored and dhaidashenko committed Dec 20, 2024
1 parent 1976211 commit df7ab9f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 4 deletions.
6 changes: 3 additions & 3 deletions contracts/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion contracts/crates/arrayvec/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "arrayvec"
version = "1.0.0"
version = "1.0.1"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
43 changes: 43 additions & 0 deletions contracts/crates/arrayvec/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,17 @@ macro_rules! arrayvec {
self.xs[offset..offset + len].copy_from_slice(&data);
self.len += len as $capacity_ty;
}

/// Removes the last element from the array and returns it.
/// Returns `None` if the array is empty.
pub fn pop(&mut self) -> Option<$ty> {
if self.len > 0 {
self.len -= 1;
Some(self.xs[self.len as usize])
} else {
None
}
}
}

impl std::ops::Deref for $name {
Expand Down Expand Up @@ -126,6 +137,38 @@ mod tests {
}
arrayvec!(ArrayVec, u8, u32);

#[test]
fn push_pop() {
let mut vec = ArrayVec::new();
assert!(vec.is_empty());
assert_eq!(vec.pop(), None);

vec.push(10);
assert_eq!(vec.len(), 1);
assert_eq!(vec.as_slice(), &[10]);

vec.push(20);
vec.push(30);
assert_eq!(vec.len(), 3);
assert_eq!(vec.as_slice(), &[10, 20, 30]);

// Popping elements
assert_eq!(vec.pop(), Some(30));
assert_eq!(vec.len(), 2);
assert_eq!(vec.as_slice(), &[10, 20]);

assert_eq!(vec.pop(), Some(20));
assert_eq!(vec.len(), 1);
assert_eq!(vec.as_slice(), &[10]);

assert_eq!(vec.pop(), Some(10));
assert_eq!(vec.len(), 0);
assert!(vec.is_empty());

// Popping from empty vec
assert_eq!(vec.pop(), None);
}

#[test]
fn remove() {
let mut vec = ArrayVec::new();
Expand Down

0 comments on commit df7ab9f

Please sign in to comment.