Skip to content

Commit e511dda

Browse files
bitzoicJoshuaBatty
andauthored
Add last() to Vec (#6870)
## Description `last()` is not implemented for `Vec`. ## Checklist - [x] I have linked to any relevant issues. - [x] I have commented my code, particularly in hard-to-understand areas. - [x] I have updated the documentation where relevant (API docs, the reference, and the Sway book). - [x] If my change requires substantial documentation changes, I have [requested support from the DevRel team](https://github.com/FuelLabs/devrel-requests/issues/new/choose) - [x] I have added tests that prove my fix is effective or that my feature works. - [x] I have added (or requested a maintainer to add) the necessary `Breaking*` or `New Feature` labels where relevant. - [x] I have done my best to ensure that my PR adheres to [the Fuel Labs Code Review Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md). - [x] I have requested a review from the relevant team or maintainers. Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
1 parent 1762714 commit e511dda

File tree

2 files changed

+44
-0
lines changed
  • sway-lib-std/src
  • test/src/in_language_tests/test_programs/vec_inline_tests/src

2 files changed

+44
-0
lines changed

sway-lib-std/src/vec.sw

+26
Original file line numberDiff line numberDiff line change
@@ -753,6 +753,32 @@ impl<T> Vec<T> {
753753

754754
self.len = new_len;
755755
}
756+
757+
/// Returns the last element in the `Vec`.
758+
///
759+
/// # Returns
760+
///
761+
/// [Option<T>] - The last element in the `Vec` or `None`.
762+
///
763+
/// # Examples
764+
///
765+
/// ```sway
766+
/// fn foo() {
767+
/// let mut vec = Vec::new();
768+
/// assert(vec.last() == None);
769+
/// vec.push(1u64);
770+
/// assert(vec.last() == Some(1u64));
771+
/// vec.push(2u64);
772+
/// assert(vec.last() == Some(2u64));
773+
/// }
774+
/// ```
775+
pub fn last(self) -> Option<T> {
776+
if self.len == 0 {
777+
return None;
778+
}
779+
780+
Some(self.buf.ptr().add::<T>(self.len - 1).read::<T>())
781+
}
756782
}
757783

758784
impl<T> AsRawSlice for Vec<T> {

test/src/in_language_tests/test_programs/vec_inline_tests/src/main.sw

+18
Original file line numberDiff line numberDiff line change
@@ -805,3 +805,21 @@ fn vec_resize() {
805805
assert(vec_2.get(1) == Some(1));
806806
assert(vec_2.get(2) == Some(1));
807807
}
808+
809+
#[test]
810+
fn vec_last() {
811+
let (mut vec_1, a, b, c) = setup();
812+
assert(vec_1.last() == Some(9));
813+
814+
vec_1.push(2);
815+
assert(vec_1.last() == Some(2));
816+
817+
vec_1.push(3);
818+
assert(vec_1.last() == Some(3));
819+
820+
let _ = vec_1.pop();
821+
assert(vec_1.last() == Some(2));
822+
823+
let vec_2: Vec<u64> = Vec::new();
824+
assert(vec_2.last() == None)
825+
}

0 commit comments

Comments
 (0)