diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js index ce1fdfef0c6..9f789ade20a 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js @@ -51,7 +51,8 @@ type ReturnJSType = | 'ObjectKind' | 'ArrayKind' | 'NumberKind' - | 'StringKind'; + | 'StringKind' + | 'ArrayBufferKind'; export type MethodSerializationOutput = Readonly<{ methodName: string, @@ -219,6 +220,9 @@ function getParamObjCType( */ return notStruct(wrapOptional('NSArray *', !nullable)); } + case 'ArrayBufferTypeAnnotation': { + return notStruct(wrapOptional('NSMutableData *', !nullable)); + } } const [structTypeAnnotation] = unwrapNullable( @@ -388,9 +392,7 @@ function getReturnObjCType( case 'GenericObjectTypeAnnotation': return wrapOptional('NSDictionary *', isRequired); case 'ArrayBufferTypeAnnotation': - throw new Error( - `Unsupported return type for ${methodName}: ArrayBuffer is only supported for C++ TurboModules.`, - ); + return wrapOptional('NSMutableData *', isRequired); default: typeAnnotation.type as 'MixedTypeAnnotation'; throw new Error( @@ -464,9 +466,7 @@ function getReturnJSType( throw new Error(`Unsupported union member types`); } case 'ArrayBufferTypeAnnotation': - throw new Error( - `Unsupported return type for ${methodName}: ArrayBuffer is only supported for C++ TurboModules.`, - ); + return 'ArrayBufferKind'; default: typeAnnotation.type as 'MixedTypeAnnotation'; throw new Error( diff --git a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js index 2b1db52e4ba..b3d3345244d 100644 --- a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js +++ b/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js @@ -2678,7 +2678,7 @@ const ARRAY_BUFFER_NATIVE_MODULE: SchemaType = { ], }, moduleName: 'SampleTurboModule', - excludedPlatforms: ['iOS', 'android'], + excludedPlatforms: ['android'], }, }, }; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap index 229db766e45..7612ea01b0f 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap @@ -100,6 +100,34 @@ Map { #import +@protocol NativeSampleTurboModuleSpec + +- (NSMutableData *)getArrayBuffer; +- (void)voidArrayBuffer:(NSMutableData *)arg; +- (void)voidNullableArrayBuffer:(NSMutableData * _Nullable)arg; +- (void)promiseArrayBuffer:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject; + +@end + +@interface NativeSampleTurboModuleSpecBase : NSObject { +@protected +facebook::react::EventEmitterCallback _eventEmitterCallback; +} +- (void)setEventEmitterCallback:(EventEmitterCallbackWrapper *)eventEmitterCallbackWrapper; + + +@end + +namespace facebook::react { + /** + * ObjC++ class for module 'NativeSampleTurboModule' + */ + class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public ObjCTurboModule { + public: + NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms); + }; +} // namespace facebook::react #endif // array_buffer_native_module_H ", diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap index e8ff005d586..c15e20ab0bf 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap @@ -58,6 +58,50 @@ Map { #import \\"array_buffer_native_module.h\\" +@implementation NativeSampleTurboModuleSpecBase + + +- (void)setEventEmitterCallback:(EventEmitterCallbackWrapper *)eventEmitterCallbackWrapper +{ + _eventEmitterCallback = std::move(eventEmitterCallbackWrapper->_eventEmitterCallback); +} +@end + + +namespace facebook::react { + + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getArrayBuffer(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { + return static_cast(turboModule).invokeObjCMethod(rt, ArrayBufferKind, \\"getArrayBuffer\\", @selector(getArrayBuffer), args, count); + } + + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_voidArrayBuffer(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { + return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidArrayBuffer\\", @selector(voidArrayBuffer:), args, count); + } + + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_voidNullableArrayBuffer(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { + return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"voidNullableArrayBuffer\\", @selector(voidNullableArrayBuffer:), args, count); + } + + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_promiseArrayBuffer(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { + return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"promiseArrayBuffer\\", @selector(promiseArrayBuffer:reject:), args, count); + } + + NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const ObjCTurboModule::InitParams ¶ms) + : ObjCTurboModule(params) { + + methodMap_[\\"getArrayBuffer\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getArrayBuffer}; + + + methodMap_[\\"voidArrayBuffer\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_voidArrayBuffer}; + + + methodMap_[\\"voidNullableArrayBuffer\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_voidNullableArrayBuffer}; + + + methodMap_[\\"promiseArrayBuffer\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_promiseArrayBuffer}; + + } +} // namespace facebook::react ", } `; diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h index f1d51678bf5..4626a550c17 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h +++ b/packages/react-native/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.h @@ -31,6 +31,7 @@ enum TurboModuleMethodValueKind { ArrayKind, FunctionKind, PromiseKind, + ArrayBufferKind, }; /** diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/iostests/RCTTurboModuleTests.mm b/packages/react-native/ReactCommon/react/nativemodule/core/iostests/RCTTurboModuleTests.mm index 3af870ffd3b..b94f70a89a8 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/iostests/RCTTurboModuleTests.mm +++ b/packages/react-native/ReactCommon/react/nativemodule/core/iostests/RCTTurboModuleTests.mm @@ -11,6 +11,8 @@ #import #import +#import + #import using namespace facebook::react; @@ -27,6 +29,23 @@ RCT_EXPORT_METHOD(testMethodWhichTakesObject : (id)object) {} @end +// Minimal concrete MutableBuffer that owns its bytes, used to observe lifetime. +class TestMutableBuffer : public facebook::jsi::MutableBuffer { + public: + explicit TestMutableBuffer(size_t size) : bytes_(size, 0) {} + size_t size() const override + { + return bytes_.size(); + } + uint8_t *data() override + { + return bytes_.data(); + } + + private: + std::vector bytes_; +}; + class StubNativeMethodCallInvoker : public NativeMethodCallInvoker { public: void invokeAsync(const std::string &methodName, NativeMethodCallFunc &&func) noexcept override @@ -104,4 +123,34 @@ class StubNativeMethodCallInvoker : public NativeMethodCallInvoker { OCMVerify(OCMTimes(1), [instance_ testMethodWhichTakesObject:nil]); } +// A JS ArrayBuffer converts to an NSMutableData that owns an independent copy of +// the bytes — NSMutableData cannot alias a foreign buffer, so the result stays +// valid and is safe to mutate after the source buffer is gone. This covers the +// ArrayBuffer-backed-by-native-MutableBuffer case, which is the one that could in +// principle have been aliased zero-copy. +- (void)testArrayBufferConvertsToIndependentNSMutableData +{ + constexpr size_t kBufferSize = 64 * 1024; + + auto hermesRuntime = facebook::hermes::makeHermesRuntime(); + facebook::jsi::Runtime *rt = hermesRuntime.get(); + + auto buffer = std::make_shared(kBufferSize); + *buffer->data() = 0xAB; + + facebook::jsi::ArrayBuffer arrayBuffer(*rt, buffer); + id converted = + TurboModuleConvertUtils::convertJSIValueToObjCObject(*rt, facebook::jsi::Value(*rt, arrayBuffer), nullptr); + + XCTAssertTrue([converted isKindOfClass:[NSMutableData class]]); + NSMutableData *data = (NSMutableData *)converted; + XCTAssertEqual(data.length, (NSUInteger)kBufferSize); + XCTAssertEqual(*static_cast(data.bytes), 0xAB); + + // Independent copy: mutating the NSMutableData must not write through to the + // source MutableBuffer. + *static_cast(data.mutableBytes) = 0xCD; + XCTAssertEqual(*buffer->data(), 0xAB, @"NSMutableData must not alias the source buffer"); +} + @end diff --git a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm index a1111f9c856..504060fc1b2 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm +++ b/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm @@ -89,6 +89,37 @@ static std::vector convertNSArrayToStdVector(jsi::Runtime &runtime, return result; } +static jsi::ArrayBuffer convertNSMutableDataToJSIArrayBuffer(jsi::Runtime &runtime, NSMutableData *value) +{ + class NSMutableDataBuffer final : public jsi::MutableBuffer { + public: + explicit NSMutableDataBuffer(NSMutableData *data) : data_(data) {} + + size_t size() const override + { + return data_.length; + } + + uint8_t *data() override + { + return static_cast(data_.mutableBytes); + } + + private: + NSMutableData *data_; + }; + + // A nil NSMutableData would silently yield a NULL `mutableBytes` pointer + // (ObjC nil-messaging) and corrupt the resulting ArrayBuffer. Substitute a + // fresh empty NSMutableData so the wrapped pointer is always well-defined. + if (value == nil) { + RCTLogWarn(@"convertNSMutableDataToJSIArrayBuffer: received nil NSMutableData; returning empty ArrayBuffer"); + value = [NSMutableData data]; + } + auto buffer = std::make_shared(value); + return {runtime, std::move(buffer)}; +} + jsi::Value convertObjCObjectToJSIValue(jsi::Runtime &runtime, id value) { if ([value isKindOfClass:[NSString class]]) { @@ -102,6 +133,8 @@ jsi::Value convertObjCObjectToJSIValue(jsi::Runtime &runtime, id value) return convertNSDictionaryToJSIObject(runtime, (NSDictionary *)value); } else if ([value isKindOfClass:[NSArray class]]) { return convertNSArrayToJSIArray(runtime, (NSArray *)value); + } else if ([value isKindOfClass:[NSMutableData class]]) { + return convertNSMutableDataToJSIArrayBuffer(runtime, (NSMutableData *)value); } else if (value == (id)kCFNull) { return jsi::Value::null(); } @@ -166,6 +199,18 @@ convertJSIFunctionToCallback(jsi::Runtime &rt, jsi::Function &&function, const s }; } +// Copy the ArrayBuffer's bytes into an NSMutableData. A zero-copy wrap is not +// possible here: NSMutableData needs its own resizable backing store and cannot +// alias a foreign buffer (even via initWithBytesNoCopy:length:deallocator:, which +// copies eagerly for the mutable subclass). Copying also makes the result safe to +// retain in a block, store, or dispatch to another thread, regardless of whether +// the bytes were owned by JS (valid only for this callstack) or by a native +// MutableBuffer (which the JS ArrayBuffer may GC concurrently). +static NSMutableData *convertJSIArrayBufferToNSMutableData(jsi::Runtime &rt, const jsi::ArrayBuffer &value) +{ + return [NSMutableData dataWithBytes:value.data(rt) length:value.size(rt)]; +} + id convertJSIValueToObjCObject( jsi::Runtime &runtime, const jsi::Value &value, @@ -195,6 +240,9 @@ id convertJSIValueToObjCObject( if (o.isFunction(runtime)) { return convertJSIFunctionToCallback(runtime, o.getFunction(runtime), jsInvoker); } + if (o.isArrayBuffer(runtime)) { + return convertJSIArrayBufferToNSMutableData(runtime, o.getArrayBuffer(runtime)); + } return convertJSIObjectToNSDictionary(runtime, o, jsInvoker, useNSNull); } @@ -522,6 +570,14 @@ jsi::Value ObjCTurboModule::convertReturnIdToJSIValue( returnValue = convertNSArrayToJSIArray(runtime, (NSArray *)result); break; } + case ArrayBufferKind: { + if (result != nil && ![result isKindOfClass:[NSMutableData class]]) { + RCTLogError(@"convertReturnIdToJSIValue: expected NSMutableData for ArrayBufferKind, got %@", [result class]); + break; + } + returnValue = convertNSMutableDataToJSIArrayBuffer(runtime, (NSMutableData *)result); + break; + } case FunctionKind: throw jsi::JSError(runtime, "convertReturnIdToJSIValue: FunctionKind is not supported yet."); case PromiseKind: @@ -605,7 +661,7 @@ void ObjCTurboModule::setInvocationArg( * JS type checking ensures the Objective C argument here is either a BOOL or NSNumber*. */ if (objCArgType == @encode(id)) { - id objCArg = [NSNumber numberWithBool:v]; + id objCArg = @(v); [inv setArgument:(void *)&objCArg atIndex:i + 2]; [retainedObjectsForInvocation addObject:objCArg]; } else { @@ -622,7 +678,7 @@ void ObjCTurboModule::setInvocationArg( * JS type checking ensures the Objective C argument here is either a double or NSNumber* or NSInteger. */ if (objCArgType == @encode(id)) { - id objCArg = [NSNumber numberWithDouble:v]; + id objCArg = @(v); [inv setArgument:(void *)&objCArg atIndex:i + 2]; [retainedObjectsForInvocation addObject:objCArg]; } else if (objCArgType == @encode(NSInteger)) { @@ -813,7 +869,8 @@ jsi::Value ObjCTurboModule::invokeObjCMethod( case StringKind: case ObjectKind: case ArrayKind: - case FunctionKind: { + case FunctionKind: + case ArrayBufferKind: { id result = performMethodInvocation(runtime, true, methodName, inv, retainedObjectsForInvocation); TurboModulePerfLogger::syncMethodCallReturnConversionStart(moduleName, methodName); returnValue = convertReturnIdToJSIValue(runtime, methodName, returnType, result); diff --git a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj index 898cd14e1ca..2f6e9c5ea8d 100644 --- a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj +++ b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj @@ -53,6 +53,7 @@ E7DB216722B2F69F005AC45F /* JavaScriptCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E7DB213022B2C649005AC45F /* JavaScriptCore.framework */; }; E7DB218C22B41FCD005AC45F /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E7DB218B22B41FCD005AC45F /* XCTest.framework */; }; F0D621C32BBB9E38005960AC /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = F0D621C22BBB9E38005960AC /* PrivacyInfo.xcprivacy */; }; + F1A0B1C23D4E5F6071829302 /* RCTTurboModuleArrayBufferTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = F1A0B1C23D4E5F6071829301 /* RCTTurboModuleArrayBufferTests.mm */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -156,6 +157,7 @@ E7DB215D22B2F3EC005AC45F /* RNTesterTestModule.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNTesterTestModule.m; sourceTree = ""; }; E7DB218B22B41FCD005AC45F /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = XCTest.framework; sourceTree = DEVELOPER_DIR; }; F0D621C22BBB9E38005960AC /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; + F1A0B1C23D4E5F6071829301 /* RCTTurboModuleArrayBufferTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RCTTurboModuleArrayBufferTests.mm; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -332,6 +334,7 @@ E7DB20AA22B2BAA3005AC45F /* RCTModuleInitNotificationRaceTests.m */, E7DB20B022B2BAA4005AC45F /* RCTModuleInitTests.m */, E7DB20CB22B2BAA5005AC45F /* RCTModuleMethodTests.mm */, + F1A0B1C23D4E5F6071829301 /* RCTTurboModuleArrayBufferTests.mm */, E7DB20CF22B2BAA5005AC45F /* RCTMultipartStreamReaderTests.m */, A975CA6B2C05EADE0043F72A /* RCTNetworkTaskTests.m */, E7DB20BE22B2BAA4005AC45F /* RCTNativeAnimatedNodesManagerTests.m */, @@ -746,6 +749,7 @@ E7DB20EC22B2BAA6005AC45F /* RCTMultipartStreamReaderTests.m in Sources */, E7DB20E022B2BAA6005AC45F /* RCTMethodArgumentTests.m in Sources */, E7DB20E822B2BAA6005AC45F /* RCTModuleMethodTests.mm in Sources */, + F1A0B1C23D4E5F6071829302 /* RCTTurboModuleArrayBufferTests.mm in Sources */, E7DB20E222B2BAA6005AC45F /* RCTGzipTests.m in Sources */, E7DB20ED22B2BAA6005AC45F /* RCTURLUtilsTests.m in Sources */, E7DB20D322B2BAA6005AC45F /* RCTBlobManagerTests.m in Sources */, diff --git a/packages/rn-tester/RNTesterUnitTests/RCTTurboModuleArrayBufferTests.mm b/packages/rn-tester/RNTesterUnitTests/RCTTurboModuleArrayBufferTests.mm new file mode 100644 index 00000000000..f890da05271 --- /dev/null +++ b/packages/rn-tester/RNTesterUnitTests/RCTTurboModuleArrayBufferTests.mm @@ -0,0 +1,367 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import + +#import +#import +#import +#import + +#import +#import + +using namespace facebook::react; + +namespace { + +std::shared_ptr createHermesRuntime(bool enableMicrotaskQueue = false) +{ + if (!enableMicrotaskQueue) { + return facebook::hermes::makeHermesRuntime(); + } + + return facebook::hermes::makeHermesRuntime(::hermes::vm::RuntimeConfig::Builder().withMicrotaskQueue(true).build()); +} + +NSMutableData *createIntegerSequenceData(NSUInteger size) +{ + NSMutableData *data = [NSMutableData dataWithLength:size]; + auto *bytes = static_cast(data.mutableBytes); + for (NSUInteger i = 0; i < size; ++i) { + bytes[i] = static_cast(i); + } + return data; +} + +std::vector bytesFromData(NSData *data) +{ + if (data == nil) { + return {}; + } + + auto *bytes = static_cast(data.bytes); + return std::vector(bytes, bytes + data.length); +} + +std::vector bytesFromArrayBuffer(facebook::jsi::Runtime &runtime, const facebook::jsi::ArrayBuffer &buffer) +{ + auto *bytes = buffer.data(runtime); + return std::vector(bytes, bytes + buffer.size(runtime)); +} + +class ImmediateNativeMethodCallInvoker final : public NativeMethodCallInvoker { + public: + void invokeAsync(const std::string &, NativeMethodCallFunc &&func) noexcept override + { + func(); + } + + void invokeSync(const std::string &, NativeMethodCallFunc &&func) noexcept override + { + func(); + } +}; + +class QueueingNativeMethodCallInvoker final : public NativeMethodCallInvoker { + public: + void invokeAsync(const std::string &, NativeMethodCallFunc &&func) noexcept override + { + queue_.push_back(std::move(func)); + } + + void invokeSync(const std::string &, NativeMethodCallFunc &&func) noexcept override + { + func(); + } + + void flushQueue() + { + while (!queue_.empty()) { + auto func = std::move(queue_.front()); + queue_.pop_front(); + func(); + } + } + + private: + std::list queue_; +}; + +} // namespace + +@interface RCTTestArrayBufferTurboModule : NSObject + +@property (nonatomic, copy) NSData *lastReceivedPayload; + +@end + +@implementation RCTTestArrayBufferTurboModule + +RCT_EXPORT_MODULE() + +RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSMutableData *, testMethodWhichMutatesArrayBuffer : (NSMutableData *)buffer) +{ + auto *bytes = static_cast(buffer.mutableBytes); + for (NSUInteger i = 0; i < buffer.length; ++i) { + bytes[i] = static_cast((i + 1) * 10); + } + return buffer; +} + +RCT_EXPORT_METHOD(testMethodWhichStoresArrayBuffer : (NSMutableData *)payload) +{ + self.lastReceivedPayload = [payload copy]; +} + +RCT_EXPORT_METHOD(testMethodWhichStoresNestedArrayBuffer : (NSDictionary *)payload) +{ + NSDictionary *nestedPayload = payload[@"nested"]; + self.lastReceivedPayload = [nestedPayload[@"buffer"] copy]; +} + +RCT_EXPORT_METHOD( + testMethodWhichReturnsArrayBuffer : (double)size resolve : (RCTPromiseResolveBlock) + resolve reject : (RCTPromiseRejectBlock)reject) +{ + if (resolve == nil || reject == nil) { + return; + } + + resolve(createIntegerSequenceData(static_cast(size))); +} + +@end + +@interface RCTTurboModuleArrayBufferTests : XCTestCase + +@end + +@implementation RCTTurboModuleArrayBufferTests + +- (void)testSyncArrayBufferRoundTrip +{ + auto hermesRuntime = createHermesRuntime(); + facebook::jsi::Runtime *rt = hermesRuntime.get(); + auto *instance = [RCTTestArrayBufferTurboModule new]; + + ObjCTurboModule::InitParams params = { + .moduleName = "TestModule", + .instance = instance, + .jsInvoker = nullptr, + .nativeMethodCallInvoker = std::make_shared(), + .isSyncModule = false, + }; + ObjCTurboModule module(params); + + auto sourceBuffer = rt->global() + .getPropertyAsFunction(*rt, "eval") + .call(*rt, "new Uint8Array([1, 2, 3]).buffer") + .asObject(*rt) + .getArrayBuffer(*rt); + facebook::jsi::Value args[1] = {facebook::jsi::Value(*rt, sourceBuffer)}; + + auto result = module.invokeObjCMethod( + *rt, + ArrayBufferKind, + "testMethodWhichMutatesArrayBuffer", + @selector(testMethodWhichMutatesArrayBuffer:), + args, + 1); + + XCTAssertTrue(result.isObject()); + XCTAssertTrue(result.asObject(*rt).isArrayBuffer(*rt)); + + auto returnedBuffer = result.asObject(*rt).getArrayBuffer(*rt); + auto returnedBytes = bytesFromArrayBuffer(*rt, returnedBuffer); + XCTAssertEqual(returnedBytes.size(), 3u); + XCTAssertEqual(returnedBytes[0], 10); + XCTAssertEqual(returnedBytes[1], 20); + XCTAssertEqual(returnedBytes[2], 30); +} + +- (void)testAsyncJSBackedArrayBufferIsCopied +{ + auto hermesRuntime = createHermesRuntime(); + facebook::jsi::Runtime *rt = hermesRuntime.get(); + auto nativeInvoker = std::make_shared(); + auto *instance = [RCTTestArrayBufferTurboModule new]; + + ObjCTurboModule::InitParams params = { + .moduleName = "TestModule", + .instance = instance, + .jsInvoker = nullptr, + .nativeMethodCallInvoker = nativeInvoker, + .isSyncModule = false, + }; + ObjCTurboModule module(params); + + auto sourceBuffer = rt->global() + .getPropertyAsFunction(*rt, "eval") + .call(*rt, "new Uint8Array([1, 2, 3]).buffer") + .asObject(*rt) + .getArrayBuffer(*rt); + facebook::jsi::Value args[1] = {facebook::jsi::Value(*rt, sourceBuffer)}; + + module.invokeObjCMethod( + *rt, VoidKind, "testMethodWhichStoresArrayBuffer", @selector(testMethodWhichStoresArrayBuffer:), args, 1); + + auto *sourceBytes = sourceBuffer.data(*rt); + sourceBytes[0] = 9; + sourceBytes[1] = 8; + sourceBytes[2] = 7; + + nativeInvoker->flushQueue(); + + auto receivedBytes = bytesFromData(instance.lastReceivedPayload); + XCTAssertEqual(receivedBytes.size(), 3u); + XCTAssertEqual(receivedBytes[0], 1); + XCTAssertEqual(receivedBytes[1], 2); + XCTAssertEqual(receivedBytes[2], 3); +} + +- (void)testAsyncNestedJSBackedArrayBufferIsCopied +{ + auto hermesRuntime = createHermesRuntime(); + facebook::jsi::Runtime *rt = hermesRuntime.get(); + auto nativeInvoker = std::make_shared(); + auto *instance = [RCTTestArrayBufferTurboModule new]; + + ObjCTurboModule::InitParams params = { + .moduleName = "TestModule", + .instance = instance, + .jsInvoker = nullptr, + .nativeMethodCallInvoker = nativeInvoker, + .isSyncModule = false, + }; + ObjCTurboModule module(params); + + auto sourceObject = rt->global() + .getPropertyAsFunction(*rt, "eval") + .call(*rt, "({nested: {buffer: new Uint8Array([1, 2, 3]).buffer}})") + .asObject(*rt); + auto sourceBuffer = sourceObject.getProperty(*rt, "nested") + .asObject(*rt) + .getProperty(*rt, "buffer") + .asObject(*rt) + .getArrayBuffer(*rt); + facebook::jsi::Value args[1] = {facebook::jsi::Value(*rt, sourceObject)}; + + module.invokeObjCMethod( + *rt, + VoidKind, + "testMethodWhichStoresNestedArrayBuffer", + @selector(testMethodWhichStoresNestedArrayBuffer:), + args, + 1); + + auto *sourceBytes = sourceBuffer.data(*rt); + sourceBytes[0] = 9; + sourceBytes[1] = 8; + sourceBytes[2] = 7; + + nativeInvoker->flushQueue(); + + auto receivedBytes = bytesFromData(instance.lastReceivedPayload); + XCTAssertEqual(receivedBytes.size(), 3u); + XCTAssertEqual(receivedBytes[0], 1); + XCTAssertEqual(receivedBytes[1], 2); + XCTAssertEqual(receivedBytes[2], 3); +} + +- (void)testAsyncNativeBackedArrayBufferRetainsBackingStore +{ + auto hermesRuntime = createHermesRuntime(); + facebook::jsi::Runtime *rt = hermesRuntime.get(); + auto nativeInvoker = std::make_shared(); + auto *instance = [RCTTestArrayBufferTurboModule new]; + + ObjCTurboModule::InitParams params = { + .moduleName = "TestModule", + .instance = instance, + .jsInvoker = nullptr, + .nativeMethodCallInvoker = nativeInvoker, + .isSyncModule = false, + }; + ObjCTurboModule module(params); + + facebook::jsi::Value args[1] = {facebook::jsi::Value::undefined()}; + { + auto nativeBuffer = std::make_shared(std::vector{4, 5, 6, 7}); + auto sourceBuffer = facebook::jsi::ArrayBuffer(*rt, nativeBuffer); + args[0] = facebook::jsi::Value(*rt, sourceBuffer); + } + + module.invokeObjCMethod( + *rt, VoidKind, "testMethodWhichStoresArrayBuffer", @selector(testMethodWhichStoresArrayBuffer:), args, 1); + args[0] = facebook::jsi::Value::undefined(); + + nativeInvoker->flushQueue(); + + auto receivedBytes = bytesFromData(instance.lastReceivedPayload); + XCTAssertEqual(receivedBytes.size(), 4u); + XCTAssertEqual(receivedBytes[0], 4); + XCTAssertEqual(receivedBytes[1], 5); + XCTAssertEqual(receivedBytes[2], 6); + XCTAssertEqual(receivedBytes[3], 7); +} + +- (void)testPromiseResolvesArrayBuffer +{ + auto hermesRuntime = createHermesRuntime(true); + facebook::jsi::Runtime *rt = hermesRuntime.get(); + auto jsInvoker = std::make_shared(*rt); + auto *instance = [RCTTestArrayBufferTurboModule new]; + + ObjCTurboModule::InitParams params = { + .moduleName = "TestModule", + .instance = instance, + .jsInvoker = jsInvoker, + .nativeMethodCallInvoker = std::make_shared(), + .isSyncModule = false, + }; + ObjCTurboModule module(params); + + facebook::jsi::Value args[1] = {facebook::jsi::Value(4.0)}; + auto promiseValue = module.invokeObjCMethod( + *rt, + PromiseKind, + "testMethodWhichReturnsArrayBuffer", + @selector(testMethodWhichReturnsArrayBuffer:resolve:reject:), + args, + 1); + + auto promise = promiseValue.asObject(*rt); + auto then = promise.getPropertyAsFunction(*rt, "then"); + + std::vector resolvedBytes; + auto onResolved = facebook::jsi::Function::createFromHostFunction( + *rt, + facebook::jsi::PropNameID::forAscii(*rt, "onResolved"), + 1, + [&resolvedBytes]( + facebook::jsi::Runtime &runtime, + const facebook::jsi::Value &, + const facebook::jsi::Value *callbackArgs, + size_t count) -> facebook::jsi::Value { + if (count == 1 && callbackArgs[0].isObject() && callbackArgs[0].asObject(runtime).isArrayBuffer(runtime)) { + resolvedBytes = bytesFromArrayBuffer(runtime, callbackArgs[0].asObject(runtime).getArrayBuffer(runtime)); + } + return facebook::jsi::Value::undefined(); + }); + then.callWithThis(*rt, promise, onResolved); + + jsInvoker->flushQueue(); + + XCTAssertEqual(resolvedBytes.size(), 4u); + XCTAssertEqual(resolvedBytes[0], 0); + XCTAssertEqual(resolvedBytes[1], 1); + XCTAssertEqual(resolvedBytes[2], 2); + XCTAssertEqual(resolvedBytes[3], 3); +} + +@end diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api index 4a5ea93ebca..8e829c46bde 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api @@ -6577,6 +6577,7 @@ enum facebook::react::TransformOperationType : uint8_t { } enum facebook::react::TurboModuleMethodValueKind { + ArrayBufferKind, ArrayKind, BooleanKind, FunctionKind, diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api index 6e821b751f6..68888450c51 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api @@ -6391,6 +6391,7 @@ enum facebook::react::TransformOperationType : uint8_t { } enum facebook::react::TurboModuleMethodValueKind { + ArrayBufferKind, ArrayKind, BooleanKind, FunctionKind, diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api index 77a90677d4c..14571543b72 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api @@ -6568,6 +6568,7 @@ enum facebook::react::TransformOperationType : uint8_t { } enum facebook::react::TurboModuleMethodValueKind { + ArrayBufferKind, ArrayKind, BooleanKind, FunctionKind, diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index cb3c73c37a1..1eed958ecd5 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -8767,6 +8767,7 @@ enum facebook::react::TransformOperationType : uint8_t { } enum facebook::react::TurboModuleMethodValueKind { + ArrayBufferKind, ArrayKind, BooleanKind, FunctionKind, diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index 87d6ca7aa0d..d29785710d5 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -8609,6 +8609,7 @@ enum facebook::react::TransformOperationType : uint8_t { } enum facebook::react::TurboModuleMethodValueKind { + ArrayBufferKind, ArrayKind, BooleanKind, FunctionKind, diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index cff79303f84..4c5d3b6c1d8 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -8758,6 +8758,7 @@ enum facebook::react::TransformOperationType : uint8_t { } enum facebook::react::TurboModuleMethodValueKind { + ArrayBufferKind, ArrayKind, BooleanKind, FunctionKind, diff --git a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api index 87aaa9ae289..e040adc8b61 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api @@ -4914,6 +4914,7 @@ enum facebook::react::TransformOperationType : uint8_t { } enum facebook::react::TurboModuleMethodValueKind { + ArrayBufferKind, ArrayKind, BooleanKind, FunctionKind, diff --git a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api index ed97d3fdcb8..42992e00eba 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api @@ -4768,6 +4768,7 @@ enum facebook::react::TransformOperationType : uint8_t { } enum facebook::react::TurboModuleMethodValueKind { + ArrayBufferKind, ArrayKind, BooleanKind, FunctionKind, diff --git a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api index 9a6ba873336..c56d1d911a2 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api @@ -4905,6 +4905,7 @@ enum facebook::react::TransformOperationType : uint8_t { } enum facebook::react::TurboModuleMethodValueKind { + ArrayBufferKind, ArrayKind, BooleanKind, FunctionKind,