Skip to content

Commit

Permalink
Add AbiEncode and AbiDecode for String (#6037)
Browse files Browse the repository at this point in the history
## Description

`AbiEncode` and `AbiDecode` are missing for the `String` type. This is
required for inline tests being developed in
[sway-standards](FuelLabs/sway-standards#91).

## Checklist

- [ ] I have linked to any relevant issues.
- [x] 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)
- [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.
  • Loading branch information
bitzoic authored May 22, 2024
1 parent 6621833 commit 8011f84
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions sway-lib-std/src/string.sw
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,35 @@ impl Hash for String {
}
}

impl AbiEncode for String {
fn abi_encode(self, buffer: Buffer) -> Buffer {
// Encode the length
let mut buffer = self.bytes.len().abi_encode(buffer);

// Encode each byte of the string
let mut i = 0;
while i < self.bytes.len() {
let item = self.bytes.get(i).unwrap();
buffer = item.abi_encode(buffer);
i += 1;
}

buffer
}
}

impl AbiDecode for String {
fn abi_decode(ref mut buffer: BufferReader) -> Self {
// Get length and string data
let len = u64::abi_decode(buffer);
let data = buffer.read_bytes(len);
// Create string from the ptr and len as parts of a raw_slice
String {
bytes: Bytes::from(raw_slice::from_parts::<u8>(data.ptr(), len)),
}
}
}

// Tests

#[test]
Expand Down Expand Up @@ -521,3 +550,18 @@ fn string_test_hash() {

assert(sha256(string) == sha256(bytes));
}

#[test]
fn string_test_abi_encoding() {
let string = String::from_ascii_str("fuel");

let buffer = Buffer::new();
let encoded_string = string.abi_encode(buffer);

let encoded_raw_slice = encoded_string.as_raw_slice();
let mut buffer_reader = BufferReader::from_parts(encoded_raw_slice.ptr(), encoded_raw_slice.number_of_bytes());

let decoded_string = String::abi_decode(buffer_reader);

assert(string == decoded_string);
}

0 comments on commit 8011f84

Please sign in to comment.