Skip to content
This repository was archived by the owner on Jul 12, 2024. It is now read-only.

Commit 049d901

Browse files
committed
Refactor: use toCharArray to encode string to WTF-16
1 parent 7465e39 commit 049d901

File tree

1 file changed

+4
-29
lines changed

1 file changed

+4
-29
lines changed

Diff for: wasm/src/main/scala/wasm4s/WasmContext.scala

+4-29
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@ import org.scalajs.linker.interface.ModuleInitializer
2121
import org.scalajs.linker.interface.unstable.ModuleInitializerImpl
2222
import org.scalajs.linker.standard.LinkedTopLevelExport
2323

24-
import java.nio.charset.StandardCharsets
25-
2624
abstract class ReadOnlyWasmContext {
2725
import WasmContext._
2826

@@ -188,7 +186,10 @@ abstract class TypeDefinableWasmContext extends ReadOnlyWasmContext { this: Wasm
188186
data
189187

190188
case None =>
191-
val bytes = encodeStringToWTF16LE(str)
189+
val bytes = str.toCharArray.flatMap { char =>
190+
val value = char.toInt
191+
Array((value & 0xFF).toByte, (value >> 8).toByte)
192+
}
192193
val offset = nextConstatnStringOffset
193194
val data = StringData(nextConstantStringIndex, offset)
194195
constantStringGlobals(str) = data
@@ -243,32 +244,6 @@ abstract class TypeDefinableWasmContext extends ReadOnlyWasmContext { this: Wasm
243244
if (typeRef.dimensions > 1) IRTypes.ArrayType(typeRef.copy(dimensions = typeRef.dimensions - 1))
244245
else inferTypeFromTypeRef(typeRef.base)
245246
}
246-
247-
/** http://simonsapin.github.io/wtf-8/#encoding-ill-formed-utf-16
248-
*/
249-
private def encodeStringToWTF16LE(input: String): Array[Byte] = {
250-
val result = scala.collection.mutable.ArrayBuffer[Int]()
251-
var i = 0
252-
while (i < input.length) {
253-
val codePoint = input.codePointAt(i)
254-
if (codePoint < 0x10000) {
255-
// BMP code point
256-
result += codePoint
257-
i += Character.charCount(codePoint)
258-
} else {
259-
// Supplementary code point
260-
val highSurrogate = ((codePoint - 0x10000) >> 10) + 0xD800
261-
val lowSurrogate = ((codePoint - 0x10000) & 0x3FF) + 0xDC00
262-
result += highSurrogate
263-
result += lowSurrogate
264-
i += 2
265-
}
266-
}
267-
268-
result
269-
.flatMap(codeUnit => Seq((codeUnit & 0xFF).toByte, ((codeUnit >> 8) & 0xFF).toByte))
270-
.toArray
271-
}
272247
}
273248

274249
class WasmContext(val module: WasmModule) extends TypeDefinableWasmContext {

0 commit comments

Comments
 (0)