[Git][ghc/ghc][wip/wasm-minor-improvements] wasm: add zero length fast path for fromJSString

Cheng Shao pushed to branch wip/wasm-minor-improvements at Glasgow Haskell Compiler / GHC Commits: f098a7b5 by Cheng Shao at 2025-05-09T21:24:20+00:00 wasm: add zero length fast path for fromJSString This patch adds a zero length fast path for `fromJSString`; when marshaling a zero-length `JSString` we don't need to allocate an empty `ByteArray#` at all. - - - - - 1 changed file: - libraries/ghc-internal/src/GHC/Internal/Wasm/Prim/Types.hs Changes: ===================================== libraries/ghc-internal/src/GHC/Internal/Wasm/Prim/Types.hs ===================================== @@ -184,15 +184,16 @@ newtype JSString -- eagerly once the resulting 'String' is forced, and the argument -- 'JSString' may be explicitly freed if no longer used. fromJSString :: JSString -> String -fromJSString s = unsafeDupablePerformIO $ do - l <- js_stringLength s - fp <- mallocPlainForeignPtrBytes $ l * 3 - withForeignPtr fp $ \buf -> do - l' <- js_encodeInto s buf $ l * 3 - peekCStringLen utf8 (buf, l') +fromJSString s = case js_stringLength s * 3 of + 0 -> "" + max_len -> unsafePerformIO $ do + fptr <- mallocPlainForeignPtrBytes max_len + withForeignPtr fptr $ \ptr -> do + len <- js_encodeInto s ptr max_len + peekCStringLen utf8 (ptr, len) foreign import javascript unsafe "$1.length" - js_stringLength :: JSString -> IO Int + js_stringLength :: JSString -> Int foreign import javascript unsafe "(new TextEncoder()).encodeInto($1, new Uint8Array(__exports.memory.buffer, $2, $3)).written" js_encodeInto :: JSString -> Ptr a -> Int -> IO Int View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/f098a7b5d1d8c9678a4f5267b2265bd8... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/f098a7b5d1d8c9678a4f5267b2265bd8... You're receiving this email because of your account on gitlab.haskell.org.
participants (1)
-
Cheng Shao (@TerrorJack)