Skip to content

Commit

Permalink
Merge pull request #32 from pendulum-chain/spacewalk/544-change-check…
Browse files Browse the repository at this point in the history
…s-for-unknown-validators-in-stellar-relay-pallet

Add `pop` and `get_element` functions for `LimitedVarArray`
  • Loading branch information
b-yap authored Aug 5, 2024
2 parents 22bd78d + d69bae5 commit 9b8e2b7
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/xdr/compound_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,18 @@ impl<T, const N: i32> LimitedVarArray<T, N> {
&self.0
}

/// Searches for an element in the array that satisfies the predicate.
///
/// # Arguments
///
/// * `predicate` - a closure that applies to each element of the array.
/// Returns `true` if any of them return `true`, then get_element() returns Some(element)
/// If they all return `false`, `get_element()` returns None.
pub fn get_element<P>(&self, mut predicate:P) -> Option<&T>
where P: FnMut(&T) -> bool {
self.0.iter().find(|elem| predicate(elem))
}

pub fn len(&self) -> usize {
self.0.len()
}
Expand All @@ -175,6 +187,12 @@ impl<T, const N: i32> LimitedVarArray<T, N> {
self.0.push(item);
Ok(())
}

/// Removes an element from the end of the array and returns it, or `None` if it is empty.
pub fn pop(&mut self) -> Option<T> {
self.0.pop()
}

}

impl<T: XdrCodec, const N: i32> XdrCodec for LimitedVarArray<T, N> {
Expand Down Expand Up @@ -295,4 +313,16 @@ mod tests {
);
assert_eq!(XdrArchive::<LimitedVarArray<Price, 10>>::from_xdr(encoded).unwrap(), xdr_archive)
}

#[test]
fn pop_and_find_limited_array() {
let sample_vec = vec![0,1,2,3,4];
let mut sample_limited_array = LimitedVarArray::<u8,5>::new(sample_vec).expect("should return just fine");
let len = sample_limited_array.len();
let popped = sample_limited_array.pop();
assert_eq!(popped, Some(4));
assert_ne!(sample_limited_array.len(), len);

assert!(sample_limited_array.get_element(|elem| *elem == 2).is_some());
}
}

0 comments on commit 9b8e2b7

Please sign in to comment.