Skip to content

Commit

Permalink
stdlib: Fix temp alloc size in try_as_str_array. (#5753)
Browse files Browse the repository at this point in the history
Allocation must be based on the type size with padding.

In addition to the usual testing, I've also tested against
https://github.com/FuelLabs/fuel-vm/tree/feature/0.43.3-memory-grow.
  • Loading branch information
vaivaswatha authored Mar 20, 2024
1 parent e40daf7 commit 9e51eeb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
2 changes: 1 addition & 1 deletion docs/book/src/reference/compiler_intrinsics.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ ___
__size_of_str_array<T>() -> u64
```

**Description:** Return the size of type `T` in bytes. This intrinsic differs from `__size_of` in the case of "string arrays" where the actual length in bytes of the string is returned without padding the byte size to the next word alignment. When `T` is not a string `0` is returned.
**Description:** Return the size of type `T` in bytes. This intrinsic differs from `__size_of` in the case of "string arrays" where the actual length in bytes of the string is returned without padding the byte size to the next word alignment. When `T` is not a "string array" `0` is returned.

**Constraints:** None.

Expand Down
16 changes: 12 additions & 4 deletions sway-lib-std/src/primitive_conversions/str.sw
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,23 @@ impl str {
pub fn try_as_str_array<S>(self) -> Option<S> {
__assert_is_str_array::<S>();
let str_size = __size_of_str_array::<S>();
let tmp_alloc_size = __size_of::<S>();
let source = self.as_ptr();

if self.len() == str_size {
let s: S = asm(str_size: str_size, source: source, dest) {
let s: S = asm(
str_size: str_size,
tmp_alloc_size: tmp_alloc_size,
source: source,
dest,
) {
move dest sp;
cfe str_size;
cfe tmp_alloc_size;
mcp dest source str_size;
dest: S
};
asm(str_size: str_size) {
cfs str_size;
asm(tmp_alloc_size: tmp_alloc_size) {
cfs tmp_alloc_size;
}
Some(s)
} else {
Expand All @@ -32,6 +38,8 @@ fn str_slice_to_str_array() {

let a = "abcd";
let b: str[4] = a.try_as_str_array().unwrap();
assert(__size_of_str_array::<str[4]>() == a.len() && __size_of_val(b) == 8);

let c = from_str_array(b);

assert(a == c);
Expand Down

0 comments on commit 9e51eeb

Please sign in to comment.