mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
ArrayBuffer support to Java TurboModules
Summary: Changelog: [ANDROID] [ADDED] - Add ArrayBuffer support to Java TurboModules - Codegen: ArrayBufferTypeAnnotation → ByteBuffer / ArrayBufferKind / Ljava/nio/ByteBuffer; in GenerateModuleJavaSpec and GenerateModuleJniCpp. Guard in Utils.js rejects Promise<ArrayBuffer> on Android at codegen time — drops async return to avoid CxxCallbackImpl.kt / JCallback / PromiseImpl.kt changes. - Runtime: New JByteBufferMutableBuffer.h — jsi::MutableBuffer wrapping global_ref<JByteBuffer> direct ByteBuffer, holds Java object alive for JS ArrayBuffer lifetime; dtor uses ThreadScope to attach JNI thread (Hermes GC finalizes off-thread). Zero-copy native→JS return mirrors iOS NSMutableDataBuffer. Args JS→Java always copied into Java-owned direct ByteBuffer via allocateDirect+memcpy (mirrors iOS NSData copy), no sync/async branching — safe to retain/dispatch past GC. - No changes to CxxCallbackImpl.kt, JCallback, PromiseImpl.kt. Nested ArrayBuffers still via folly::dynamic, deferred like ObjC/C++. - Samples: NativeSampleTurboModule.js spec, SampleTurboModule.kt (getArrayBuffer/ createNativeBuffer/ processAsyncBuffer), RCTSampleTurboModule.mm. (NSData param / NSMutableData return), RNTester UI SampleTurboModuleExample.js. X-link: https://github.com/facebook/react-native/pull/57062 Reviewed By: javache Differential Revision: D107411163 Pulled By: christophpurrer fbshipit-source-id: 67cc5da796a87f6918f0382debc5c5594f76661b
This commit is contained in:
1 parent
3f3425e246
commit
5fb3ebce1a
26 files changed
+707
-28
No files matched your search
+16
-10
@@ -25,7 +25,11 @@ import type {AliasResolver} from './Utils';
|
||||
const {unwrapNullable} = require('../../parsers/parsers-commons');
|
||||
const {wrapOptional} = require('../TypeUtils/Java');
|
||||
const {parseValidUnionType, toPascalCase} = require('../Utils');
|
||||
const {createAliasResolver, getModules} = require('./Utils');
|
||||
const {
|
||||
createAliasResolver,
|
||||
getModules,
|
||||
throwIfUnsupportedPromiseArrayBuffer,
|
||||
} = require('./Utils');
|
||||
|
||||
type FilesOutput = Map<string, string>;
|
||||
|
||||
@@ -170,6 +174,7 @@ function translateEventEmitterTypeToJavaType(
|
||||
case 'FloatTypeAnnotation':
|
||||
case 'Int32TypeAnnotation':
|
||||
case 'VoidTypeAnnotation':
|
||||
case 'ArrayBufferTypeAnnotation':
|
||||
// TODO: Add support for these types
|
||||
throw new Error(
|
||||
`Unsupported eventType for ${eventEmitter.name}. Found: ${eventEmitter.typeAnnotation.typeAnnotation.type}`,
|
||||
@@ -268,9 +273,8 @@ function translateFunctionParamToJavaType(
|
||||
imports.add('com.facebook.react.bridge.Callback');
|
||||
return wrapOptional('Callback', isRequired);
|
||||
case 'ArrayBufferTypeAnnotation':
|
||||
throw new Error(
|
||||
`${createErrorMessage(realTypeAnnotation.type)} ArrayBuffer is only supported for C++ TurboModules.`,
|
||||
);
|
||||
imports.add('java.nio.ByteBuffer');
|
||||
return wrapOptional('ByteBuffer', isRequired);
|
||||
default:
|
||||
realTypeAnnotation.type as 'MixedTypeAnnotation';
|
||||
throw new Error(createErrorMessage(realTypeAnnotation.type));
|
||||
@@ -366,9 +370,8 @@ function translateFunctionReturnTypeToJavaType(
|
||||
imports.add('com.facebook.react.bridge.WritableArray');
|
||||
return wrapOptional('WritableArray', isRequired);
|
||||
case 'ArrayBufferTypeAnnotation':
|
||||
throw new Error(
|
||||
`${createErrorMessage(realTypeAnnotation.type)} ArrayBuffer is only supported for C++ TurboModules.`,
|
||||
);
|
||||
imports.add('java.nio.ByteBuffer');
|
||||
return wrapOptional('ByteBuffer', isRequired);
|
||||
default:
|
||||
realTypeAnnotation.type as 'MixedTypeAnnotation';
|
||||
throw new Error(createErrorMessage(realTypeAnnotation.type));
|
||||
@@ -452,9 +455,7 @@ function getFalsyReturnStatementFromReturnType(
|
||||
case 'ArrayTypeAnnotation':
|
||||
return 'return null;';
|
||||
case 'ArrayBufferTypeAnnotation':
|
||||
throw new Error(
|
||||
`${createErrorMessage(realTypeAnnotation.type)} ArrayBuffer is only supported for C++ TurboModules.`,
|
||||
);
|
||||
return 'return null;';
|
||||
default:
|
||||
realTypeAnnotation.type as 'MixedTypeAnnotation';
|
||||
throw new Error(createErrorMessage(realTypeAnnotation.type));
|
||||
@@ -589,6 +590,11 @@ module.exports = {
|
||||
method.typeAnnotation,
|
||||
);
|
||||
|
||||
throwIfUnsupportedPromiseArrayBuffer(
|
||||
method.name,
|
||||
methodTypeAnnotation.returnTypeAnnotation,
|
||||
);
|
||||
|
||||
// Handle return type
|
||||
const translatedReturnType = translateFunctionReturnTypeToJavaType(
|
||||
methodTypeAnnotation.returnTypeAnnotation,
|
||||
|
||||
+12
-5
@@ -24,7 +24,11 @@ import type {AliasResolver} from './Utils';
|
||||
|
||||
const {unwrapNullable} = require('../../parsers/parsers-commons');
|
||||
const {parseValidUnionType} = require('../Utils');
|
||||
const {createAliasResolver, getModules} = require('./Utils');
|
||||
const {
|
||||
createAliasResolver,
|
||||
getModules,
|
||||
throwIfUnsupportedPromiseArrayBuffer,
|
||||
} = require('./Utils');
|
||||
|
||||
type FilesOutput = Map<string, string>;
|
||||
|
||||
@@ -35,7 +39,8 @@ type JSReturnType =
|
||||
| 'NumberKind'
|
||||
| 'PromiseKind'
|
||||
| 'ObjectKind'
|
||||
| 'ArrayKind';
|
||||
| 'ArrayKind'
|
||||
| 'ArrayBufferKind';
|
||||
|
||||
const HostFunctionTemplate = ({
|
||||
hasteModuleName,
|
||||
@@ -217,7 +222,7 @@ function translateReturnTypeToKind(
|
||||
case 'ArrayTypeAnnotation':
|
||||
return 'ArrayKind';
|
||||
case 'ArrayBufferTypeAnnotation':
|
||||
throw new Error('ArrayBuffer is only supported for C++ TurboModules.');
|
||||
return 'ArrayBufferKind';
|
||||
default:
|
||||
realTypeAnnotation.type as 'MixedTypeAnnotation';
|
||||
throw new Error(
|
||||
@@ -306,7 +311,7 @@ function translateParamTypeToJniType(
|
||||
case 'FunctionTypeAnnotation':
|
||||
return 'Lcom/facebook/react/bridge/Callback;';
|
||||
case 'ArrayBufferTypeAnnotation':
|
||||
throw new Error('ArrayBuffer is only supported for C++ TurboModules.');
|
||||
return 'Ljava/nio/ByteBuffer;';
|
||||
default:
|
||||
realTypeAnnotation.type as 'MixedTypeAnnotation';
|
||||
throw new Error(
|
||||
@@ -392,7 +397,7 @@ function translateReturnTypeToJniType(
|
||||
case 'ArrayTypeAnnotation':
|
||||
return 'Lcom/facebook/react/bridge/WritableArray;';
|
||||
case 'ArrayBufferTypeAnnotation':
|
||||
throw new Error('ArrayBuffer is only supported for C++ TurboModules.');
|
||||
return 'Ljava/nio/ByteBuffer;';
|
||||
default:
|
||||
realTypeAnnotation.type as 'MixedTypeAnnotation';
|
||||
throw new Error(
|
||||
@@ -448,6 +453,8 @@ function translateMethodForImplementation(
|
||||
unwrapNullable<NativeModuleFunctionTypeAnnotation>(property.typeAnnotation);
|
||||
const {returnTypeAnnotation} = propertyTypeAnnotation;
|
||||
|
||||
throwIfUnsupportedPromiseArrayBuffer(property.name, returnTypeAnnotation);
|
||||
|
||||
if (
|
||||
property.name === 'getConstants' &&
|
||||
returnTypeAnnotation.type === 'ObjectTypeAnnotation' &&
|
||||
|
||||
Vendored
+6
@@ -26,6 +26,7 @@ const {
|
||||
} = require('../../../parsers/parsers-commons');
|
||||
const {wrapOptional} = require('../../TypeUtils/Objective-C');
|
||||
const {capitalize, parseValidUnionType} = require('../../Utils');
|
||||
const {throwIfUnsupportedPromiseArrayBuffer} = require('../Utils');
|
||||
const {getNamespacedStructName} = require('./Utils');
|
||||
const invariant = require('invariant');
|
||||
|
||||
@@ -103,6 +104,11 @@ function serializeMethod(
|
||||
}
|
||||
});
|
||||
|
||||
throwIfUnsupportedPromiseArrayBuffer(
|
||||
methodName,
|
||||
propertyTypeAnnotation.returnTypeAnnotation,
|
||||
);
|
||||
|
||||
// Unwrap returnTypeAnnotation, so we check if the return type is Promise
|
||||
// TODO(T76719514): Disallow nullable PromiseTypeAnnotations
|
||||
const [returnTypeAnnotation] = unwrapNullable(
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
import type {
|
||||
NativeModuleAliasMap,
|
||||
NativeModuleObjectTypeAnnotation,
|
||||
NativeModuleReturnTypeAnnotation,
|
||||
NativeModuleSchema,
|
||||
NativeModuleTypeAnnotation,
|
||||
Nullable,
|
||||
@@ -77,9 +78,50 @@ function isArrayRecursiveMember(
|
||||
);
|
||||
}
|
||||
|
||||
// Platform-native (Java/Kotlin and ObjC) TurboModules copy ArrayBuffer
|
||||
// arguments and return ArrayBuffers zero-copy from synchronous methods, but
|
||||
// `Promise<ArrayBuffer>` is not part of their contract.
|
||||
//
|
||||
// On Android it cannot work: the resolve path serializes through
|
||||
// folly::dynamic, which cannot carry raw bytes. On iOS the resolve path is a
|
||||
// direct ObjC->jsi conversion that would in fact produce an ArrayBuffer for an
|
||||
// NSMutableData, so the limitation there is not technical — the guard is
|
||||
// applied to ObjC as well to keep one cross-platform contract, so a spec that
|
||||
// compiles for iOS cannot fail to build for Android.
|
||||
//
|
||||
// Reject `Promise<ArrayBuffer>` at codegen time for both native platforms so
|
||||
// the unsupported case surfaces as a build error rather than a runtime failure
|
||||
// or a silent iOS/Android divergence.
|
||||
function throwIfUnsupportedPromiseArrayBuffer(
|
||||
methodName: string,
|
||||
nullableReturnTypeAnnotation: Nullable<NativeModuleReturnTypeAnnotation>,
|
||||
): void {
|
||||
const [returnTypeAnnotation] =
|
||||
unwrapNullable<NativeModuleReturnTypeAnnotation>(
|
||||
nullableReturnTypeAnnotation,
|
||||
);
|
||||
if (returnTypeAnnotation.type !== 'PromiseTypeAnnotation') {
|
||||
return;
|
||||
}
|
||||
let elementType = returnTypeAnnotation.elementType;
|
||||
if (elementType.type === 'NullableTypeAnnotation') {
|
||||
elementType = elementType.typeAnnotation;
|
||||
}
|
||||
if (elementType.type === 'ArrayBufferTypeAnnotation') {
|
||||
throw new Error(
|
||||
`Unsupported return type for method "${methodName}": Promise<ArrayBuffer> is not ` +
|
||||
'supported for Android (Java/Kotlin) or iOS (ObjC) TurboModules. Use a C++ ' +
|
||||
'(Cxx) TurboModule, return the ArrayBuffer from a synchronous method, or resolve ' +
|
||||
'the Promise with a different type. ArrayBuffer is still supported as a method ' +
|
||||
'argument and as a synchronous return value on all platforms.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createAliasResolver,
|
||||
getModules,
|
||||
isDirectRecursiveMember,
|
||||
isArrayRecursiveMember,
|
||||
throwIfUnsupportedPromiseArrayBuffer,
|
||||
};
|
||||
+21
-1
@@ -2661,6 +2661,25 @@ const ARRAY_BUFFER_NATIVE_MODULE: SchemaType = {
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
moduleName: 'SampleTurboModule',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Promise<ArrayBuffer> is only supported by C++ (Cxx) TurboModules (see
|
||||
// throwIfUnsupportedPromiseArrayBuffer), so this fixture is excluded on both
|
||||
// Android and iOS. It keeps C++ codegen coverage for the async-return case.
|
||||
const ARRAY_BUFFER_PROMISE_NATIVE_MODULE: SchemaType = {
|
||||
modules: {
|
||||
NativeSampleTurboModule: {
|
||||
type: 'NativeModule',
|
||||
aliasMap: {},
|
||||
enumMap: {},
|
||||
spec: {
|
||||
eventEmitters: [],
|
||||
methods: [
|
||||
{
|
||||
name: 'promiseArrayBuffer',
|
||||
optional: false,
|
||||
@@ -2678,7 +2697,7 @@ const ARRAY_BUFFER_NATIVE_MODULE: SchemaType = {
|
||||
],
|
||||
},
|
||||
moduleName: 'SampleTurboModule',
|
||||
excludedPlatforms: ['android'],
|
||||
excludedPlatforms: ['android', 'iOS'],
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -2877,6 +2896,7 @@ const STRING_LITERALS: SchemaType = {
|
||||
|
||||
module.exports = {
|
||||
array_buffer_native_module: ARRAY_BUFFER_NATIVE_MODULE,
|
||||
array_buffer_promise_native_module: ARRAY_BUFFER_PROMISE_NATIVE_MODULE,
|
||||
complex_objects: COMPLEX_OBJECTS,
|
||||
two_modules_different_files: TWO_MODULES_DIFFERENT_FILES,
|
||||
empty_native_modules: EMPTY_NATIVE_MODULES,
|
||||
|
||||
Vendored
+40
@@ -10,6 +10,8 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
import type {SchemaType} from '../../../CodegenSchema';
|
||||
|
||||
const fixtures = require('../__test_fixtures__/fixtures.js');
|
||||
const generator = require('../GenerateModuleObjCpp');
|
||||
|
||||
@@ -31,4 +33,42 @@ describe('GenerateModuleHObjCpp', () => {
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
it('throws for a method returning Promise<ArrayBuffer> (unsupported on iOS)', () => {
|
||||
const schema: SchemaType = {
|
||||
modules: {
|
||||
NativeSampleTurboModule: {
|
||||
type: 'NativeModule',
|
||||
aliasMap: {},
|
||||
enumMap: {},
|
||||
spec: {
|
||||
eventEmitters: [],
|
||||
methods: [
|
||||
{
|
||||
name: 'getAsyncBuffer',
|
||||
optional: false,
|
||||
typeAnnotation: {
|
||||
type: 'FunctionTypeAnnotation',
|
||||
returnTypeAnnotation: {
|
||||
type: 'PromiseTypeAnnotation',
|
||||
elementType: {type: 'ArrayBufferTypeAnnotation'},
|
||||
},
|
||||
params: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
moduleName: 'SampleTurboModule',
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(() =>
|
||||
generator.generate(
|
||||
'array_buffer_promise_throws',
|
||||
schema,
|
||||
'com.facebook.fbreact.specs',
|
||||
false,
|
||||
),
|
||||
).toThrow(/Promise<ArrayBuffer> is not supported/);
|
||||
});
|
||||
});
|
||||
Vendored
+35
@@ -10,6 +10,8 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
import type {SchemaType} from '../../../CodegenSchema';
|
||||
|
||||
const fixtures = require('../__test_fixtures__/fixtures.js');
|
||||
const generator = require('../GenerateModuleJavaSpec.js');
|
||||
|
||||
@@ -29,4 +31,37 @@ describe('GenerateModuleJavaSpec', () => {
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
it('throws for a method returning Promise<ArrayBuffer> (unsupported on Android)', () => {
|
||||
const schema: SchemaType = {
|
||||
modules: {
|
||||
NativeSampleTurboModule: {
|
||||
type: 'NativeModule',
|
||||
aliasMap: {},
|
||||
enumMap: {},
|
||||
spec: {
|
||||
eventEmitters: [],
|
||||
methods: [
|
||||
{
|
||||
name: 'getAsyncBuffer',
|
||||
optional: false,
|
||||
typeAnnotation: {
|
||||
type: 'FunctionTypeAnnotation',
|
||||
returnTypeAnnotation: {
|
||||
type: 'PromiseTypeAnnotation',
|
||||
elementType: {type: 'ArrayBufferTypeAnnotation'},
|
||||
},
|
||||
params: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
moduleName: 'SampleTurboModule',
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(() =>
|
||||
generator.generate('array_buffer_promise_throws', schema),
|
||||
).toThrow(/Promise<ArrayBuffer> is not supported/);
|
||||
});
|
||||
});
|
||||
Vendored
+39
@@ -10,6 +10,8 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
import type {SchemaType} from '../../../CodegenSchema';
|
||||
|
||||
const fixtures = require('../__test_fixtures__/fixtures.js');
|
||||
const generator = require('../GenerateModuleJniCpp.js');
|
||||
|
||||
@@ -29,4 +31,41 @@ describe('GenerateModuleJniCpp', () => {
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
it('throws for a method returning Promise<ArrayBuffer> (unsupported on Android)', () => {
|
||||
const schema: SchemaType = {
|
||||
modules: {
|
||||
NativeSampleTurboModule: {
|
||||
type: 'NativeModule',
|
||||
aliasMap: {},
|
||||
enumMap: {},
|
||||
spec: {
|
||||
eventEmitters: [],
|
||||
methods: [
|
||||
{
|
||||
name: 'getAsyncBuffer',
|
||||
optional: false,
|
||||
typeAnnotation: {
|
||||
type: 'FunctionTypeAnnotation',
|
||||
returnTypeAnnotation: {
|
||||
type: 'PromiseTypeAnnotation',
|
||||
elementType: {type: 'ArrayBufferTypeAnnotation'},
|
||||
},
|
||||
params: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
moduleName: 'SampleTurboModule',
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(() =>
|
||||
generator.generate(
|
||||
'array_buffer_promise_throws',
|
||||
schema,
|
||||
'com.facebook.fbreact.specs',
|
||||
),
|
||||
).toThrow(/Promise<ArrayBuffer> is not supported/);
|
||||
});
|
||||
});
|
||||
+36
-1
@@ -67,7 +67,6 @@ protected:
|
||||
methodMap_[\\"getArrayBuffer\\"] = MethodMetadata {.argCount = 0, .invoker = __getArrayBuffer};
|
||||
methodMap_[\\"voidArrayBuffer\\"] = MethodMetadata {.argCount = 1, .invoker = __voidArrayBuffer};
|
||||
methodMap_[\\"voidNullableArrayBuffer\\"] = MethodMetadata {.argCount = 1, .invoker = __voidNullableArrayBuffer};
|
||||
methodMap_[\\"promiseArrayBuffer\\"] = MethodMetadata {.argCount = 0, .invoker = __promiseArrayBuffer};
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -93,7 +92,43 @@ private:
|
||||
bridging::callFromJs<void>(rt, &T::voidNullableArrayBuffer, static_cast<NativeSampleTurboModuleCxxSpec*>(&turboModule)->jsInvoker_, static_cast<T*>(&turboModule),
|
||||
count <= 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt).getArrayBuffer(rt)));return jsi::Value::undefined();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace facebook::react
|
||||
",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleH can generate fixture array_buffer_promise_native_module 1`] = `
|
||||
Map {
|
||||
"array_buffer_promise_native_moduleJSI.h" => "/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateModuleH.js
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <ReactCommon/TurboModule.h>
|
||||
#include <react/bridging/Bridging.h>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
|
||||
template <typename T>
|
||||
class JSI_EXPORT NativeSampleTurboModuleCxxSpec : public TurboModule {
|
||||
public:
|
||||
static constexpr std::string_view kModuleName = \\"SampleTurboModule\\";
|
||||
|
||||
protected:
|
||||
NativeSampleTurboModuleCxxSpec(std::shared_ptr<CallInvoker> jsInvoker) : TurboModule(std::string{NativeSampleTurboModuleCxxSpec::kModuleName}, jsInvoker) {
|
||||
methodMap_[\\"promiseArrayBuffer\\"] = MethodMetadata {.argCount = 0, .invoker = __promiseArrayBuffer};
|
||||
}
|
||||
|
||||
private:
|
||||
static jsi::Value __promiseArrayBuffer(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* /*args*/, size_t /*count*/) {
|
||||
static_assert(
|
||||
bridging::getParameterCount(&T::promiseArrayBuffer) == 1,
|
||||
|
||||
+41
-2
@@ -105,8 +105,6 @@ Map {
|
||||
- (NSMutableData *)getArrayBuffer;
|
||||
- (void)voidArrayBuffer:(NSData *)arg;
|
||||
- (void)voidNullableArrayBuffer:(NSData * _Nullable)arg;
|
||||
- (void)promiseArrayBuffer:(RCTPromiseResolveBlock)resolve
|
||||
reject:(RCTPromiseRejectBlock)reject;
|
||||
|
||||
@end
|
||||
|
||||
@@ -134,6 +132,47 @@ namespace facebook::react {
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleHObjCpp can generate fixture array_buffer_promise_native_module 1`] = `
|
||||
Map {
|
||||
"array_buffer_promise_native_module.h" => "/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateModuleObjCpp
|
||||
*
|
||||
* We create an umbrella header (and corresponding implementation) here since
|
||||
* Cxx compilation in BUCK has a limitation: source-code producing genrule()s
|
||||
* must have a single output. More files => more genrule()s => slower builds.
|
||||
*/
|
||||
|
||||
#ifndef __cplusplus
|
||||
#error This file must be compiled as Obj-C++. If you are importing it, you must change your file extension to .mm.
|
||||
#endif
|
||||
|
||||
// Avoid multiple includes of array_buffer_promise_native_module symbols
|
||||
#ifndef array_buffer_promise_native_module_H
|
||||
#define array_buffer_promise_native_module_H
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <RCTRequired/RCTRequired.h>
|
||||
#import <RCTTypeSafety/RCTConvertHelpers.h>
|
||||
#import <RCTTypeSafety/RCTTypedModuleConstants.h>
|
||||
#import <React/RCTBridgeModule.h>
|
||||
#import <React/RCTCxxConvert.h>
|
||||
#import <React/RCTManagedPointer.h>
|
||||
#import <ReactCommon/RCTTurboModule.h>
|
||||
#import <optional>
|
||||
#import <vector>
|
||||
|
||||
|
||||
|
||||
#endif // array_buffer_promise_native_module_H
|
||||
",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleHObjCpp can generate fixture complex_objects 1`] = `
|
||||
Map {
|
||||
"complex_objects.h" => "/**
|
||||
|
||||
+54
-1
@@ -41,7 +41,60 @@ public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaMo
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleJavaSpec can generate fixture array_buffer_native_module 1`] = `Map {}`;
|
||||
exports[`GenerateModuleJavaSpec can generate fixture array_buffer_native_module 1`] = `
|
||||
Map {
|
||||
"java/com/facebook/fbreact/specs/NativeSampleTurboModuleSpec.java" => "
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateModuleJavaSpec.js
|
||||
*
|
||||
* @nolint
|
||||
*/
|
||||
|
||||
package com.facebook.fbreact.specs;
|
||||
|
||||
import com.facebook.proguard.annotations.DoNotStrip;
|
||||
import com.facebook.react.bridge.ReactApplicationContext;
|
||||
import com.facebook.react.bridge.ReactContextBaseJavaModule;
|
||||
import com.facebook.react.bridge.ReactMethod;
|
||||
import com.facebook.react.turbomodule.core.interfaces.TurboModule;
|
||||
import java.nio.ByteBuffer;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaModule implements TurboModule {
|
||||
public static final String NAME = \\"SampleTurboModule\\";
|
||||
|
||||
public NativeSampleTurboModuleSpec(ReactApplicationContext reactContext) {
|
||||
super(reactContext);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nonnull String getName() {
|
||||
return NAME;
|
||||
}
|
||||
|
||||
@ReactMethod(isBlockingSynchronousMethod = true)
|
||||
@DoNotStrip
|
||||
public abstract ByteBuffer getArrayBuffer();
|
||||
|
||||
@ReactMethod
|
||||
@DoNotStrip
|
||||
public abstract void voidArrayBuffer(ByteBuffer arg);
|
||||
|
||||
@ReactMethod
|
||||
@DoNotStrip
|
||||
public abstract void voidNullableArrayBuffer(@Nullable ByteBuffer arg);
|
||||
}
|
||||
",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleJavaSpec can generate fixture array_buffer_promise_native_module 1`] = `Map {}`;
|
||||
|
||||
exports[`GenerateModuleJavaSpec can generate fixture complex_objects 1`] = `
|
||||
Map {
|
||||
|
||||
+50
@@ -51,9 +51,59 @@ Map {
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getArrayBuffer(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) {
|
||||
static jmethodID cachedMethodId = nullptr;
|
||||
return static_cast<JavaTurboModule &>(turboModule).invokeJavaMethod(rt, ArrayBufferKind, \\"getArrayBuffer\\", \\"()Ljava/nio/ByteBuffer;\\", args, count, cachedMethodId);
|
||||
}
|
||||
|
||||
static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_voidArrayBuffer(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) {
|
||||
static jmethodID cachedMethodId = nullptr;
|
||||
return static_cast<JavaTurboModule &>(turboModule).invokeJavaMethod(rt, VoidKind, \\"voidArrayBuffer\\", \\"(Ljava/nio/ByteBuffer;)V\\", args, count, cachedMethodId);
|
||||
}
|
||||
|
||||
static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_voidNullableArrayBuffer(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) {
|
||||
static jmethodID cachedMethodId = nullptr;
|
||||
return static_cast<JavaTurboModule &>(turboModule).invokeJavaMethod(rt, VoidKind, \\"voidNullableArrayBuffer\\", \\"(Ljava/nio/ByteBuffer;)V\\", args, count, cachedMethodId);
|
||||
}
|
||||
|
||||
NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms)
|
||||
: JavaTurboModule(params) {
|
||||
methodMap_[\\"getArrayBuffer\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getArrayBuffer};
|
||||
methodMap_[\\"voidArrayBuffer\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_voidArrayBuffer};
|
||||
methodMap_[\\"voidNullableArrayBuffer\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_voidNullableArrayBuffer};
|
||||
}
|
||||
|
||||
std::shared_ptr<TurboModule> array_buffer_native_module_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) {
|
||||
if (moduleName == \\"SampleTurboModule\\") {
|
||||
return std::make_shared<NativeSampleTurboModuleSpecJSI>(params);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace facebook::react
|
||||
",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleJniCpp can generate fixture array_buffer_promise_native_module 1`] = `
|
||||
Map {
|
||||
"jni/array_buffer_promise_native_module-generated.cpp" => "
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateModuleJniCpp.js
|
||||
*/
|
||||
|
||||
#include \\"array_buffer_promise_native_module.h\\"
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
|
||||
|
||||
std::shared_ptr<TurboModule> array_buffer_promise_native_module_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) {
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
+66
@@ -86,6 +86,13 @@ Map {
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
/**
|
||||
* JNI C++ class for module 'NativeSampleTurboModule'
|
||||
*/
|
||||
class JSI_EXPORT NativeSampleTurboModuleSpecJSI : public JavaTurboModule {
|
||||
public:
|
||||
NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms);
|
||||
};
|
||||
|
||||
|
||||
JSI_EXPORT
|
||||
@@ -125,6 +132,65 @@ target_compile_reactnative_options(react_codegen_array_buffer_native_module PRIV
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleJniH can generate fixture array_buffer_promise_native_module 1`] = `
|
||||
Map {
|
||||
"jni/array_buffer_promise_native_module.h" => "
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateModuleJniH.js
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <ReactCommon/JavaTurboModule.h>
|
||||
#include <ReactCommon/TurboModule.h>
|
||||
#include <jsi/jsi.h>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
|
||||
|
||||
JSI_EXPORT
|
||||
std::shared_ptr<TurboModule> array_buffer_promise_native_module_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms);
|
||||
|
||||
} // namespace facebook::react
|
||||
",
|
||||
"jni/CMakeLists.txt" => "# 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.
|
||||
|
||||
cmake_minimum_required(VERSION 3.13)
|
||||
set(CMAKE_VERBOSE_MAKEFILE on)
|
||||
|
||||
file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS *.cpp react/renderer/components/array_buffer_promise_native_module/*.cpp)
|
||||
|
||||
add_library(
|
||||
react_codegen_array_buffer_promise_native_module
|
||||
OBJECT
|
||||
\${react_codegen_SRCS}
|
||||
)
|
||||
|
||||
target_include_directories(react_codegen_array_buffer_promise_native_module PUBLIC . react/renderer/components/array_buffer_promise_native_module)
|
||||
|
||||
target_link_libraries(
|
||||
react_codegen_array_buffer_promise_native_module
|
||||
fbjni
|
||||
jsi
|
||||
# We need to link different libraries based on whether we are building rncore or not, that's necessary
|
||||
# because we want to break a circular dependency between react_codegen_rncore and reactnative
|
||||
reactnative
|
||||
)
|
||||
|
||||
target_compile_reactnative_options(react_codegen_array_buffer_promise_native_module PRIVATE)
|
||||
",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleJniH can generate fixture complex_objects 1`] = `
|
||||
Map {
|
||||
"jni/complex_objects.h" => "
|
||||
|
||||
+22
-7
@@ -82,10 +82,6 @@ namespace facebook::react {
|
||||
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) {
|
||||
|
||||
@@ -97,15 +93,34 @@ namespace facebook::react {
|
||||
|
||||
methodMap_[\\"voidNullableArrayBuffer\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_voidNullableArrayBuffer};
|
||||
|
||||
|
||||
methodMap_[\\"promiseArrayBuffer\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_promiseArrayBuffer};
|
||||
|
||||
}
|
||||
} // namespace facebook::react
|
||||
",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleMm can generate fixture array_buffer_promise_native_module 1`] = `
|
||||
Map {
|
||||
"array_buffer_promise_native_module-generated.mm" => "/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateModuleObjCpp
|
||||
*
|
||||
* We create an umbrella header (and corresponding implementation) here since
|
||||
* Cxx compilation in BUCK has a limitation: source-code producing genrule()s
|
||||
* must have a single output. More files => more genrule()s => slower builds.
|
||||
*/
|
||||
|
||||
#import \\"array_buffer_promise_native_module.h\\"
|
||||
|
||||
|
||||
",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`GenerateModuleMm can generate fixture complex_objects 1`] = `
|
||||
Map {
|
||||
"complex_objects-generated.mm" => "/**
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <fbjni/ByteBuffer.h>
|
||||
#include <fbjni/fbjni.h>
|
||||
#include <jsi/jsi.h>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
// Wraps a direct Java ByteBuffer as a jsi::MutableBuffer for zero-copy JS
|
||||
// ArrayBuffer access. The global ref keeps the Java object alive for as long as
|
||||
// the JS ArrayBuffer is reachable.
|
||||
//
|
||||
// IMPORTANT: jsi::MutableBuffer finalizers run on the Hermes GC background
|
||||
// thread, which is not attached to JNI. Destroying a jni::global_ref on an
|
||||
// unattached thread calls abort(). jni::ThreadScope in the destructor attaches
|
||||
// the GC thread temporarily, making the global_ref teardown safe.
|
||||
class JByteBufferMutableBuffer final : public jsi::MutableBuffer {
|
||||
public:
|
||||
explicit JByteBufferMutableBuffer(jni::alias_ref<jni::JByteBuffer> byteBuffer)
|
||||
: byteBuffer_(jni::make_global(byteBuffer))
|
||||
{
|
||||
}
|
||||
|
||||
~JByteBufferMutableBuffer() override
|
||||
{
|
||||
jni::ThreadScope threadScope;
|
||||
byteBuffer_.reset();
|
||||
}
|
||||
|
||||
JByteBufferMutableBuffer(const JByteBufferMutableBuffer &) = delete;
|
||||
JByteBufferMutableBuffer &operator=(const JByteBufferMutableBuffer &) = delete;
|
||||
JByteBufferMutableBuffer(JByteBufferMutableBuffer &&) = delete;
|
||||
JByteBufferMutableBuffer &operator=(JByteBufferMutableBuffer &&) = delete;
|
||||
|
||||
size_t size() const override
|
||||
{
|
||||
return byteBuffer_->getDirectSize();
|
||||
}
|
||||
uint8_t *data() override
|
||||
{
|
||||
return byteBuffer_->getDirectBytes();
|
||||
}
|
||||
|
||||
private:
|
||||
jni::global_ref<jni::JByteBuffer> byteBuffer_;
|
||||
};
|
||||
|
||||
} // namespace facebook::react
|
||||
+68
-1
@@ -5,10 +5,13 @@
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include <cxxreact/TraceSection.h>
|
||||
#include <fbjni/ByteBuffer.h>
|
||||
#include <fbjni/fbjni.h>
|
||||
#include <glog/logging.h>
|
||||
#include <jsi/jsi.h>
|
||||
@@ -20,6 +23,7 @@
|
||||
#include <react/bridging/Bridging.h>
|
||||
#include <react/debug/react_native_assert.h>
|
||||
#include <react/featureflags/ReactNativeFeatureFlags.h>
|
||||
#include <react/jni/JByteBufferMutableBuffer.h>
|
||||
#include <react/jni/JDynamicNative.h>
|
||||
#include <react/jni/NativeMap.h>
|
||||
#include <react/jni/ReadableNativeMap.h>
|
||||
@@ -322,7 +326,7 @@ JNIArgs convertJSIArgsToJNIArgs(
|
||||
return obj;
|
||||
};
|
||||
|
||||
for (unsigned int argIndex = 0; argIndex < count; argIndex += 1) {
|
||||
for (int argIndex = 0; argIndex < static_cast<int>(count); argIndex += 1) {
|
||||
const std::string& type = methodArgTypes.at(argIndex);
|
||||
|
||||
const jsi::Value* arg = &args[argIndex];
|
||||
@@ -434,6 +438,37 @@ JNIArgs convertJSIArgsToJNIArgs(
|
||||
auto dynamicFromValue = jsi::dynamicFromValue(rt, *arg);
|
||||
auto jParams = JDynamicNative::newObjectCxxArgs(dynamicFromValue);
|
||||
jarg->l = makeGlobalIfNecessary(jParams.release());
|
||||
} else if (type == "Ljava/nio/ByteBuffer;") {
|
||||
if (!(arg->isObject() && arg->getObject(rt).isArrayBuffer(rt))) {
|
||||
throw JavaTurboModuleArgumentConversionException(
|
||||
"ArrayBuffer", argIndex, methodName, arg, &rt);
|
||||
}
|
||||
|
||||
auto arrayBuffer = arg->getObject(rt).getArrayBuffer(rt);
|
||||
if (arrayBuffer.detached(rt)) {
|
||||
throw jsi::JSError(
|
||||
rt,
|
||||
"JavaTurboModule::convertJSIArgsToJNIArgs: ArrayBuffer is detached.");
|
||||
}
|
||||
|
||||
auto size = arrayBuffer.size(rt);
|
||||
if (size > static_cast<size_t>(std::numeric_limits<jint>::max())) {
|
||||
throw jsi::JSError(
|
||||
rt,
|
||||
"JavaTurboModule::convertJSIArgsToJNIArgs: ArrayBuffer exceeds maximum size.");
|
||||
}
|
||||
auto data = arrayBuffer.data(rt);
|
||||
// ArrayBuffer arguments are always copied into a Java-owned direct
|
||||
// ByteBuffer, so Java fully owns the bytes. Borrowing the JS bytes is
|
||||
// never safe — even on a synchronous call the module may retain the
|
||||
// buffer or hand it to an async method, and JS may garbage-collect the
|
||||
// source ArrayBuffer, leaving Java with a dangling view.
|
||||
auto buffer = jni::JByteBuffer::allocateDirect(static_cast<jint>(size));
|
||||
if (size > 0) {
|
||||
// @lint-ignore CLANGSECURITY facebook-security-vulnerable-memcpy
|
||||
std::memcpy(buffer->getDirectBytes(), data, size);
|
||||
}
|
||||
jarg->l = makeGlobalIfNecessary(buffer.release());
|
||||
} else {
|
||||
throw JavaTurboModuleInvalidArgumentTypeException(
|
||||
type, argIndex, methodName);
|
||||
@@ -963,6 +998,38 @@ jsi::Value JavaTurboModule::invokeJavaMethod(
|
||||
TMPL::asyncMethodCallEnd(moduleName, methodName);
|
||||
return jsPromise;
|
||||
}
|
||||
case ArrayBufferKind: {
|
||||
auto returnObject =
|
||||
(jobject)env->CallObjectMethodA(instance, methodID, jargs.data());
|
||||
checkJNIErrorForMethodCall();
|
||||
|
||||
TMPL::syncMethodCallExecutionEnd(moduleName, methodName);
|
||||
TMPL::syncMethodCallReturnConversionStart(moduleName, methodName);
|
||||
|
||||
jsi::Value returnValue = jsi::Value::null();
|
||||
if (returnObject != nullptr) {
|
||||
auto jByteBuffer = jni::adopt_local(
|
||||
static_cast<jni::JByteBuffer::javaobject>(returnObject));
|
||||
|
||||
if (!jByteBuffer->isDirect()) {
|
||||
throw jsi::JSError(
|
||||
runtime,
|
||||
"Only direct ByteBuffers (ByteBuffer.allocateDirect) can be returned from a TurboModule.");
|
||||
}
|
||||
// Zero-copy: JByteBufferMutableBuffer takes a global reference that
|
||||
// pins the ByteBuffer's memory for the lifetime of the JS ArrayBuffer,
|
||||
// and its destructor attaches the current thread before releasing that
|
||||
// ref, so JS GC finalization on any thread is safe.
|
||||
auto nativeBuffer =
|
||||
std::make_shared<JByteBufferMutableBuffer>(jByteBuffer);
|
||||
returnValue = {
|
||||
runtime, jsi::ArrayBuffer{runtime, std::move(nativeBuffer)}};
|
||||
}
|
||||
|
||||
TMPL::syncMethodCallReturnConversionEnd(moduleName, methodName);
|
||||
TMPL::syncMethodCallEnd(moduleName, methodName);
|
||||
return returnValue;
|
||||
}
|
||||
default:
|
||||
throw std::runtime_error(
|
||||
"Unable to find method module: " + methodNameStr + "(" +
|
||||
|
||||
+25
@@ -27,6 +27,7 @@ import com.facebook.react.bridge.WritableNativeMap
|
||||
import com.facebook.react.module.annotations.ReactModule
|
||||
import com.facebook.react.turbomodule.core.interfaces.BindingsInstallerHolder
|
||||
import com.facebook.react.turbomodule.core.interfaces.TurboModuleWithJSIBindings
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.UUID
|
||||
|
||||
@DoNotStrip
|
||||
@@ -154,6 +155,30 @@ public class SampleTurboModule(private val context: ReactApplicationContext) :
|
||||
return map
|
||||
}
|
||||
|
||||
@DoNotStrip
|
||||
@Suppress("unused")
|
||||
override fun getArrayBuffer(buffer: ByteBuffer?): ByteBuffer? {
|
||||
log("getArrayBuffer", buffer, buffer)
|
||||
return buffer
|
||||
}
|
||||
|
||||
@DoNotStrip
|
||||
@Suppress("unused")
|
||||
override fun createNativeBuffer(size: Double): ByteBuffer {
|
||||
require(size.isFinite() && size >= 0.0 && size <= Int.MAX_VALUE.toDouble()) {
|
||||
"createNativeBuffer: size must be a finite value in [0, ${Int.MAX_VALUE}], got $size"
|
||||
}
|
||||
val buffer = ByteBuffer.allocateDirect(size.toInt())
|
||||
log("createNativeBuffer", size, buffer)
|
||||
return buffer
|
||||
}
|
||||
|
||||
@DoNotStrip
|
||||
@Suppress("unused")
|
||||
override fun processAsyncBuffer(payload: ByteBuffer?, promise: Promise) {
|
||||
promise.resolve((payload?.capacity() ?: 0).toDouble())
|
||||
}
|
||||
|
||||
@DoNotStrip
|
||||
@Suppress("unused")
|
||||
override fun getValueWithCallback(callback: Callback?) {
|
||||
|
||||
+20
@@ -145,6 +145,26 @@ RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSDictionary *, getValue : (double)x y : (NS
|
||||
};
|
||||
}
|
||||
|
||||
// Arguments arrive as an immutable NSData, but an ArrayBuffer return must be
|
||||
// NSMutableData: it is handed to JS as a jsi::MutableBuffer, whose data() is
|
||||
// non-const. Echoing the argument back therefore needs a mutable copy.
|
||||
RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSMutableData *, getArrayBuffer : (NSData *)buffer)
|
||||
{
|
||||
return [buffer mutableCopy];
|
||||
}
|
||||
|
||||
RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSMutableData *, createNativeBuffer : (double)size)
|
||||
{
|
||||
return [NSMutableData dataWithLength:(NSUInteger)size];
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(
|
||||
processAsyncBuffer : (NSData *)payload resolve : (RCTPromiseResolveBlock)resolve reject : (RCTPromiseRejectBlock)
|
||||
reject)
|
||||
{
|
||||
resolve(@(payload.length));
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(getValueWithCallback : (RCTResponseSenderBlock)callback)
|
||||
{
|
||||
if (callback == nullptr) {
|
||||
|
||||
+3
@@ -51,6 +51,9 @@ export interface Spec extends TurboModule {
|
||||
readonly getUnsafeObject: (arg: UnsafeObject) => UnsafeObject;
|
||||
readonly getRootTag: (arg: RootTag) => RootTag;
|
||||
readonly getValue: (x: number, y: string, z: Object) => Object;
|
||||
readonly getArrayBuffer: (buffer: ArrayBuffer) => ArrayBuffer;
|
||||
readonly createNativeBuffer: (size: number) => ArrayBuffer;
|
||||
readonly processAsyncBuffer: (payload: ArrayBuffer) => Promise<number>;
|
||||
readonly getValueWithCallback: (callback: (value: string) => void) => void;
|
||||
readonly getValueWithPromise: (error: boolean) => Promise<string>;
|
||||
readonly voidFuncThrows?: () => void;
|
||||
|
||||
@@ -46,6 +46,9 @@ type Examples =
|
||||
| 'getString'
|
||||
| 'getUnion'
|
||||
| 'getValue'
|
||||
| 'getArrayBuffer'
|
||||
| 'createNativeBuffer'
|
||||
| 'processAsyncBuffer'
|
||||
| 'promise'
|
||||
| 'rejectPromise'
|
||||
| 'voidFunc'
|
||||
@@ -108,6 +111,17 @@ class SampleTurboModuleExample extends React.Component<{}, State> {
|
||||
getRootTag: () => NativeSampleTurboModule.getRootTag(this.context),
|
||||
getValue: () =>
|
||||
NativeSampleTurboModule.getValue(5, 'test', {a: 1, b: 'foo'}),
|
||||
getArrayBuffer: () => {
|
||||
const input = new Uint8Array([1, 2, 3, 4]);
|
||||
const result = NativeSampleTurboModule.getArrayBuffer(input.buffer);
|
||||
return Array.from(new Uint8Array(result));
|
||||
},
|
||||
createNativeBuffer: () =>
|
||||
NativeSampleTurboModule.createNativeBuffer(8).byteLength,
|
||||
processAsyncBuffer: () =>
|
||||
NativeSampleTurboModule.processAsyncBuffer(
|
||||
new Uint8Array([1, 2, 3]).buffer,
|
||||
).then(length => this._setResult('processAsyncBuffer', length)),
|
||||
};
|
||||
|
||||
// $FlowFixMe[missing-local-annot]
|
||||
|
||||
@@ -2796,6 +2796,17 @@ class facebook::react::JBindingsInstaller : public jni::HybridClass<facebook::re
|
||||
public ~JBindingsInstaller();
|
||||
}
|
||||
|
||||
class facebook::react::JByteBufferMutableBuffer : public facebook::jsi::MutableBuffer {
|
||||
public JByteBufferMutableBuffer(const facebook::react::JByteBufferMutableBuffer&) = delete;
|
||||
public JByteBufferMutableBuffer(facebook::react::JByteBufferMutableBuffer&&) = delete;
|
||||
public JByteBufferMutableBuffer(jni::alias_ref<jni::JByteBuffer> byteBuffer);
|
||||
public facebook::react::JByteBufferMutableBuffer& operator=(const facebook::react::JByteBufferMutableBuffer&) = delete;
|
||||
public facebook::react::JByteBufferMutableBuffer& operator=(facebook::react::JByteBufferMutableBuffer&&) = delete;
|
||||
public virtual size_t size() const override;
|
||||
public virtual uint8_t* data() override;
|
||||
public ~JByteBufferMutableBuffer() override;
|
||||
}
|
||||
|
||||
class facebook::react::JCxxCallbackImpl : public jni::HybridClass<facebook::react::JCxxCallbackImpl, facebook::react::JCallback> {
|
||||
public static constexpr auto kJavaDescriptor;
|
||||
public static void registerNatives();
|
||||
|
||||
@@ -2754,6 +2754,17 @@ class facebook::react::JBindingsInstaller : public jni::HybridClass<facebook::re
|
||||
public ~JBindingsInstaller();
|
||||
}
|
||||
|
||||
class facebook::react::JByteBufferMutableBuffer : public facebook::jsi::MutableBuffer {
|
||||
public JByteBufferMutableBuffer(const facebook::react::JByteBufferMutableBuffer&) = delete;
|
||||
public JByteBufferMutableBuffer(facebook::react::JByteBufferMutableBuffer&&) = delete;
|
||||
public JByteBufferMutableBuffer(jni::alias_ref<jni::JByteBuffer> byteBuffer);
|
||||
public facebook::react::JByteBufferMutableBuffer& operator=(const facebook::react::JByteBufferMutableBuffer&) = delete;
|
||||
public facebook::react::JByteBufferMutableBuffer& operator=(facebook::react::JByteBufferMutableBuffer&&) = delete;
|
||||
public virtual size_t size() const override;
|
||||
public virtual uint8_t* data() override;
|
||||
public ~JByteBufferMutableBuffer() override;
|
||||
}
|
||||
|
||||
class facebook::react::JCxxCallbackImpl : public jni::HybridClass<facebook::react::JCxxCallbackImpl, facebook::react::JCallback> {
|
||||
public static constexpr auto kJavaDescriptor;
|
||||
public static void registerNatives();
|
||||
|
||||
@@ -2793,6 +2793,17 @@ class facebook::react::JBindingsInstaller : public jni::HybridClass<facebook::re
|
||||
public ~JBindingsInstaller();
|
||||
}
|
||||
|
||||
class facebook::react::JByteBufferMutableBuffer : public facebook::jsi::MutableBuffer {
|
||||
public JByteBufferMutableBuffer(const facebook::react::JByteBufferMutableBuffer&) = delete;
|
||||
public JByteBufferMutableBuffer(facebook::react::JByteBufferMutableBuffer&&) = delete;
|
||||
public JByteBufferMutableBuffer(jni::alias_ref<jni::JByteBuffer> byteBuffer);
|
||||
public facebook::react::JByteBufferMutableBuffer& operator=(const facebook::react::JByteBufferMutableBuffer&) = delete;
|
||||
public facebook::react::JByteBufferMutableBuffer& operator=(facebook::react::JByteBufferMutableBuffer&&) = delete;
|
||||
public virtual size_t size() const override;
|
||||
public virtual uint8_t* data() override;
|
||||
public ~JByteBufferMutableBuffer() override;
|
||||
}
|
||||
|
||||
class facebook::react::JCxxCallbackImpl : public jni::HybridClass<facebook::react::JCxxCallbackImpl, facebook::react::JCallback> {
|
||||
public static constexpr auto kJavaDescriptor;
|
||||
public static void registerNatives();
|
||||
|
||||
@@ -2500,6 +2500,8 @@ protocol NativeSampleTurboModuleSpec : public NSObjectRCTBridgeModule, public RC
|
||||
public virtual NSDictionary* getObjectThrows:(NSDictionary* arg);
|
||||
public virtual NSDictionary* getUnsafeObject:(NSDictionary* arg);
|
||||
public virtual NSDictionary* getValue:y:z:(double x, NSString* y, NSDictionary* z);
|
||||
public virtual NSMutableData* createNativeBuffer:(double size);
|
||||
public virtual NSMutableData* getArrayBuffer:(NSData* buffer);
|
||||
public virtual NSNumber* getBool:(BOOL arg);
|
||||
public virtual NSNumber* getEnum:(double arg);
|
||||
public virtual NSNumber* getNumber:(double arg);
|
||||
@@ -2510,6 +2512,7 @@ protocol NativeSampleTurboModuleSpec : public NSObjectRCTBridgeModule, public RC
|
||||
public virtual void getImageUrl:reject:(RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void getValueWithCallback:(RCTResponseSenderBlock callback);
|
||||
public virtual void getValueWithPromise:resolve:reject:(BOOL error, RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void processAsyncBuffer:resolve:reject:(NSData* payload, RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void promiseAssert:reject:(RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void promiseThrows:reject:(RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void voidFunc();
|
||||
|
||||
@@ -2489,6 +2489,8 @@ protocol NativeSampleTurboModuleSpec : public NSObjectRCTBridgeModule, public RC
|
||||
public virtual NSDictionary* getObjectThrows:(NSDictionary* arg);
|
||||
public virtual NSDictionary* getUnsafeObject:(NSDictionary* arg);
|
||||
public virtual NSDictionary* getValue:y:z:(double x, NSString* y, NSDictionary* z);
|
||||
public virtual NSMutableData* createNativeBuffer:(double size);
|
||||
public virtual NSMutableData* getArrayBuffer:(NSData* buffer);
|
||||
public virtual NSNumber* getBool:(BOOL arg);
|
||||
public virtual NSNumber* getEnum:(double arg);
|
||||
public virtual NSNumber* getNumber:(double arg);
|
||||
@@ -2499,6 +2501,7 @@ protocol NativeSampleTurboModuleSpec : public NSObjectRCTBridgeModule, public RC
|
||||
public virtual void getImageUrl:reject:(RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void getValueWithCallback:(RCTResponseSenderBlock callback);
|
||||
public virtual void getValueWithPromise:resolve:reject:(BOOL error, RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void processAsyncBuffer:resolve:reject:(NSData* payload, RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void promiseAssert:reject:(RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void promiseThrows:reject:(RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void voidFunc();
|
||||
|
||||
@@ -2500,6 +2500,8 @@ protocol NativeSampleTurboModuleSpec : public NSObjectRCTBridgeModule, public RC
|
||||
public virtual NSDictionary* getObjectThrows:(NSDictionary* arg);
|
||||
public virtual NSDictionary* getUnsafeObject:(NSDictionary* arg);
|
||||
public virtual NSDictionary* getValue:y:z:(double x, NSString* y, NSDictionary* z);
|
||||
public virtual NSMutableData* createNativeBuffer:(double size);
|
||||
public virtual NSMutableData* getArrayBuffer:(NSData* buffer);
|
||||
public virtual NSNumber* getBool:(BOOL arg);
|
||||
public virtual NSNumber* getEnum:(double arg);
|
||||
public virtual NSNumber* getNumber:(double arg);
|
||||
@@ -2510,6 +2512,7 @@ protocol NativeSampleTurboModuleSpec : public NSObjectRCTBridgeModule, public RC
|
||||
public virtual void getImageUrl:reject:(RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void getValueWithCallback:(RCTResponseSenderBlock callback);
|
||||
public virtual void getValueWithPromise:resolve:reject:(BOOL error, RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void processAsyncBuffer:resolve:reject:(NSData* payload, RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void promiseAssert:reject:(RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void promiseThrows:reject:(RCTPromiseResolveBlock resolve, RCTPromiseRejectBlock reject);
|
||||
public virtual void voidFunc();
|
||||
|
||||
Reference in new issue
Block a user