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 AbiEncode and AbiDecode for String #6037

Merged
merged 7 commits into from
May 22, 2024
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
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);
}
Loading