From f0e58fec494ee732de26fd825bbc02a2873df5a8 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Sat, 21 May 2022 02:15:46 -0700 Subject: [PATCH] [TextEncoder] 3x faster in hot loops --- Makefile | 2 +- src/javascript/jsc/base.zig | 1 - .../jsc/bindings/ZigGlobalObject.cpp | 15 +- src/javascript/jsc/bindings/bindings.cpp | 21 +- src/javascript/jsc/bindings/bindings.zig | 7 +- src/javascript/jsc/bindings/headers-cpp.h | 2 +- src/javascript/jsc/bindings/headers.h | 3 +- src/javascript/jsc/bindings/headers.zig | 1 + .../bindings/webcore/DOMClientIsoSubspaces.h | 2 +- .../jsc/bindings/webcore/DOMIsoSubspaces.h | 2 +- .../jsc/bindings/webcore/JSTextEncoder.cpp | 409 ++++++++++++++++++ .../jsc/bindings/webcore/JSTextEncoder.dep | 1 + .../jsc/bindings/webcore/JSTextEncoder.h | 98 +++++ .../jsc/bindings/webcore/TextEncoder.cpp | 75 ++++ .../jsc/bindings/webcore/TextEncoder.h | 54 +++ src/javascript/jsc/javascript.zig | 41 +- src/javascript/jsc/typescript.zig | 1 - src/javascript/jsc/webcore/encoding.zig | 132 ++---- src/js_parser.zig | 5 +- src/options.zig | 6 +- src/string_immutable.zig | 7 +- 21 files changed, 752 insertions(+), 133 deletions(-) create mode 100644 src/javascript/jsc/bindings/webcore/JSTextEncoder.cpp create mode 100644 src/javascript/jsc/bindings/webcore/JSTextEncoder.dep create mode 100644 src/javascript/jsc/bindings/webcore/JSTextEncoder.h create mode 100644 src/javascript/jsc/bindings/webcore/TextEncoder.cpp create mode 100644 src/javascript/jsc/bindings/webcore/TextEncoder.h diff --git a/Makefile b/Makefile index 670283b7a6..5941d025cc 100644 --- a/Makefile +++ b/Makefile @@ -1144,7 +1144,7 @@ wasm-return1: EMIT_LLVM_FOR_RELEASE= -emit-llvm EMIT_LLVM_FOR_DEBUG= -EMIT_LLVM=$(EMIT_LLVM_FOR_DEBUG) +EMIT_LLVM=$(EMIT_LLVM_FOR_RELEASE) # We do this outside of build.zig for performance reasons # The C compilation stuff with build.zig is really slow and we don't need to run this as often as the rest diff --git a/src/javascript/jsc/base.zig b/src/javascript/jsc/base.zig index 70570ed201..998344d1ce 100644 --- a/src/javascript/jsc/base.zig +++ b/src/javascript/jsc/base.zig @@ -2646,7 +2646,6 @@ pub const JSPrivateDataPtr = TaggedPointerUnion(.{ Stats, TextChunk, TextDecoder, - TextEncoder, TimeoutTask, Transpiler, FFI, diff --git a/src/javascript/jsc/bindings/ZigGlobalObject.cpp b/src/javascript/jsc/bindings/ZigGlobalObject.cpp index 7d531c7e98..f21107634d 100644 --- a/src/javascript/jsc/bindings/ZigGlobalObject.cpp +++ b/src/javascript/jsc/bindings/ZigGlobalObject.cpp @@ -130,6 +130,7 @@ using JSBuffer = WebCore::JSBuffer; #include "JSWritableStreamDefaultController.h" #include "JSWritableStreamDefaultWriter.h" #include "JavaScriptCore/BuiltinNames.h" +#include "JSTextEncoder.h" #include "StructuredClone.h" // #include @@ -378,6 +379,17 @@ JSC_DEFINE_CUSTOM_GETTER(JSBuffer_getter, WebCore::JSBuffer::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); } +JSC_DECLARE_CUSTOM_GETTER(JSTextEncoder_getter); + +JSC_DEFINE_CUSTOM_GETTER(JSTextEncoder_getter, + (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, + JSC::PropertyName)) +{ + Zig::GlobalObject* thisObject = JSC::jsCast(lexicalGlobalObject); + return JSC::JSValue::encode( + WebCore::JSTextEncoder::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); +} + JSC_DECLARE_CUSTOM_GETTER(JSDOMURL_getter); JSC_DEFINE_CUSTOM_GETTER(JSDOMURL_getter, @@ -1307,7 +1319,8 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm) putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "Buffer"_s), JSC::CustomGetterSetter::create(vm, JSBuffer_getter, nullptr), JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); - + putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "TextEncoder"_s), JSC::CustomGetterSetter::create(vm, JSTextEncoder_getter, nullptr), + JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); putDirectCustomAccessor(vm, static_cast(vm.clientData)->builtinNames().TransformStreamPublicName(), CustomGetterSetter::create(vm, jsServiceWorkerGlobalScope_TransformStreamConstructor, nullptr), attributesForStructure(static_cast(JSC::PropertyAttribute::DontEnum))); putDirectCustomAccessor(vm, static_cast(vm.clientData)->builtinNames().TransformStreamPrivateName(), CustomGetterSetter::create(vm, jsServiceWorkerGlobalScope_TransformStreamConstructor, nullptr), attributesForStructure(static_cast(JSC::PropertyAttribute::DontEnum))); putDirectCustomAccessor(vm, static_cast(vm.clientData)->builtinNames().TransformStreamDefaultControllerPublicName(), CustomGetterSetter::create(vm, jsServiceWorkerGlobalScope_TransformStreamDefaultControllerConstructor, nullptr), attributesForStructure(static_cast(JSC::PropertyAttribute::DontEnum))); diff --git a/src/javascript/jsc/bindings/bindings.cpp b/src/javascript/jsc/bindings/bindings.cpp index ce21b81089..7d46becce9 100644 --- a/src/javascript/jsc/bindings/bindings.cpp +++ b/src/javascript/jsc/bindings/bindings.cpp @@ -967,15 +967,12 @@ bool JSC__JSValue__asArrayBuffer_(JSC__JSValue JSValue0, JSC__JSGlobalObject* ar JSC::JSObject* object = value.getObject(); if (JSC::JSArrayBufferView* typedArray = JSC::jsDynamicCast(object)) { - if (JSC::ArrayBuffer* buffer = typedArray->possiblySharedBuffer()) { - buffer->pinAndLock(); - arg2->ptr = reinterpret_cast(buffer->data()); - arg2->len = typedArray->length(); - arg2->byte_len = buffer->byteLength(); - arg2->offset = typedArray->byteOffset(); - arg2->cell_type = typedArray->type(); - return true; - } + arg2->ptr = reinterpret_cast(typedArray->vector()); + arg2->len = typedArray->length(); + arg2->byte_len = typedArray->byteLength(); + arg2->offset = typedArray->byteOffset(); + arg2->cell_type = typedArray->type(); + return true; } if (JSC::ArrayBuffer* buffer = JSC::toPossiblySharedArrayBuffer(vm, value)) { @@ -2997,4 +2994,10 @@ JSC__JSValue JSC__JSPromise__resolvedPromiseValue(JSC__JSGlobalObject* arg0, return JSC::JSValue::encode( JSC::JSPromise::resolvedPromise(arg0, JSC::JSValue::decode(JSValue1))); } +} + +JSC__JSValue JSC__JSValue__createUninitializedUint8Array(JSC__JSGlobalObject* arg0, size_t arg1) +{ + JSC::JSValue value = JSC::JSUint8Array::createUninitialized(arg0, arg0->m_typedArrayUint8.get(arg0), arg1); + return JSC::JSValue::encode(value); } \ No newline at end of file diff --git a/src/javascript/jsc/bindings/bindings.zig b/src/javascript/jsc/bindings/bindings.zig index 96d3ab17c1..ceeacfff72 100644 --- a/src/javascript/jsc/bindings/bindings.zig +++ b/src/javascript/jsc/bindings/bindings.zig @@ -2369,6 +2369,11 @@ pub const JSValue = enum(u64) { } } + pub fn createUninitializedUint8Array(globalObject: *JSGlobalObject, len: usize) JSValue { + if (comptime JSC.is_bindgen) unreachable; + return shim.cppFn("createUninitializedUint8Array", .{ globalObject, len }); + } + pub fn createBufferWithCtx(globalObject: *JSGlobalObject, slice: []u8, ptr: ?*anyopaque, func: JSC.C.JSTypedArrayBytesDeallocator) JSValue { if (comptime JSC.is_bindgen) unreachable; @setRuntimeSafety(false); @@ -2906,7 +2911,7 @@ pub const JSValue = enum(u64) { return @intToPtr(*anyopaque, @enumToInt(this)); } - pub const Extern = [_][]const u8{ "fromInt64NoTruncate", "fromUInt64NoTruncate", "toUInt64NoTruncate", "asPromise", "toInt64", "_then", "put", "makeWithNameAndPrototype", "parseJSON", "symbolKeyFor", "symbolFor", "getSymbolDescription", "createInternalPromise", "asInternalPromise", "asArrayBuffer_", "getReadableStreamState", "getWritableStreamState", "fromEntries", "createTypeError", "createRangeError", "createObject2", "getIfPropertyExistsImpl", "jsType", "jsonStringify", "kind_", "isTerminationException", "isSameValue", "getLengthOfArray", "toZigString", "createStringArray", "createEmptyObject", "putRecord", "asPromise", "isClass", "getNameProperty", "getClassName", "getErrorsProperty", "toInt32", "toBoolean", "isInt32", "isIterable", "forEach", "isAggregateError", "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" }; + pub const Extern = [_][]const u8{ "createUninitializedUint8Array", "fromInt64NoTruncate", "fromUInt64NoTruncate", "toUInt64NoTruncate", "asPromise", "toInt64", "_then", "put", "makeWithNameAndPrototype", "parseJSON", "symbolKeyFor", "symbolFor", "getSymbolDescription", "createInternalPromise", "asInternalPromise", "asArrayBuffer_", "getReadableStreamState", "getWritableStreamState", "fromEntries", "createTypeError", "createRangeError", "createObject2", "getIfPropertyExistsImpl", "jsType", "jsonStringify", "kind_", "isTerminationException", "isSameValue", "getLengthOfArray", "toZigString", "createStringArray", "createEmptyObject", "putRecord", "asPromise", "isClass", "getNameProperty", "getClassName", "getErrorsProperty", "toInt32", "toBoolean", "isInt32", "isIterable", "forEach", "isAggregateError", "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" }; }; extern "c" fn Microtask__run(*Microtask, *JSGlobalObject) void; diff --git a/src/javascript/jsc/bindings/headers-cpp.h b/src/javascript/jsc/bindings/headers-cpp.h index e4ce342308..a0f87d57df 100644 --- a/src/javascript/jsc/bindings/headers-cpp.h +++ b/src/javascript/jsc/bindings/headers-cpp.h @@ -1,4 +1,4 @@ -//-- AUTOGENERATED FILE -- 1653084677 +//-- AUTOGENERATED FILE -- 1653120181 // clang-format off #pragma once diff --git a/src/javascript/jsc/bindings/headers.h b/src/javascript/jsc/bindings/headers.h index 7a1ba00b70..c5964f0018 100644 --- a/src/javascript/jsc/bindings/headers.h +++ b/src/javascript/jsc/bindings/headers.h @@ -1,5 +1,5 @@ // clang-format: off -//-- AUTOGENERATED FILE -- 1653084677 +//-- AUTOGENERATED FILE -- 1653120181 #pragma once #include @@ -477,6 +477,7 @@ CPP_DECL JSC__JSValue JSC__JSValue__createObject2(JSC__JSGlobalObject* arg0, con CPP_DECL JSC__JSValue JSC__JSValue__createRangeError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); CPP_DECL JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject* arg0, ZigString* arg1, size_t arg2, bool arg3); CPP_DECL JSC__JSValue JSC__JSValue__createTypeError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); +CPP_DECL JSC__JSValue JSC__JSValue__createUninitializedUint8Array(JSC__JSGlobalObject* arg0, size_t arg1); CPP_DECL bool JSC__JSValue__eqlCell(JSC__JSValue JSValue0, JSC__JSCell* arg1); CPP_DECL bool JSC__JSValue__eqlValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1); CPP_DECL void JSC__JSValue__forEach(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, void* arg2, void (* ArgFn3)(JSC__VM* arg0, JSC__JSGlobalObject* arg1, void* arg2, JSC__JSValue JSValue3)); diff --git a/src/javascript/jsc/bindings/headers.zig b/src/javascript/jsc/bindings/headers.zig index 3b74bd4cdb..0c09354096 100644 --- a/src/javascript/jsc/bindings/headers.zig +++ b/src/javascript/jsc/bindings/headers.zig @@ -320,6 +320,7 @@ pub extern fn JSC__JSValue__createObject2(arg0: [*c]JSC__JSGlobalObject, arg1: [ pub extern fn JSC__JSValue__createRangeError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn JSC__JSValue__createStringArray(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: usize, arg3: bool) JSC__JSValue; pub extern fn JSC__JSValue__createTypeError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn JSC__JSValue__createUninitializedUint8Array(arg0: [*c]JSC__JSGlobalObject, arg1: usize) JSC__JSValue; pub extern fn JSC__JSValue__eqlCell(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSCell) bool; pub extern fn JSC__JSValue__eqlValue(JSValue0: JSC__JSValue, JSValue1: JSC__JSValue) bool; pub extern fn JSC__JSValue__forEach(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: ?*anyopaque, ArgFn3: ?fn ([*c]JSC__VM, [*c]JSC__JSGlobalObject, ?*anyopaque, JSC__JSValue) callconv(.C) void) void; diff --git a/src/javascript/jsc/bindings/webcore/DOMClientIsoSubspaces.h b/src/javascript/jsc/bindings/webcore/DOMClientIsoSubspaces.h index c965f6731d..14e748a9af 100644 --- a/src/javascript/jsc/bindings/webcore/DOMClientIsoSubspaces.h +++ b/src/javascript/jsc/bindings/webcore/DOMClientIsoSubspaces.h @@ -450,7 +450,7 @@ public: // std::unique_ptr m_clientSubspaceForTextDecoder; // std::unique_ptr m_clientSubspaceForTextDecoderStream; // std::unique_ptr m_clientSubspaceForTextDecoderStreamDecoder; - // std::unique_ptr m_clientSubspaceForTextEncoder; + std::unique_ptr m_clientSubspaceForTextEncoder; // std::unique_ptr m_clientSubspaceForTextEncoderStream; // std::unique_ptr m_clientSubspaceForTextEncoderStreamEncoder; // std::unique_ptr m_clientSubspaceForTextEvent; diff --git a/src/javascript/jsc/bindings/webcore/DOMIsoSubspaces.h b/src/javascript/jsc/bindings/webcore/DOMIsoSubspaces.h index 7d0c1cb3fd..b434ff7716 100644 --- a/src/javascript/jsc/bindings/webcore/DOMIsoSubspaces.h +++ b/src/javascript/jsc/bindings/webcore/DOMIsoSubspaces.h @@ -443,7 +443,7 @@ public: // std::unique_ptr m_subspaceForTextDecoder; // std::unique_ptr m_subspaceForTextDecoderStream; // std::unique_ptr m_subspaceForTextDecoderStreamDecoder; - // std::unique_ptr m_subspaceForTextEncoder; + std::unique_ptr m_subspaceForTextEncoder; // std::unique_ptr m_subspaceForTextEncoderStream; // std::unique_ptr m_subspaceForTextEncoderStreamEncoder; // std::unique_ptr m_subspaceForTextEvent; diff --git a/src/javascript/jsc/bindings/webcore/JSTextEncoder.cpp b/src/javascript/jsc/bindings/webcore/JSTextEncoder.cpp new file mode 100644 index 0000000000..bc348276c3 --- /dev/null +++ b/src/javascript/jsc/bindings/webcore/JSTextEncoder.cpp @@ -0,0 +1,409 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "JSTextEncoder.h" + +#include "ActiveDOMObject.h" +#include "ExtendedDOMClientIsoSubspaces.h" +#include "ExtendedDOMIsoSubspaces.h" +#include "JSDOMAttribute.h" +#include "JSDOMBinding.h" +#include "JSDOMConstructor.h" +#include "JSDOMConvertBufferSource.h" +#include "JSDOMConvertInterface.h" +#include "JSDOMConvertNumbers.h" +#include "JSDOMConvertStrings.h" +#include "JSDOMExceptionHandling.h" +#include "JSDOMGlobalObject.h" +#include "JSDOMGlobalObjectInlines.h" +#include "JSDOMOperation.h" +#include "JSDOMWrapperCache.h" +#include "ScriptExecutionContext.h" +#include "WebCoreJSClientData.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WebCore { +using namespace JSC; + +template<> TextEncoder::EncodeIntoResult convertDictionary(JSGlobalObject& lexicalGlobalObject, JSValue value) +{ + VM& vm = JSC::getVM(&lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + bool isNullOrUndefined = value.isUndefinedOrNull(); + auto* object = isNullOrUndefined ? nullptr : value.getObject(); + if (UNLIKELY(!isNullOrUndefined && !object)) { + throwTypeError(&lexicalGlobalObject, throwScope); + return {}; + } + TextEncoder::EncodeIntoResult result; + JSValue readValue; + if (isNullOrUndefined) + readValue = jsUndefined(); + else { + readValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "read"_s)); + RETURN_IF_EXCEPTION(throwScope, {}); + } + if (!readValue.isUndefined()) { + result.read = convert(lexicalGlobalObject, readValue); + RETURN_IF_EXCEPTION(throwScope, {}); + } + JSValue writtenValue; + if (isNullOrUndefined) + writtenValue = jsUndefined(); + else { + writtenValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "written"_s)); + RETURN_IF_EXCEPTION(throwScope, {}); + } + if (!writtenValue.isUndefined()) { + result.written = convert(lexicalGlobalObject, writtenValue); + RETURN_IF_EXCEPTION(throwScope, {}); + } + return result; +} + +JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject& lexicalGlobalObject, JSDOMGlobalObject& globalObject, const TextEncoder::EncodeIntoResult& dictionary) +{ + auto& vm = JSC::getVM(&lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + + auto result = constructEmptyObject(&lexicalGlobalObject, globalObject.objectPrototype()); + + if (!IDLUnsignedLongLong::isNullValue(dictionary.read)) { + auto readValue = toJS(lexicalGlobalObject, throwScope, IDLUnsignedLongLong::extractValueFromNullable(dictionary.read)); + RETURN_IF_EXCEPTION(throwScope, {}); + result->putDirect(vm, JSC::Identifier::fromString(vm, "read"_s), readValue); + } + if (!IDLUnsignedLongLong::isNullValue(dictionary.written)) { + auto writtenValue = toJS(lexicalGlobalObject, throwScope, IDLUnsignedLongLong::extractValueFromNullable(dictionary.written)); + RETURN_IF_EXCEPTION(throwScope, {}); + result->putDirect(vm, JSC::Identifier::fromString(vm, "written"_s), writtenValue); + } + return result; +} + +// Functions + +static JSC_DECLARE_HOST_FUNCTION(jsTextEncoderPrototypeFunction_encode); +static JSC_DECLARE_HOST_FUNCTION(jsTextEncoderPrototypeFunction_encodeInto); + +// Attributes + +static JSC_DECLARE_CUSTOM_GETTER(jsTextEncoderConstructor); +static JSC_DECLARE_CUSTOM_GETTER(jsTextEncoder_encoding); + +class JSTextEncoderPrototype final : public JSC::JSNonFinalObject { +public: + using Base = JSC::JSNonFinalObject; + static JSTextEncoderPrototype* create(JSC::VM& vm, JSDOMGlobalObject* globalObject, JSC::Structure* structure) + { + JSTextEncoderPrototype* ptr = new (NotNull, JSC::allocateCell(vm)) JSTextEncoderPrototype(vm, globalObject, structure); + ptr->finishCreation(vm); + return ptr; + } + + DECLARE_INFO; + template + static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSTextEncoderPrototype, Base); + return &vm.plainObjectSpace(); + } + static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) + { + return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); + } + +private: + JSTextEncoderPrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) + : JSC::JSNonFinalObject(vm, structure) + { + } + + void finishCreation(JSC::VM&); +}; +STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSTextEncoderPrototype, JSTextEncoderPrototype::Base); + +using JSTextEncoderDOMConstructor = JSDOMConstructor; + +template<> EncodedJSValue JSC_HOST_CALL_ATTRIBUTES JSTextEncoderDOMConstructor::construct(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame) +{ + VM& vm = lexicalGlobalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto* castedThis = jsCast(callFrame->jsCallee()); + ASSERT(castedThis); + auto object = TextEncoder::create(); + if constexpr (IsExceptionOr) + RETURN_IF_EXCEPTION(throwScope, {}); + static_assert(TypeOrExceptionOrUnderlyingType::isRef); + auto jsValue = toJSNewlyCreated>(*lexicalGlobalObject, *castedThis->globalObject(), throwScope, WTFMove(object)); + if constexpr (IsExceptionOr) + RETURN_IF_EXCEPTION(throwScope, {}); + setSubclassStructureIfNeeded(lexicalGlobalObject, callFrame, asObject(jsValue)); + RETURN_IF_EXCEPTION(throwScope, {}); + return JSValue::encode(jsValue); +} +JSC_ANNOTATE_HOST_FUNCTION(JSTextEncoderDOMConstructorConstruct, JSTextEncoderDOMConstructor::construct); + +template<> const ClassInfo JSTextEncoderDOMConstructor::s_info = { "TextEncoder"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTextEncoderDOMConstructor) }; + +template<> JSValue JSTextEncoderDOMConstructor::prototypeForStructure(JSC::VM& vm, const JSDOMGlobalObject& globalObject) +{ + UNUSED_PARAM(vm); + return globalObject.functionPrototype(); +} + +template<> void JSTextEncoderDOMConstructor::initializeProperties(VM& vm, JSDOMGlobalObject& globalObject) +{ + putDirect(vm, vm.propertyNames->length, jsNumber(0), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); + JSString* nameString = jsNontrivialString(vm, "TextEncoder"_s); + m_originalName.set(vm, this, nameString); + putDirect(vm, vm.propertyNames->name, nameString, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); + putDirect(vm, vm.propertyNames->prototype, JSTextEncoder::prototype(vm, globalObject), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::DontDelete); +} + +/* Hash table for prototype */ + +static const HashTableValue JSTextEncoderPrototypeTableValues[] = { + { "constructor"_s, static_cast(JSC::PropertyAttribute::DontEnum), NoIntrinsic, { (intptr_t) static_cast(jsTextEncoderConstructor), (intptr_t) static_cast(0) } }, + { "encoding"_s, static_cast(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute), NoIntrinsic, { (intptr_t) static_cast(jsTextEncoder_encoding), (intptr_t) static_cast(0) } }, + { "encode"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { (intptr_t) static_cast(jsTextEncoderPrototypeFunction_encode), (intptr_t)(0) } }, + { "encodeInto"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { (intptr_t) static_cast(jsTextEncoderPrototypeFunction_encodeInto), (intptr_t)(2) } }, +}; + +const ClassInfo JSTextEncoderPrototype::s_info = { "TextEncoder"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTextEncoderPrototype) }; + +void JSTextEncoderPrototype::finishCreation(VM& vm) +{ + Base::finishCreation(vm); + reifyStaticProperties(vm, JSTextEncoder::info(), JSTextEncoderPrototypeTableValues, *this); + JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); +} + +const ClassInfo JSTextEncoder::s_info = { "TextEncoder"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTextEncoder) }; + +JSTextEncoder::JSTextEncoder(Structure* structure, JSDOMGlobalObject& globalObject, Ref&& impl) + : JSDOMWrapper(structure, globalObject, WTFMove(impl)) +{ +} + +void JSTextEncoder::finishCreation(VM& vm) +{ + Base::finishCreation(vm); + ASSERT(inherits(info())); + + // static_assert(!std::is_base_of::value, "Interface is not marked as [ActiveDOMObject] even though implementation class subclasses ActiveDOMObject."); +} + +JSObject* JSTextEncoder::createPrototype(VM& vm, JSDOMGlobalObject& globalObject) +{ + return JSTextEncoderPrototype::create(vm, &globalObject, JSTextEncoderPrototype::createStructure(vm, &globalObject, globalObject.objectPrototype())); +} + +JSObject* JSTextEncoder::prototype(VM& vm, JSDOMGlobalObject& globalObject) +{ + return getDOMPrototype(vm, globalObject); +} + +JSValue JSTextEncoder::getConstructor(VM& vm, const JSGlobalObject* globalObject) +{ + return getDOMConstructor(vm, *jsCast(globalObject)); +} + +void JSTextEncoder::destroy(JSC::JSCell* cell) +{ + JSTextEncoder* thisObject = static_cast(cell); + thisObject->JSTextEncoder::~JSTextEncoder(); +} + +JSC_DEFINE_CUSTOM_GETTER(jsTextEncoderConstructor, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto* prototype = jsDynamicCast(JSValue::decode(thisValue)); + if (UNLIKELY(!prototype)) + return throwVMTypeError(lexicalGlobalObject, throwScope); + return JSValue::encode(JSTextEncoder::getConstructor(JSC::getVM(lexicalGlobalObject), prototype->globalObject())); +} + +static inline JSValue jsTextEncoder_encodingGetter(JSGlobalObject& lexicalGlobalObject, JSTextEncoder& thisObject) +{ + auto& vm = JSC::getVM(&lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto& impl = thisObject.wrapped(); + RELEASE_AND_RETURN(throwScope, (toJS(lexicalGlobalObject, throwScope, impl.encoding()))); +} + +JSC_DEFINE_CUSTOM_GETTER(jsTextEncoder_encoding, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) +{ + return IDLAttribute::get(*lexicalGlobalObject, thisValue, attributeName); +} + +extern "C" JSC::EncodedJSValue TextEncoder__encode(JSC::JSGlobalObject* lexicalGlobalObject, const ZigString*); +extern "C" JSC::EncodedJSValue TextEncoder__encodeInto(JSC::JSGlobalObject* lexicalGlobalObject, const ZigString*, void* ptr, size_t len); + +static inline JSC::EncodedJSValue jsTextEncoderPrototypeFunction_encodeBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + EnsureStillAliveScope argument0 = callFrame->argument(0); + if (argument0.value().isUndefined()) { + return JSValue::encode(JSC::JSUint8Array::createUninitialized(lexicalGlobalObject, lexicalGlobalObject->m_typedArrayUint8.get(lexicalGlobalObject), 0)); + } + auto input = argument0.value().toWTFString(lexicalGlobalObject); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + auto str = Zig::toZigString(WTFMove(input)); + auto res = TextEncoder__encode(lexicalGlobalObject, &str); + if (UNLIKELY(JSC::JSValue::decode(res).isObject() && JSC::JSValue::decode(res).getObject()->isErrorInstance())) { + throwScope.throwException(lexicalGlobalObject, JSC::JSValue::decode(res)); + return encodedJSValue(); + } + RELEASE_AND_RETURN(throwScope, res); +} + +JSC_DEFINE_HOST_FUNCTION(jsTextEncoderPrototypeFunction_encode, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "encode"); +} + +static inline JSC::EncodedJSValue jsTextEncoderPrototypeFunction_encodeIntoBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + if (UNLIKELY(callFrame->argumentCount() < 2)) + return throwVMError(lexicalGlobalObject, throwScope, createNotEnoughArgumentsError(lexicalGlobalObject)); + EnsureStillAliveScope argument0 = callFrame->uncheckedArgument(0); + auto source = argument0.value().toWTFString(lexicalGlobalObject); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + EnsureStillAliveScope argument1 = callFrame->uncheckedArgument(1); + auto destination = convert>(*lexicalGlobalObject, argument1.value(), [](JSC::JSGlobalObject& lexicalGlobalObject, JSC::ThrowScope& scope) { throwArgumentTypeError(lexicalGlobalObject, scope, 1, "destination", "TextEncoder", "encodeInto", "Uint8Array"); }); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + auto str = Zig::toZigString(WTFMove(source)); + auto res = TextEncoder__encodeInto(lexicalGlobalObject, &str, destination->data(), destination->length()); + if (UNLIKELY(JSC::JSValue::decode(res).isObject() && JSC::JSValue::decode(res).getObject()->isErrorInstance())) { + throwScope.throwException(lexicalGlobalObject, JSC::JSValue::decode(res)); + return encodedJSValue(); + } + + RELEASE_AND_RETURN(throwScope, res); +} + +JSC_DEFINE_HOST_FUNCTION(jsTextEncoderPrototypeFunction_encodeInto, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "encodeInto"); +} + +JSC::GCClient::IsoSubspace* JSTextEncoder::subspaceForImpl(JSC::VM& vm) +{ + return WebCore::subspaceForImpl( + vm, + [](auto& spaces) { return spaces.m_clientSubspaceForTextEncoder.get(); }, + [](auto& spaces, auto&& space) { spaces.m_clientSubspaceForTextEncoder = WTFMove(space); }, + [](auto& spaces) { return spaces.m_subspaceForTextEncoder.get(); }, + [](auto& spaces, auto&& space) { spaces.m_subspaceForTextEncoder = WTFMove(space); }); +} + +void JSTextEncoder::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) +{ + auto* thisObject = jsCast(cell); + analyzer.setWrappedObjectForCell(cell, &thisObject->wrapped()); + if (thisObject->scriptExecutionContext()) + analyzer.setLabelForCell(cell, "url " + thisObject->scriptExecutionContext()->url().string()); + Base::analyzeHeap(cell, analyzer); +} + +bool JSTextEncoderOwner::isReachableFromOpaqueRoots(JSC::Handle handle, void*, AbstractSlotVisitor& visitor, const char** reason) +{ + UNUSED_PARAM(handle); + UNUSED_PARAM(visitor); + UNUSED_PARAM(reason); + return false; +} + +void JSTextEncoderOwner::finalize(JSC::Handle handle, void* context) +{ + auto* jsTextEncoder = static_cast(handle.slot()->asCell()); + auto& world = *static_cast(context); + uncacheWrapper(world, &jsTextEncoder->wrapped(), jsTextEncoder); +} + +#if ENABLE(BINDING_INTEGRITY) +#if PLATFORM(WIN) +#pragma warning(disable : 4483) +extern "C" { +extern void (*const __identifier("??_7TextEncoder@WebCore@@6B@")[])(); +} +#else +extern "C" { +extern void* _ZTVN7WebCore11TextEncoderE[]; +} +#endif +#endif + +JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject* globalObject, Ref&& impl) +{ + + if constexpr (std::is_polymorphic_v) { +#if ENABLE(BINDING_INTEGRITY) + const void* actualVTablePointer = getVTablePointer(impl.ptr()); +#if PLATFORM(WIN) + void* expectedVTablePointer = __identifier("??_7TextEncoder@WebCore@@6B@"); +#else + void* expectedVTablePointer = &_ZTVN7WebCore11TextEncoderE[2]; +#endif + + // If you hit this assertion you either have a use after free bug, or + // TextEncoder has subclasses. If TextEncoder has subclasses that get passed + // to toJS() we currently require TextEncoder you to opt out of binding hardening + // by adding the SkipVTableValidation attribute to the interface IDL definition + RELEASE_ASSERT(actualVTablePointer == expectedVTablePointer); +#endif + } + return createWrapper(globalObject, WTFMove(impl)); +} + +JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, TextEncoder& impl) +{ + return wrap(lexicalGlobalObject, globalObject, impl); +} + +TextEncoder* JSTextEncoder::toWrapped(JSC::VM&, JSC::JSValue value) +{ + if (auto* wrapper = jsDynamicCast(value)) + return &wrapper->wrapped(); + return nullptr; +} + +} diff --git a/src/javascript/jsc/bindings/webcore/JSTextEncoder.dep b/src/javascript/jsc/bindings/webcore/JSTextEncoder.dep new file mode 100644 index 0000000000..bdb1dfb7c5 --- /dev/null +++ b/src/javascript/jsc/bindings/webcore/JSTextEncoder.dep @@ -0,0 +1 @@ +JSTextEncoder.h : diff --git a/src/javascript/jsc/bindings/webcore/JSTextEncoder.h b/src/javascript/jsc/bindings/webcore/JSTextEncoder.h new file mode 100644 index 0000000000..ce0ffd3c90 --- /dev/null +++ b/src/javascript/jsc/bindings/webcore/JSTextEncoder.h @@ -0,0 +1,98 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#pragma once + +#include "JSDOMConvertDictionary.h" +#include "JSDOMWrapper.h" +#include "TextEncoder.h" +#include + +namespace WebCore { + +class JSTextEncoder : public JSDOMWrapper { +public: + using Base = JSDOMWrapper; + static JSTextEncoder* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, Ref&& impl) + { + JSTextEncoder* ptr = new (NotNull, JSC::allocateCell(globalObject->vm())) JSTextEncoder(structure, *globalObject, WTFMove(impl)); + ptr->finishCreation(globalObject->vm()); + return ptr; + } + + static JSC::JSObject* createPrototype(JSC::VM&, JSDOMGlobalObject&); + static JSC::JSObject* prototype(JSC::VM&, JSDOMGlobalObject&); + static TextEncoder* toWrapped(JSC::VM&, JSC::JSValue); + static void destroy(JSC::JSCell*); + + DECLARE_INFO; + + static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) + { + return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info(), JSC::NonArray); + } + + static JSC::JSValue getConstructor(JSC::VM&, const JSC::JSGlobalObject*); + template static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + if constexpr (mode == JSC::SubspaceAccess::Concurrently) + return nullptr; + return subspaceForImpl(vm); + } + static JSC::GCClient::IsoSubspace* subspaceForImpl(JSC::VM& vm); + static void analyzeHeap(JSCell*, JSC::HeapAnalyzer&); +protected: + JSTextEncoder(JSC::Structure*, JSDOMGlobalObject&, Ref&&); + + void finishCreation(JSC::VM&); +}; + +class JSTextEncoderOwner final : public JSC::WeakHandleOwner { +public: + bool isReachableFromOpaqueRoots(JSC::Handle, void* context, JSC::AbstractSlotVisitor&, const char**) final; + void finalize(JSC::Handle, void* context) final; +}; + +inline JSC::WeakHandleOwner* wrapperOwner(DOMWrapperWorld&, TextEncoder*) +{ + static NeverDestroyed owner; + return &owner.get(); +} + +inline void* wrapperKey(TextEncoder* wrappableObject) +{ + return wrappableObject; +} + +JSC::JSValue toJS(JSC::JSGlobalObject*, JSDOMGlobalObject*, TextEncoder&); +inline JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, TextEncoder* impl) { return impl ? toJS(lexicalGlobalObject, globalObject, *impl) : JSC::jsNull(); } +JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject*, Ref&&); +inline JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, RefPtr&& impl) { return impl ? toJSNewlyCreated(lexicalGlobalObject, globalObject, impl.releaseNonNull()) : JSC::jsNull(); } + +template<> struct JSDOMWrapperConverterTraits { + using WrapperClass = JSTextEncoder; + using ToWrappedReturnType = TextEncoder*; +}; +template<> TextEncoder::EncodeIntoResult convertDictionary(JSC::JSGlobalObject&, JSC::JSValue); + +JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject&, JSDOMGlobalObject&, const TextEncoder::EncodeIntoResult&); + + +} // namespace WebCore diff --git a/src/javascript/jsc/bindings/webcore/TextEncoder.cpp b/src/javascript/jsc/bindings/webcore/TextEncoder.cpp new file mode 100644 index 0000000000..85d09bcf42 --- /dev/null +++ b/src/javascript/jsc/bindings/webcore/TextEncoder.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "TextEncoder.h" + +#include +#include +#include + +namespace WebCore { + +String TextEncoder::encoding() const +{ + return "utf-8"_s; +} + +RefPtr TextEncoder::encode(String&& input) const +{ + // THIS CODE SHOULD NEVER BE REACHED IN BUN + RELEASE_ASSERT(1); + return nullptr; +} + +auto TextEncoder::encodeInto(String&& input, Ref&& array) -> EncodeIntoResult +{ + // THIS CODE SHOULD NEVER BE REACHED IN BUN + RELEASE_ASSERT(1); + + auto* destinationBytes = static_cast(array->baseAddress()); + auto capacity = array->byteLength(); + + uint64_t read = 0; + uint64_t written = 0; + + for (auto token : StringView(input).codePoints()) { + if (written >= capacity) { + ASSERT(written == capacity); + break; + } + UBool sawError = false; + U8_APPEND(destinationBytes, written, capacity, token, sawError); + if (sawError) + break; + if (U_IS_BMP(token)) + read++; + else + read += 2; + } + + return { read, written }; +} + +} diff --git a/src/javascript/jsc/bindings/webcore/TextEncoder.h b/src/javascript/jsc/bindings/webcore/TextEncoder.h new file mode 100644 index 0000000000..6a0145c78c --- /dev/null +++ b/src/javascript/jsc/bindings/webcore/TextEncoder.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "JSDOMConvertBufferSource.h" +#include +#include +#include +#include +#include + +// THIS FILE IS UNUSED +// IT EXISTS TO MAKE THE BINDINGS HAPPY +namespace WebCore { + +class TextEncoder : public RefCounted { +public: + struct EncodeIntoResult { + uint64_t read { 0 }; + uint64_t written { 0 }; + }; + + static Ref create() { return adoptRef(*new TextEncoder); } + String encoding() const; + RefPtr encode(String&&) const; + EncodeIntoResult encodeInto(String&&, Ref&& destination); + +private: + TextEncoder() {}; +}; + +} diff --git a/src/javascript/jsc/javascript.zig b/src/javascript/jsc/javascript.zig index 9de25b756e..2be4512594 100644 --- a/src/javascript/jsc/javascript.zig +++ b/src/javascript/jsc/javascript.zig @@ -15,7 +15,7 @@ const StoredFileDescriptorType = bun.StoredFileDescriptorType; const Arena = @import("../../mimalloc_arena.zig").Arena; const C = bun.C; const NetworkThread = @import("http").NetworkThread; - +const IO = @import("io"); pub fn zigCast(comptime Destination: type, value: anytype) *Destination { return @ptrCast(*Destination, @alignCast(@alignOf(*Destination), value)); } @@ -88,7 +88,7 @@ const ThreadSafeFunction = JSC.napi.ThreadSafeFunction; pub const GlobalConstructors = [_]type{ WebCore.Blob.Constructor, WebCore.TextDecoder.Constructor, - WebCore.TextEncoder.Constructor, + // WebCore.TextEncoder.Constructor, Request.Constructor, Response.Constructor, JSC.Cloudflare.HTMLRewriter.Constructor, @@ -575,6 +575,15 @@ pub const VirtualMachine = struct { response_objects_pool: ?*Response.Pool = null, rare_data: ?*JSC.RareData = null, + io_: ?IO = null, + + pub fn io(this: *VirtualMachine) *IO { + if (this.io_ == null) { + this.io_ = IO.init(this) catch @panic("Failed to initialize IO"); + } + + return &this.io_.?; + } pub inline fn nodeFS(this: *VirtualMachine) *Node.NodeFS { return this.node_fs orelse brk: { @@ -712,16 +721,32 @@ pub const VirtualMachine = struct { // TODO: fix this technical debt pub fn tick(this: *EventLoop) void { - while (true) { - this.tickConcurrent(); + if (this.virtual_machine.io_ == null) { + while (true) { + this.tickConcurrent(); - // this.global.vm().doWork(); + // this.global.vm().doWork(); - while (this.tickWithCount() > 0) {} + while (this.tickWithCount() > 0) {} - this.tickConcurrent(); + this.tickConcurrent(); - if (this.tickWithCount() == 0) break; + if (this.tickWithCount() == 0) break; + } else { + while (true) { + this.tickConcurrent(); + this.virtual_machine.io().tick() catch unreachable; + + // this.global.vm().doWork(); + + while (this.tickWithCount() > 0) {} + this.virtual_machine.io().tick() catch unreachable; + + this.tickConcurrent(); + + if (this.tickWithCount() == 0) break; + } + } } } diff --git a/src/javascript/jsc/typescript.zig b/src/javascript/jsc/typescript.zig index e6dd78ff7a..8815071ee1 100644 --- a/src/javascript/jsc/typescript.zig +++ b/src/javascript/jsc/typescript.zig @@ -40,7 +40,6 @@ pub fn main() anyerror!void { JSC.WebCore.Fetch.Class.typescriptDeclaration(), JSC.Performance.Class.typescriptDeclaration(), JSC.Crypto.Class.typescriptDeclaration(), - JSC.WebCore.TextEncoder.Class.typescriptDeclaration(), JSC.WebCore.TextDecoder.Class.typescriptDeclaration(), JSC.API.Transpiler.Class.typescriptDeclaration(), }; diff --git a/src/javascript/jsc/webcore/encoding.zig b/src/javascript/jsc/webcore/encoding.zig index 245f6127d8..3fab481272 100644 --- a/src/javascript/jsc/webcore/encoding.zig +++ b/src/javascript/jsc/webcore/encoding.zig @@ -42,116 +42,46 @@ const picohttp = @import("picohttp"); pub const TextEncoder = struct { filler: u32 = 0, - var text_encoder: TextEncoder = TextEncoder{}; - - pub const Constructor = JSC.NewConstructor( - TextEncoder, - .{ - .constructor = .{ .rfn = constructor }, - }, - .{}, - ); - - pub const Class = NewClass( - TextEncoder, - .{ - .name = "TextEncoder", - }, - .{ - .encode = .{ - .rfn = encode, - }, - .encodeInto = .{ - .rfn = encodeInto, - }, - }, - .{ - .encoding = .{ - .get = getEncoding, - .readOnly = true, - }, - }, - ); const utf8_string: string = "utf-8"; - pub fn getEncoding( - _: *TextEncoder, - ctx: js.JSContextRef, - _: js.JSValueRef, - _: js.JSStringRef, - _: js.ExceptionRef, - ) js.JSValueRef { - return ZigString.init(utf8_string).toValue(ctx.ptr()).asObjectRef(); - } - pub fn encode( - _: *TextEncoder, - ctx: js.JSContextRef, - _: js.JSObjectRef, - _: js.JSObjectRef, - args: []const js.JSValueRef, - exception: js.ExceptionRef, - ) js.JSValueRef { - var arguments: []const JSC.JSValue = @ptrCast([*]const JSC.JSValue, args.ptr)[0..args.len]; - - if (arguments.len < 1) { - return JSC.C.JSObjectMakeTypedArray(ctx, JSC.C.JSTypedArrayType.kJSTypedArrayTypeUint8Array, 0, exception); - } - - const value = arguments[0]; - - var zig_str = value.getZigString(ctx.ptr()); - - var array_buffer: ArrayBuffer = undefined; + pub export fn TextEncoder__encode( + globalThis: *JSGlobalObject, + zig_str: *const ZigString, + ) JSValue { + var ctx = globalThis.ref(); if (zig_str.is16Bit()) { var bytes = strings.toUTF8AllocWithType( default_allocator, @TypeOf(zig_str.utf16Slice()), zig_str.utf16Slice(), ) catch { - JSC.throwInvalidArguments("Out of memory", .{}, ctx, exception); - return null; + return JSC.toInvalidArguments("Out of memory", .{}, ctx); }; - array_buffer = ArrayBuffer.fromBytes(bytes, .Uint8Array); + return ArrayBuffer.fromBytes(bytes, .Uint8Array).toJS(ctx, null); } else { - var bytes = strings.allocateLatin1IntoUTF8(default_allocator, []const u8, zig_str.slice()) catch { - JSC.throwInvalidArguments("Out of memory", .{}, ctx, exception); - return null; - }; - - array_buffer = ArrayBuffer.fromBytes(bytes, .Uint8Array); + // latin1 always has the same length as utf-8 + // so we can use the Gigacage to allocate the buffer + var array = JSC.JSValue.createUninitializedUint8Array(ctx.ptr(), zig_str.len); + var buffer = array.asArrayBuffer(ctx.ptr()) orelse return JSC.toInvalidArguments("Out of memory", .{}, ctx); + const result = strings.copyLatin1IntoUTF8(buffer.slice(), []const u8, zig_str.slice()); + std.debug.assert(result.written == zig_str.len); + return array; } - return array_buffer.toJS(ctx, exception).asObjectRef(); + unreachable; } const read_key = ZigString.init("read"); const written_key = ZigString.init("written"); - pub fn encodeInto( - _: *TextEncoder, - ctx: js.JSContextRef, - _: js.JSObjectRef, - _: js.JSObjectRef, - args: []const js.JSValueRef, - exception: js.ExceptionRef, - ) js.JSValueRef { - var arguments: []const JSC.JSValue = @ptrCast([*]const JSC.JSValue, args.ptr)[0..args.len]; - - if (arguments.len < 2) { - JSC.throwInvalidArguments("TextEncoder.encodeInto expects (string, Uint8Array)", .{}, ctx, exception); - return null; - } - - const value = arguments[0]; - - const array_buffer = arguments[1].asArrayBuffer(ctx.ptr()) orelse { - JSC.throwInvalidArguments("TextEncoder.encodeInto expects a Uint8Array", .{}, ctx, exception); - return null; - }; - - var output = array_buffer.slice(); - const input = value.getZigString(ctx.ptr()); + pub export fn TextEncoder__encodeInto( + globalThis: *JSC.JSGlobalObject, + input: *const ZigString, + buf_ptr: [*]u8, + buf_len: usize, + ) JSC.JSValue { + var output = buf_ptr[0..buf_len]; var result: strings.EncodeIntoResult = strings.EncodeIntoResult{ .read = 0, .written = 0 }; if (input.is16Bit()) { const utf16_slice = input.utf16Slice(); @@ -159,19 +89,17 @@ pub const TextEncoder = struct { } else { result = strings.copyLatin1IntoUTF8(output, @TypeOf(input.slice()), input.slice()); } - return JSC.JSValue.createObject2(ctx.ptr(), &read_key, &written_key, JSValue.jsNumber(result.read), JSValue.jsNumber(result.written)).asObjectRef(); - } - - pub fn constructor( - ctx: js.JSContextRef, - _: js.JSObjectRef, - _: []const js.JSValueRef, - _: js.ExceptionRef, - ) js.JSObjectRef { - return TextEncoder.Class.make(ctx, &text_encoder); + return JSC.JSValue.createObject2(globalThis, &read_key, &written_key, JSValue.jsNumber(result.read), JSValue.jsNumber(result.written)); } }; +comptime { + if (!JSC.is_bindgen) { + _ = TextEncoder.TextEncoder__encode; + _ = TextEncoder.TextEncoder__encodeInto; + } +} + /// https://encoding.spec.whatwg.org/encodings.json pub const EncodingLabel = enum { @"UTF-8", diff --git a/src/js_parser.zig b/src/js_parser.zig index 89a3e82caf..4ddeba8964 100644 --- a/src/js_parser.zig +++ b/src/js_parser.zig @@ -2548,7 +2548,10 @@ pub const Parser = struct { // Auto-import & post-process JSX switch (comptime ParserType.jsx_transform_type) { .react => { - const jsx_filename_symbol = p.symbols.items[p.jsx_filename.ref.innerIndex()]; + const jsx_filename_symbol = if (p.options.jsx.development) + p.symbols.items[p.jsx_filename.ref.innerIndex()] + else + Symbol{ .original_name = "" }; { const jsx_symbol = p.symbols.items[p.jsx_runtime.ref.innerIndex()]; diff --git a/src/options.zig b/src/options.zig index 52352e3238..3f05174c85 100644 --- a/src/options.zig +++ b/src/options.zig @@ -914,10 +914,14 @@ pub const JSX = struct { pragma.package_name = parsePackageName(pragma.import_source); } else if (jsx.development) { pragma.import_source = Defaults.ImportSourceDev; - pragma.jsx = Defaults.JSXFunctionDev; pragma.package_name = "react"; } else { pragma.import_source = Defaults.ImportSource; + } + + if (jsx.development) { + pragma.jsx = Defaults.JSXFunctionDev; + } else { pragma.jsx = Defaults.JSXFunction; } diff --git a/src/string_immutable.zig b/src/string_immutable.zig index b27a0f8207..f1ffb83783 100644 --- a/src/string_immutable.zig +++ b/src/string_immutable.zig @@ -974,7 +974,7 @@ pub fn toUTF8AllocWithType(allocator: std.mem.Allocator, comptime Type: type, ut utf16_remaining = utf16_remaining[replacement.len..]; const count: usize = replacement.utf8Width(); - try list.ensureUnusedCapacity(i + count); + try list.ensureTotalCapacityPrecise(i + count + list.items.len + @floatToInt(usize, (@intToFloat(f64, @truncate(u52, utf16_remaining.len)) * 1.2))); list.items.len += i; copyU16IntoU8( @@ -992,12 +992,13 @@ pub fn toUTF8AllocWithType(allocator: std.mem.Allocator, comptime Type: type, ut ); } - try list.ensureUnusedCapacity(utf16_remaining.len); + try list.ensureTotalCapacityPrecise(utf16_remaining.len + list.items.len); const old_len = list.items.len; list.items.len += utf16_remaining.len; copyU16IntoU8(list.items[old_len..], Type, utf16_remaining); - return list.toOwnedSlice(); + // don't call toOwnedSlice() because our + return list.items; } pub const EncodeIntoResult = struct {