Skip to content

Commit

Permalink
Add last() to Vec (#6870)
Browse files Browse the repository at this point in the history
## 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 <[email protected]>
  • Loading branch information
bitzoic and JoshuaBatty authored Jan 30, 2025
1 parent 1762714 commit e511dda
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
26 changes: 26 additions & 0 deletions sway-lib-std/src/vec.sw
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,32 @@ impl<T> Vec<T> {

self.len = new_len;
}

/// Returns the last element in the `Vec`.
///
/// # Returns
///
/// [Option<T>] - The last element in the `Vec` or `None`.
///
/// # Examples
///
/// ```sway
/// fn foo() {
/// let mut vec = Vec::new();
/// assert(vec.last() == None);
/// vec.push(1u64);
/// assert(vec.last() == Some(1u64));
/// vec.push(2u64);
/// assert(vec.last() == Some(2u64));
/// }
/// ```
pub fn last(self) -> Option<T> {
if self.len == 0 {
return None;
}

Some(self.buf.ptr().add::<T>(self.len - 1).read::<T>())
}
}

impl<T> AsRawSlice for Vec<T> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -805,3 +805,21 @@ fn vec_resize() {
assert(vec_2.get(1) == Some(1));
assert(vec_2.get(2) == Some(1));
}

#[test]
fn vec_last() {
let (mut vec_1, a, b, c) = setup();
assert(vec_1.last() == Some(9));

vec_1.push(2);
assert(vec_1.last() == Some(2));

vec_1.push(3);
assert(vec_1.last() == Some(3));

let _ = vec_1.pop();
assert(vec_1.last() == Some(2));

let vec_2: Vec<u64> = Vec::new();
assert(vec_2.last() == None)
}

0 comments on commit e511dda

Please sign in to comment.