From fb5723355856890469c6a730639eb784f595cf13 Mon Sep 17 00:00:00 2001 From: Vaivaswatha Nagaraj Date: Tue, 19 Mar 2024 15:49:32 +0530 Subject: [PATCH] Fix temp alloc size in `try_as_str_array`. Allocation must be based on the type size with padding. --- 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);