@@ -118,6 +118,9 @@ import {
118118 isPowerOf2
119119} from "./util" ;
120120
121+ // Use the built-in `TextEncoder` for UTF-8 conversion
122+ declare let TextEncoder : any ;
123+
121124/** Internal names of various compiler built-ins. */
122125export namespace BuiltinNames {
123126
@@ -749,6 +752,7 @@ export namespace BuiltinNames {
749752 export const memory_copy = "~lib/memory/memory.copy" ;
750753 export const memory_fill = "~lib/memory/memory.fill" ;
751754 export const memory_data = "~lib/memory/memory.data" ;
755+ export const memory_dataUTF8 = "~lib/memory/memory.dataUTF8" ;
752756
753757 // std/typedarray.ts
754758 export const Int8Array = "~lib/typedarray/Int8Array" ;
@@ -3491,6 +3495,41 @@ function builtin_memory_data(ctx: BuiltinFunctionContext): ExpressionRef {
34913495}
34923496builtinFunctions . set ( BuiltinNames . memory_data , builtin_memory_data ) ;
34933497
3498+ // memory.dataUTF8(value) -> usize
3499+ function builtin_memory_dataUTF8 ( ctx : BuiltinFunctionContext ) : ExpressionRef {
3500+ let compiler = ctx . compiler ;
3501+ let module = compiler . module ;
3502+ if (
3503+ checkTypeAbsent ( ctx ) |
3504+ checkArgsRequired ( ctx , 1 )
3505+ ) return module . unreachable ( ) ;
3506+ let operands = ctx . operands ;
3507+ let usizeType = compiler . options . usizeType ;
3508+ let offset : i64 ;
3509+ let arg0 = operands [ 0 ] ;
3510+ if ( ! arg0 . isLiteralKind ( LiteralKind . String ) ) {
3511+ compiler . error (
3512+ DiagnosticCode . String_literal_expected ,
3513+ arg0 . range
3514+ ) ;
3515+ return module . unreachable ( ) ;
3516+ }
3517+ let str = ( < StringLiteralExpression > arg0 ) . value ;
3518+ let array : Uint8Array = new TextEncoder ( 'utf8' ) . encode ( str ) ;
3519+ let arrayNullTerminated = new Uint8Array ( array . length + 1 ) ;
3520+ arrayNullTerminated . set ( array ) ;
3521+ offset = compiler . addAlignedMemorySegment ( arrayNullTerminated , 1 ) . offset ;
3522+ // FIXME: what if recompiles happen? recompiles are bad.
3523+ compiler . currentType = usizeType ;
3524+ if ( usizeType == Type . usize32 ) {
3525+ assert ( ! i64_high ( offset ) ) ;
3526+ return module . i32 ( i64_low ( offset ) ) ;
3527+ } else {
3528+ return module . i64 ( i64_low ( offset ) , i64_high ( offset ) ) ;
3529+ }
3530+ }
3531+ builtinFunctions . set ( BuiltinNames . memory_dataUTF8 , builtin_memory_dataUTF8 ) ;
3532+
34943533// === GC =====================================================================================
34953534
34963535function builtin_i31_new ( ctx : BuiltinFunctionContext ) : ExpressionRef {
0 commit comments