Skip to content

Commit 2d73d09

Browse files
authored
AbiDecode for Vec using with_capacity (#5849)
## Description This PR uses the fact that we know the final length of the `Vec`, and creates it with the correct length, avoiding future allocations. ## Checklist - [ ] I have linked to any relevant issues. - [ ] I have commented my code, particularly in hard-to-understand areas. - [ ] I have updated the documentation where relevant (API docs, the reference, and the Sway book). - [ ] If my change requires substantial documentation changes, I have [requested support from the DevRel team](https://github.com/FuelLabs/devrel-requests/issues/new/choose) - [ ] I have added tests that prove my fix is effective or that my feature works. - [ ] I have added (or requested a maintainer to add) the necessary `Breaking*` or `New Feature` labels where relevant. - [ ] 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). - [ ] I have requested a review from the relevant team or maintainers.
1 parent c34231f commit 2d73d09

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

sway-lib-std/src/vec.sw

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -669,10 +669,10 @@ where
669669
T: AbiDecode,
670670
{
671671
fn abi_decode(ref mut buffer: BufferReader) -> Vec<T> {
672-
let mut v = Vec::new();
673-
674672
let len = u64::abi_decode(buffer);
675673

674+
let mut v = Vec::with_capacity(len);
675+
676676
let mut i = 0;
677677
while i < len {
678678
let item = T::abi_decode(buffer);
@@ -710,3 +710,19 @@ fn test_vec_with_len_1() {
710710
let _ = ve.remove(0);
711711
assert(ve.len == 0);
712712
}
713+
714+
#[test()]
715+
fn encode_and_decode_vec() {
716+
let mut v1: Vec<u64> = Vec::new();
717+
v1.push(1);
718+
v1.push(2);
719+
v1.push(3);
720+
721+
let v2 = abi_decode::<Vec<u64>>(encode(v1));
722+
723+
assert(v2.len() == 3);
724+
assert(v2.capacity() == 3);
725+
assert(v2.get(0) == Some(1));
726+
assert(v2.get(1) == Some(2));
727+
assert(v2.get(2) == Some(3));
728+
}

0 commit comments

Comments
 (0)