From 9e51eebd6dfdb80ebddb3b39cb6723a783d262b0 Mon Sep 17 00:00:00 2001 From: Vaivaswatha N Date: Wed, 20 Mar 2024 12:18:41 +0530 Subject: [PATCH] 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. --- docs/book/src/reference/compiler_intrinsics.md | 2 +- sway-lib-std/src/primitive_conversions/str.sw | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/book/src/reference/compiler_intrinsics.md b/docs/book/src/reference/compiler_intrinsics.md index 80de9d623c3..a0dfd0f7c62 100644 --- a/docs/book/src/reference/compiler_intrinsics.md +++ b/docs/book/src/reference/compiler_intrinsics.md @@ -28,7 +28,7 @@ ___ __size_of_str_array() -> 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. diff --git a/sway-lib-std/src/primitive_conversions/str.sw b/sway-lib-std/src/primitive_conversions/str.sw index a6477f57657..bf0728a2eee 100644 --- a/sway-lib-std/src/primitive_conversions/str.sw +++ b/sway-lib-std/src/primitive_conversions/str.sw @@ -6,17 +6,23 @@ impl str { pub fn try_as_str_array(self) -> Option { __assert_is_str_array::(); let str_size = __size_of_str_array::(); + let tmp_alloc_size = __size_of::(); 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 { @@ -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::() == a.len() && __size_of_val(b) == 8); + let c = from_str_array(b); assert(a == c);