Skip to content

Commit 9e51eeb

Browse files
authored
stdlib: Fix temp alloc size in try_as_str_array. (#5753)
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.
1 parent e40daf7 commit 9e51eeb

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

docs/book/src/reference/compiler_intrinsics.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ ___
2828
__size_of_str_array<T>() -> u64
2929
```
3030

31-
**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.
31+
**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.
3232

3333
**Constraints:** None.
3434

sway-lib-std/src/primitive_conversions/str.sw

+12-4
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,23 @@ impl str {
66
pub fn try_as_str_array<S>(self) -> Option<S> {
77
__assert_is_str_array::<S>();
88
let str_size = __size_of_str_array::<S>();
9+
let tmp_alloc_size = __size_of::<S>();
910
let source = self.as_ptr();
1011

1112
if self.len() == str_size {
12-
let s: S = asm(str_size: str_size, source: source, dest) {
13+
let s: S = asm(
14+
str_size: str_size,
15+
tmp_alloc_size: tmp_alloc_size,
16+
source: source,
17+
dest,
18+
) {
1319
move dest sp;
14-
cfe str_size;
20+
cfe tmp_alloc_size;
1521
mcp dest source str_size;
1622
dest: S
1723
};
18-
asm(str_size: str_size) {
19-
cfs str_size;
24+
asm(tmp_alloc_size: tmp_alloc_size) {
25+
cfs tmp_alloc_size;
2026
}
2127
Some(s)
2228
} else {
@@ -32,6 +38,8 @@ fn str_slice_to_str_array() {
3238

3339
let a = "abcd";
3440
let b: str[4] = a.try_as_str_array().unwrap();
41+
assert(__size_of_str_array::<str[4]>() == a.len() && __size_of_val(b) == 8);
42+
3543
let c = from_str_array(b);
3644

3745
assert(a == c);

0 commit comments

Comments
 (0)