Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pop and get_element functions for LimitedVarArray #32

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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());
}
}
Loading