mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
ArrayBuffer support to ObjC TurboModules
Summary: Adds ArrayBuffer support to ObjC TurboModules, following the C++ ArrayBuffer PR ([`226ef2e`](https://github.com/facebook/react-native/commit/226ef2e7c5d1928d5696dc23efc1b8950ba00e37)). - Codegen support for `ArrayBufferTypeAnnotation` in ObjC module specs (`NSMutableData *` params/returns, new `ArrayBufferKind`) - JSI↔ObjC conversion wraps native-backed buffers zero-copy via `-[NSMutableData initWithBytesNoCopy:length:deallocator:]`; the deallocator retains the backing store so the bytes stay valid even if the `NSMutableData` escapes the call or the source ArrayBuffer is garbage-collected - JS-backed buffers are copied, which is safe on both the synchronous and asynchronous paths This PR is iOS-only; Android support follows in a separate PR. ## Changelog: [IOS] [ADDED] - Add ArrayBuffer support to ObjC TurboModules X-link: https://github.com/facebook/react-native/pull/56986 Reviewed By: javache Differential Revision: D106846249 Pulled By: christophpurrer fbshipit-source-id: 3393d5d6f31a1412f5d52328c90e51205aa6b153
This commit is contained in:
1 parent
a3582a9d19
commit
54b88d9dea
18 files changed
+570
-11
No files matched your search
Vendored
+7
-7
@@ -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(
|
||||
|
||||
+1
-1
@@ -2678,7 +2678,7 @@ const ARRAY_BUFFER_NATIVE_MODULE: SchemaType = {
|
||||
],
|
||||
},
|
||||
moduleName: 'SampleTurboModule',
|
||||
excludedPlatforms: ['iOS', 'android'],
|
||||
excludedPlatforms: ['android'],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
+28
@@ -100,6 +100,34 @@ Map {
|
||||
#import <vector>
|
||||
|
||||
|
||||
@protocol NativeSampleTurboModuleSpec <RCTBridgeModule, RCTTurboModule>
|
||||
|
||||
- (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
|
||||
",
|
||||
|
||||
+44
@@ -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<ObjCTurboModule&>(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<ObjCTurboModule&>(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<ObjCTurboModule&>(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<ObjCTurboModule&>(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
|
||||
",
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -31,6 +31,7 @@ enum TurboModuleMethodValueKind {
|
||||
ArrayKind,
|
||||
FunctionKind,
|
||||
PromiseKind,
|
||||
ArrayBufferKind,
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+49
@@ -11,6 +11,8 @@
|
||||
#import <hermes/hermes.h>
|
||||
#import <react/featureflags/ReactNativeFeatureFlags.h>
|
||||
|
||||
#import <vector>
|
||||
|
||||
#import <OCMock/OCMock.h>
|
||||
|
||||
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<uint8_t> 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<TestMutableBuffer>(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<const uint8_t *>(data.bytes), 0xAB);
|
||||
|
||||
// Independent copy: mutating the NSMutableData must not write through to the
|
||||
// source MutableBuffer.
|
||||
*static_cast<uint8_t *>(data.mutableBytes) = 0xCD;
|
||||
XCTAssertEqual(*buffer->data(), 0xAB, @"NSMutableData must not alias the source buffer");
|
||||
}
|
||||
|
||||
@end
|
||||
+60
-3
@@ -89,6 +89,37 @@ static std::vector<jsi::Value> 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<uint8_t *>(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<NSMutableDataBuffer>(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);
|
||||
|
||||
@@ -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 = "<group>"; };
|
||||
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 = "<group>"; };
|
||||
F1A0B1C23D4E5F6071829301 /* RCTTurboModuleArrayBufferTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RCTTurboModuleArrayBufferTests.mm; sourceTree = "<group>"; };
|
||||
/* 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 */,
|
||||
|
||||
@@ -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 <XCTest/XCTest.h>
|
||||
|
||||
#import <React/RCTBridgeModule.h>
|
||||
#import <ReactCommon/RCTTurboModule.h>
|
||||
#import <ReactCommon/TestCallInvoker.h>
|
||||
#import <hermes/hermes.h>
|
||||
|
||||
#import <list>
|
||||
#import <vector>
|
||||
|
||||
using namespace facebook::react;
|
||||
|
||||
namespace {
|
||||
|
||||
std::shared_ptr<facebook::jsi::Runtime> 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<uint8_t *>(data.mutableBytes);
|
||||
for (NSUInteger i = 0; i < size; ++i) {
|
||||
bytes[i] = static_cast<uint8_t>(i);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> bytesFromData(NSData *data)
|
||||
{
|
||||
if (data == nil) {
|
||||
return {};
|
||||
}
|
||||
|
||||
auto *bytes = static_cast<const uint8_t *>(data.bytes);
|
||||
return std::vector<uint8_t>(bytes, bytes + data.length);
|
||||
}
|
||||
|
||||
std::vector<uint8_t> bytesFromArrayBuffer(facebook::jsi::Runtime &runtime, const facebook::jsi::ArrayBuffer &buffer)
|
||||
{
|
||||
auto *bytes = buffer.data(runtime);
|
||||
return std::vector<uint8_t>(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<NativeMethodCallFunc> queue_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
@interface RCTTestArrayBufferTurboModule : NSObject <RCTBridgeModule>
|
||||
|
||||
@property (nonatomic, copy) NSData *lastReceivedPayload;
|
||||
|
||||
@end
|
||||
|
||||
@implementation RCTTestArrayBufferTurboModule
|
||||
|
||||
RCT_EXPORT_MODULE()
|
||||
|
||||
RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSMutableData *, testMethodWhichMutatesArrayBuffer : (NSMutableData *)buffer)
|
||||
{
|
||||
auto *bytes = static_cast<uint8_t *>(buffer.mutableBytes);
|
||||
for (NSUInteger i = 0; i < buffer.length; ++i) {
|
||||
bytes[i] = static_cast<uint8_t>((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<NSUInteger>(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<ImmediateNativeMethodCallInvoker>(),
|
||||
.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<QueueingNativeMethodCallInvoker>();
|
||||
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<QueueingNativeMethodCallInvoker>();
|
||||
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<QueueingNativeMethodCallInvoker>();
|
||||
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<detail::OwnedBytesBuffer>(std::vector<uint8_t>{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<TestCallInvoker>(*rt);
|
||||
auto *instance = [RCTTestArrayBufferTurboModule new];
|
||||
|
||||
ObjCTurboModule::InitParams params = {
|
||||
.moduleName = "TestModule",
|
||||
.instance = instance,
|
||||
.jsInvoker = jsInvoker,
|
||||
.nativeMethodCallInvoker = std::make_shared<ImmediateNativeMethodCallInvoker>(),
|
||||
.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<uint8_t> 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
|
||||
@@ -6577,6 +6577,7 @@ enum facebook::react::TransformOperationType : uint8_t {
|
||||
}
|
||||
|
||||
enum facebook::react::TurboModuleMethodValueKind {
|
||||
ArrayBufferKind,
|
||||
ArrayKind,
|
||||
BooleanKind,
|
||||
FunctionKind,
|
||||
|
||||
@@ -6391,6 +6391,7 @@ enum facebook::react::TransformOperationType : uint8_t {
|
||||
}
|
||||
|
||||
enum facebook::react::TurboModuleMethodValueKind {
|
||||
ArrayBufferKind,
|
||||
ArrayKind,
|
||||
BooleanKind,
|
||||
FunctionKind,
|
||||
|
||||
@@ -6568,6 +6568,7 @@ enum facebook::react::TransformOperationType : uint8_t {
|
||||
}
|
||||
|
||||
enum facebook::react::TurboModuleMethodValueKind {
|
||||
ArrayBufferKind,
|
||||
ArrayKind,
|
||||
BooleanKind,
|
||||
FunctionKind,
|
||||
|
||||
@@ -8767,6 +8767,7 @@ enum facebook::react::TransformOperationType : uint8_t {
|
||||
}
|
||||
|
||||
enum facebook::react::TurboModuleMethodValueKind {
|
||||
ArrayBufferKind,
|
||||
ArrayKind,
|
||||
BooleanKind,
|
||||
FunctionKind,
|
||||
|
||||
@@ -8609,6 +8609,7 @@ enum facebook::react::TransformOperationType : uint8_t {
|
||||
}
|
||||
|
||||
enum facebook::react::TurboModuleMethodValueKind {
|
||||
ArrayBufferKind,
|
||||
ArrayKind,
|
||||
BooleanKind,
|
||||
FunctionKind,
|
||||
|
||||
@@ -8758,6 +8758,7 @@ enum facebook::react::TransformOperationType : uint8_t {
|
||||
}
|
||||
|
||||
enum facebook::react::TurboModuleMethodValueKind {
|
||||
ArrayBufferKind,
|
||||
ArrayKind,
|
||||
BooleanKind,
|
||||
FunctionKind,
|
||||
|
||||
@@ -4914,6 +4914,7 @@ enum facebook::react::TransformOperationType : uint8_t {
|
||||
}
|
||||
|
||||
enum facebook::react::TurboModuleMethodValueKind {
|
||||
ArrayBufferKind,
|
||||
ArrayKind,
|
||||
BooleanKind,
|
||||
FunctionKind,
|
||||
|
||||
@@ -4768,6 +4768,7 @@ enum facebook::react::TransformOperationType : uint8_t {
|
||||
}
|
||||
|
||||
enum facebook::react::TurboModuleMethodValueKind {
|
||||
ArrayBufferKind,
|
||||
ArrayKind,
|
||||
BooleanKind,
|
||||
FunctionKind,
|
||||
|
||||
@@ -4905,6 +4905,7 @@ enum facebook::react::TransformOperationType : uint8_t {
|
||||
}
|
||||
|
||||
enum facebook::react::TurboModuleMethodValueKind {
|
||||
ArrayBufferKind,
|
||||
ArrayKind,
|
||||
BooleanKind,
|
||||
FunctionKind,
|
||||
|
||||
Reference in new issue
Block a user