Remove usage of folly::to (#49786)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49786

Most of these call-sites are only used for exceptional scenarios, so we can just rely on std::to_string and do string concatenation. For a few others that may be more perf-sensitive, I switched over to `snprintf`.

Changelog: [Internal]

Reviewed By: sammy-SC

Differential Revision: D70402439

fbshipit-source-id: 3b90ebb13a7bf1c6cf30722ef636e5e8498a5b26
This commit is contained in:
Pieter De Baets
2025-03-04 10:07:09 -08:00
committed by Facebook GitHub Bot
parent 86b1f9ac07
commit 6bf6cebcf0
25 changed files with 215 additions and 194 deletions
@@ -11,7 +11,6 @@
#include <cxxreact/JSBigString.h>
#include <cxxreact/JSBundleType.h>
#include <fbjni/fbjni.h>
#include <folly/Conv.h>
#ifdef WITH_FBSYSTRACE
#include <fbsystrace.h>
@@ -87,11 +86,10 @@ loadScriptFromAssets(AAssetManager* manager, const std::string& assetName) {
}
}
throw std::runtime_error(folly::to<std::string>(
throw std::runtime_error(
"Unable to load script. Make sure you're "
"either running Metro (run 'npx react-native start') or that your bundle '",
assetName,
"' is packaged correctly for release."));
"either running Metro (run 'npx react-native start') or that your bundle '" +
assetName + "' is packaged correctly for release.");
}
} // namespace facebook::react
@@ -15,7 +15,6 @@
#include <cxxreact/JsArgumentHelpers.h>
#include <cxxreact/NativeModule.h>
#include <fbjni/fbjni.h>
#include <folly/json.h>
#ifdef WITH_FBSYSTRACE
#include <fbsystrace.h>
@@ -51,19 +50,16 @@ std::string JavaNativeModule::getName() {
std::string JavaNativeModule::getSyncMethodName(unsigned int reactMethodId) {
if (reactMethodId >= syncMethods_.size()) {
throw std::invalid_argument(folly::to<std::string>(
"methodId ",
reactMethodId,
" out of range [0..",
syncMethods_.size(),
"]"));
throw std::invalid_argument(
"methodId " + std::to_string(reactMethodId) + " out of range [0.." +
std::to_string(syncMethods_.size()) + "]");
}
auto& methodInvoker = syncMethods_[reactMethodId];
if (!methodInvoker.has_value()) {
throw std::invalid_argument(folly::to<std::string>(
"methodId ", reactMethodId, " is not a recognized sync method"));
throw std::invalid_argument(
"methodId " + std::to_string(reactMethodId) +
" is not a recognized sync method");
}
return methodInvoker->getMethodName();
@@ -137,12 +133,9 @@ MethodCallResult JavaNativeModule::callSerializableNativeHook(
folly::dynamic&& params) {
// TODO: evaluate whether calling through invoke is potentially faster
if (reactMethodId >= syncMethods_.size()) {
throw std::invalid_argument(folly::to<std::string>(
"methodId ",
reactMethodId,
" out of range [0..",
syncMethods_.size(),
"]"));
throw std::invalid_argument(
"methodId " + std::to_string(reactMethodId) + " out of range [0.." +
std::to_string(syncMethods_.size()) + "]");
}
auto& method = syncMethods_[reactMethodId];
@@ -12,6 +12,7 @@
#include <libgen.h>
#include <sys/endian.h>
#include <cstdint>
#include <functional>
#include <memory>
#include <sstream>
#include <utility>
@@ -65,9 +65,9 @@ jint extractInteger(const folly::dynamic& value) {
double dbl = value.getDouble();
jint result = static_cast<jint>(dbl);
if (dbl != result) {
throw std::invalid_argument(folly::to<std::string>(
"Tried to convert jint argument, but got a non-integral double: ",
dbl));
throw std::invalid_argument(
"Tried to convert jint argument, but got a non-integral double: " +
std::to_string(dbl));
}
return result;
}
@@ -222,8 +222,9 @@ MethodCallResult MethodInvoker::invoke(
#endif
if (params.size() != jsArgCount_) {
throw std::invalid_argument(folly::to<std::string>(
"expected ", jsArgCount_, " arguments, got ", params.size()));
throw std::invalid_argument(
"expected " + std::to_string(jsArgCount_) + " arguments, got " +
std::to_string(params.size()));
}
auto env = Environment::current();
@@ -68,12 +68,8 @@ void CxxNativeModule::emitWarnIfWarnOnUsage(
const std::string& method_name,
const std::string& module_name) {
if (shouldWarnOnUse_) {
std::string message = folly::to<std::string>(
"Calling ",
method_name,
" on Cxx NativeModule (name = \"",
module_name,
"\").");
std::string message = "Calling " + method_name +
" on Cxx NativeModule (name = \"" + module_name + "\").";
react_native_log_warn(message.c_str());
}
}
@@ -84,12 +80,9 @@ std::string CxxNativeModule::getName() {
std::string CxxNativeModule::getSyncMethodName(unsigned int reactMethodId) {
if (reactMethodId >= methods_.size()) {
throw std::invalid_argument(folly::to<std::string>(
"methodId ",
reactMethodId,
" out of range [0..",
methods_.size(),
"]"));
throw std::invalid_argument(
"methodId " + std::to_string(reactMethodId) + " out of range [0.." +
std::to_string(methods_.size()) + "]");
}
return methods_[reactMethodId].name;
}
@@ -125,16 +118,14 @@ void CxxNativeModule::invoke(
folly::dynamic&& params,
int callId) {
if (reactMethodId >= methods_.size()) {
throw std::invalid_argument(folly::to<std::string>(
"methodId ",
reactMethodId,
" out of range [0..",
methods_.size(),
"]"));
throw std::invalid_argument(
"methodId " + std::to_string(reactMethodId) + " out of range [0.." +
std::to_string(methods_.size()) + "]");
}
if (!params.isArray()) {
throw std::invalid_argument(folly::to<std::string>(
"method parameters should be array, but are ", params.typeName()));
throw std::invalid_argument(
std::string("Method parameters should be array, but are ") +
params.typeName());
}
CxxModule::Callback first;
@@ -143,19 +134,17 @@ void CxxNativeModule::invoke(
const auto& method = methods_[reactMethodId];
if (!method.func) {
throw std::runtime_error(folly::to<std::string>(
"Method ", method.name, " is synchronous but invoked asynchronously"));
throw std::runtime_error(
"Method " + method.name + " is synchronous but invoked asynchronously");
}
emitWarnIfWarnOnUsage(method.name, getName());
if (params.size() < method.callbacks) {
throw std::invalid_argument(folly::to<std::string>(
"Expected ",
method.callbacks,
" callbacks, but only ",
params.size(),
" parameters provided"));
throw std::invalid_argument(
"Expected " + std::to_string(method.callbacks) +
" callbacks, but only " + std::to_string(params.size()) +
" parameters provided");
}
if (method.callbacks == 1) {
@@ -229,15 +218,16 @@ MethodCallResult CxxNativeModule::callSerializableNativeHook(
unsigned int hookId,
folly::dynamic&& args) {
if (hookId >= methods_.size()) {
throw std::invalid_argument(folly::to<std::string>(
"methodId ", hookId, " out of range [0..", methods_.size(), "]"));
throw std::invalid_argument(
"methodId " + std::to_string(hookId) + " out of range [0.." +
std::to_string(methods_.size()) + "]");
}
const auto& method = methods_[hookId];
if (!method.syncFunc) {
throw std::runtime_error(folly::to<std::string>(
"Method ", method.name, " is asynchronous but invoked synchronously"));
throw std::runtime_error(
"Method " + method.name + " is asynchronous but invoked synchronously");
}
emitWarnIfWarnOnUsage(method.name, getName());
@@ -9,10 +9,10 @@
#include "RAMBundleRegistry.h"
#include <folly/Conv.h>
#include <jsinspector-modern/ReactCdp.h>
#include <react/timing/primitives.h>
#include <array>
#include <chrono>
namespace facebook::react {
@@ -23,7 +23,10 @@ std::string JSExecutor::getSyntheticBundlePath(
if (bundleId == RAMBundleRegistry::MAIN_BUNDLE_ID) {
return bundlePath;
}
return folly::to<std::string>("seg-", bundleId, ".js");
std::array<char, 32> buffer{};
std::snprintf(buffer.data(), buffer.size(), "seg-%u.js", bundleId);
return buffer.data();
}
double JSExecutor::performanceNow() {
@@ -24,8 +24,9 @@ JSIndexedRAMBundle::buildFactory() {
JSIndexedRAMBundle::JSIndexedRAMBundle(const char* sourcePath) {
m_bundle = std::make_unique<std::ifstream>(sourcePath, std::ifstream::binary);
if (!m_bundle) {
throw std::ios_base::failure(folly::to<std::string>(
"Bundle ", sourcePath, "cannot be opened: ", m_bundle->rdstate()));
throw std::ios_base::failure(
std::string("Bundle ") + sourcePath +
"cannot be opened: " + std::to_string(m_bundle->rdstate()));
}
init();
}
@@ -39,8 +40,9 @@ JSIndexedRAMBundle::JSIndexedRAMBundle(
tmpStream->write(script->c_str(), script->size());
m_bundle = std::move(tmpStream);
if (!m_bundle) {
throw std::ios_base::failure(folly::to<std::string>(
"Bundle from string cannot be opened: ", m_bundle->rdstate()));
throw std::ios_base::failure(
"Bundle from string cannot be opened: " +
std::to_string(m_bundle->rdstate()));
}
init();
}
@@ -73,7 +75,7 @@ void JSIndexedRAMBundle::init() {
JSIndexedRAMBundle::Module JSIndexedRAMBundle::getModule(
uint32_t moduleId) const {
Module ret;
ret.name = folly::to<std::string>(moduleId, ".js");
ret.name = std::to_string(moduleId) + ".js";
ret.code = getModuleCode(moduleId);
return ret;
}
@@ -92,7 +94,7 @@ std::string JSIndexedRAMBundle::getModuleCode(const uint32_t id) const {
moduleData ? folly::Endian::little(moduleData->length) : 0;
if (length == 0) {
throw std::ios_base::failure(
folly::to<std::string>("Error loading module", id, "from RAM Bundle"));
"Error loading module" + std::to_string(id) + "from RAM Bundle");
}
std::string ret(length - 1, '\0');
@@ -109,8 +111,8 @@ void JSIndexedRAMBundle::readBundle(char* buffer, const std::streamsize bytes)
if (m_bundle->rdstate() & std::ios::eofbit) {
throw std::ios_base::failure("Unexpected end of RAM Bundle file");
}
throw std::ios_base::failure(folly::to<std::string>(
"Error reading RAM Bundle: ", m_bundle->rdstate()));
throw std::ios_base::failure(
"Error reading RAM Bundle: " + std::to_string(m_bundle->rdstate()));
}
}
@@ -119,8 +121,8 @@ void JSIndexedRAMBundle::readBundle(
const std::streamsize bytes,
const std::ifstream::pos_type position) const {
if (!m_bundle->seekg(position)) {
throw std::ios_base::failure(folly::to<std::string>(
"Error reading RAM Bundle: ", m_bundle->rdstate()));
throw std::ios_base::failure(
"Error reading RAM Bundle: " + std::to_string(m_bundle->rdstate()));
}
readBundle(buffer, bytes);
}
@@ -11,8 +11,6 @@
#include <stdexcept>
#include <string>
#include <folly/Conv.h>
namespace facebook::react {
class JSModulesUnbundle {
@@ -27,9 +25,9 @@ class JSModulesUnbundle {
class ModuleNotFound : public std::out_of_range {
public:
using std::out_of_range::out_of_range;
ModuleNotFound(uint32_t moduleId)
explicit ModuleNotFound(uint32_t moduleId)
: std::out_of_range::out_of_range(
folly::to<std::string>("Module not found: ", moduleId)) {}
"Module not found: " + std::to_string(moduleId)) {}
};
struct Module {
std::string name;
@@ -6,6 +6,7 @@
*/
#pragma once
#include <folly/dynamic.h>
namespace facebook {
@@ -13,19 +14,32 @@ namespace xplat {
namespace detail {
inline std::string toStringHelper() {
return "";
}
template <typename T, typename... Rest>
inline std::string toStringHelper(const T& value, const Rest&... rest) {
return std::to_string(value) + toStringHelper(rest...);
}
template <typename... Rest>
inline std::string toStringHelper(const char* value, const Rest&... rest) {
return std::string(value) + toStringHelper(rest...);
}
template <typename R, typename M, typename... T>
R jsArg1(const folly::dynamic& arg, M asFoo, const T&... desc) {
try {
return (arg.*asFoo)();
} catch (const folly::TypeError& ex) {
throw JsArgumentException(folly::to<std::string>(
"Error converting javascript arg ", desc..., " to C++: ", ex.what()));
throw JsArgumentException(
"Error converting JavaScript arg " + toStringHelper(desc...) +
" to C++: " + ex.what());
} catch (const std::range_error& ex) {
throw JsArgumentException(folly::to<std::string>(
"Could not convert argument ",
desc...,
" to required type: ",
ex.what()));
throw JsArgumentException(
"Could not convert argument " + toStringHelper(desc...) +
" to required type: " + ex.what());
}
}
@@ -54,13 +68,10 @@ typename detail::is_dynamic<T>::type& jsArgAsDynamic(T&& args, size_t n) {
return args[n];
} catch (const std::out_of_range& ex) {
// Use 1-base counting for argument description.
throw JsArgumentException(folly::to<std::string>(
"JavaScript provided ",
args.size(),
" arguments for C++ method which references at least ",
n + 1,
" arguments: ",
ex.what()));
throw JsArgumentException(
"JavaScript provided " + std::to_string(args.size()) +
" arguments for C++ method which references at least " +
std::to_string(n + 1) + " arguments: " + ex.what());
}
}
@@ -95,13 +106,9 @@ typename detail::is_dynamic<T>::type& jsArgAsType(
}
// Use 1-base counting for argument description.
throw JsArgumentException(folly::to<std::string>(
"Argument ",
n + 1,
" of type ",
ret.typeName(),
" is not required type ",
required));
throw JsArgumentException(
"Argument " + std::to_string(n + 1) + " of type " + ret.typeName() +
" is not required type " + required);
}
} // end namespace detail
@@ -10,7 +10,6 @@
#include <exception>
#include <string>
#include <folly/Conv.h>
#include <folly/dynamic.h>
// When building a cross-platform module for React Native, arguments passed
@@ -31,7 +30,7 @@ class JsArgumentException : public std::logic_error {
// This extracts a single argument by calling the given method pointer on it.
// If an exception is thrown, the additional arguments are passed to
// folly::to<> to be included in the exception string. This will be most
// std::to_string to be included in the exception string. This will be most
// commonly used when extracting values from non-scalar argument. The second
// overload accepts ref-qualified member functions.
@@ -25,13 +25,15 @@ std::vector<MethodCall> parseMethodCalls(folly::dynamic&& jsonData) {
}
if (!jsonData.isArray()) {
throw std::invalid_argument(folly::to<std::string>(
errorPrefix, "input isn't array but ", jsonData.typeName()));
throw std::invalid_argument(
std::string(errorPrefix) + " input isn't array but " +
jsonData.typeName());
}
if (jsonData.size() < REQUEST_PARAMS + 1) {
throw std::invalid_argument(
folly::to<std::string>(errorPrefix, "size == ", jsonData.size()));
std::string(errorPrefix) +
"size == " + std::to_string(jsonData.size()));
}
auto& moduleIds = jsonData[REQUEST_MODULE_IDS];
@@ -40,24 +42,23 @@ std::vector<MethodCall> parseMethodCalls(folly::dynamic&& jsonData) {
int callId = -1;
if (!moduleIds.isArray() || !methodIds.isArray() || !params.isArray()) {
throw std::invalid_argument(folly::to<std::string>(
errorPrefix,
"not all fields are arrays.\n\n",
folly::toJson(jsonData)));
throw std::invalid_argument(
std::string(errorPrefix) + "not all fields are arrays.\n\n" +
folly::toJson(jsonData));
}
if (moduleIds.size() != methodIds.size() ||
moduleIds.size() != params.size()) {
throw std::invalid_argument(folly::to<std::string>(
errorPrefix,
"field sizes are different.\n\n",
folly::toJson(jsonData)));
throw std::invalid_argument(
std::string(errorPrefix) + "field sizes are different.\n\n" +
folly::toJson(jsonData));
}
if (jsonData.size() > REQUEST_CALLID) {
if (!jsonData[REQUEST_CALLID].isNumber()) {
throw std::invalid_argument(folly::to<std::string>(
errorPrefix, "invalid callId", jsonData[REQUEST_CALLID].typeName()));
throw std::invalid_argument(
std::string(errorPrefix) + "invalid callId" +
jsonData[REQUEST_CALLID].typeName());
}
callId = (int)jsonData[REQUEST_CALLID].asInt();
}
@@ -65,10 +66,9 @@ std::vector<MethodCall> parseMethodCalls(folly::dynamic&& jsonData) {
std::vector<MethodCall> methodCalls;
for (size_t i = 0; i < moduleIds.size(); i++) {
if (!params[i].isArray()) {
throw std::invalid_argument(folly::to<std::string>(
errorPrefix,
"method arguments isn't array but ",
params[i].typeName()));
throw std::invalid_argument(
std::string(errorPrefix) + "method arguments isn't array but " +
params[i].typeName());
}
methodCalls.emplace_back(
@@ -66,10 +66,9 @@ void ModuleRegistry::registerModules(
std::string name = normalizeName(modules_[index]->getName());
auto it = unknownModules_.find(name);
if (it != unknownModules_.end()) {
throw std::runtime_error(folly::to<std::string>(
"module ",
name,
" was required without being registered and is now being registered."));
throw std::runtime_error(
"module " + name +
" was required without being registered and is now being registered.");
} else if (addToNames) {
modulesByName_[name] = index;
}
@@ -193,8 +192,9 @@ std::optional<ModuleConfig> ModuleRegistry::getConfig(const std::string& name) {
std::string ModuleRegistry::getModuleName(unsigned int moduleId) {
if (moduleId >= modules_.size()) {
throw std::runtime_error(folly::to<std::string>(
"moduleId ", moduleId, " out of range [0..", modules_.size(), ")"));
throw std::runtime_error(
"moduleId " + std::to_string(moduleId) + " out of range [0.." +
std::to_string(modules_.size()) + ")");
}
return modules_[moduleId]->getName();
@@ -204,8 +204,9 @@ std::string ModuleRegistry::getModuleSyncMethodName(
unsigned int moduleId,
unsigned int methodId) {
if (moduleId >= modules_.size()) {
throw std::runtime_error(folly::to<std::string>(
"moduleId ", moduleId, " out of range [0..", modules_.size(), ")"));
throw std::runtime_error(
"moduleId " + std::to_string(moduleId) + " out of range [0.." +
std::to_string(modules_.size()) + ")");
}
return modules_[moduleId]->getSyncMethodName(methodId);
@@ -217,8 +218,9 @@ void ModuleRegistry::callNativeMethod(
folly::dynamic&& params,
int callId) {
if (moduleId >= modules_.size()) {
throw std::runtime_error(folly::to<std::string>(
"moduleId ", moduleId, " out of range [0..", modules_.size(), ")"));
throw std::runtime_error(
"moduleId " + std::to_string(moduleId) + " out of range [0.." +
std::to_string(modules_.size()) + ")");
}
modules_[moduleId]->invoke(methodId, std::move(params), callId);
}
@@ -228,8 +230,9 @@ MethodCallResult ModuleRegistry::callSerializableNativeHook(
unsigned int methodId,
folly::dynamic&& params) {
if (moduleId >= modules_.size()) {
throw std::runtime_error(folly::to<std::string>(
"moduleId ", moduleId, "out of range [0..", modules_.size(), ")"));
throw std::runtime_error(
"moduleId " + std::to_string(moduleId) + " out of range [0.." +
std::to_string(modules_.size()) + ")");
}
return modules_[moduleId]->callSerializableNativeHook(
methodId, std::move(params));
@@ -66,8 +66,9 @@ JSModulesUnbundle::Module RAMBundleRegistry::getModule(
if (bundleId == MAIN_BUNDLE_ID) {
return module;
}
return {
folly::to<std::string>("seg-", bundleId, '_', std::move(module.name)),
"seg-" + std::to_string(bundleId) + '_' + module.name,
std::move(module.code),
};
}
@@ -32,7 +32,7 @@ TEST(JsArgumentHelpersTest, args) {
const std::string aString = "word";
const dynamic anArray = dynamic::array("a", "b", "c");
const dynamic anObject = dynamic::object("k1", "v1")("k2", "v2");
const std::string aNumericString = folly::to<std::string>(anInt);
const std::string aNumericString = std::to_string(anInt);
folly::dynamic args = dynamic::array(
aBool, anInt, aDouble, aString, anArray, anObject, aNumericString);
@@ -104,7 +104,7 @@ TEST(JsArgumentHelpersTest, args) {
"Argument 3 of type double is not required type Array");
EXPECT_JSAE(
jsArgAsInt(args, 4),
"Error converting javascript arg 4 to C++: "
"Error converting JavaScript arg 4 to C++: "
"TypeError: expected dynamic type 'int/double/bool/string', but had type 'array'");
// type predicate failure
EXPECT_JSAE(
@@ -12,7 +12,6 @@
#include <cxxreact/ModuleRegistry.h>
#include <cxxreact/ReactMarker.h>
#include <cxxreact/TraceSection.h>
#include <folly/Conv.h>
#include <folly/json.h>
#include <glog/logging.h>
#include <jsi/JSIDynamic.h>
@@ -195,7 +194,7 @@ void JSIExecutor::setBundleRegistry(std::unique_ptr<RAMBundleRegistry> r) {
void JSIExecutor::registerBundle(
uint32_t bundleId,
const std::string& bundlePath) {
const auto tag = folly::to<std::string>(bundleId);
auto tag = std::to_string(bundleId);
ReactMarker::logTaggedMarker(
ReactMarker::REGISTER_JS_SEGMENT_START, tag.c_str());
if (bundleRegistry_) {
@@ -265,7 +264,7 @@ void JSIExecutor::invokeCallback(
*runtime_, callbackId, valueFromDynamic(*runtime_, arguments));
} catch (...) {
std::throw_with_nested(std::runtime_error(
folly::to<std::string>("Error invoking callback ", callbackId)));
"Error invoking callback " + std::to_string(callbackId)));
}
callNativeModules(ret, true);
@@ -436,8 +435,9 @@ Value JSIExecutor::nativeRequire(const Value* args, size_t count) {
throw std::invalid_argument("Got wrong number of args");
}
uint32_t moduleId = folly::to<uint32_t>(args[0].getNumber());
uint32_t bundleId = count == 2 ? folly::to<uint32_t>(args[1].getNumber()) : 0;
auto moduleId = static_cast<uint32_t>(args[0].getNumber());
uint32_t bundleId =
count == 2 ? static_cast<uint32_t>(args[1].getNumber()) : 0;
auto module = bundleRegistry_->getModule(bundleId, moduleId);
runtime_->evaluateJavaScript(
@@ -451,8 +451,7 @@ Value JSIExecutor::nativeCallSyncHook(const Value* args, size_t count) {
}
if (!args[2].isObject() || !args[2].asObject(*runtime_).isArray(*runtime_)) {
throw std::invalid_argument(
folly::to<std::string>("method parameters should be array"));
throw std::invalid_argument("method parameters should be array");
}
unsigned int moduleId = static_cast<unsigned int>(args[0].getNumber());
@@ -541,7 +540,7 @@ void bindNativeLogger(Runtime& runtime, Logger logger) {
}
logger(
args[0].asString(runtime).utf8(runtime),
folly::to<unsigned int>(args[1].asNumber()));
static_cast<unsigned int>(args[1].asNumber()));
return Value::undefined();
}));
}
@@ -7,12 +7,11 @@
#pragma once
#include "JSINativeModules.h"
#include <cxxreact/JSBigString.h>
#include <cxxreact/JSExecutor.h>
#include <cxxreact/RAMBundleRegistry.h>
#include <jsi/jsi.h>
#include <jsireact/JSINativeModules.h>
#include <functional>
#include <mutex>
#include <optional>
@@ -25,8 +25,7 @@
using namespace ::testing;
using namespace std::literals::chrono_literals;
using namespace std::literals::string_literals;
using folly::dynamic, folly::parseJson, folly::toJson, folly::format,
folly::sformat;
using folly::dynamic, folly::toJson, folly::sformat;
namespace facebook::react::jsinspector_modern {
@@ -11,6 +11,7 @@
#include <folly/json.h>
#include <array>
#include <mutex>
namespace facebook::react::jsinspector_modern {
@@ -304,7 +305,9 @@ folly::dynamic PerformanceTracer::serializeTraceEvent(TraceEvent event) const {
folly::dynamic result = folly::dynamic::object;
if (event.id.has_value()) {
result["id"] = folly::sformat("0x{:X}", event.id.value());
std::array<char, 16> buffer{};
snprintf(buffer.data(), buffer.size(), "0x%08x", event.id.value());
result["id"] = buffer.data();
}
result["name"] = event.name;
result["cat"] = event.cat;
@@ -153,12 +153,10 @@ jsi::Value TurboCxxModule::invokeMethod(
CxxModule::Callback second;
if (count < method.callbacks) {
throw std::invalid_argument(folly::to<std::string>(
"Expected ",
method.callbacks,
" callbacks, but only ",
count,
" parameters provided"));
throw std::invalid_argument(
"Expected " + std::to_string(method.callbacks) +
" callbacks, but only " + std::to_string(count) +
" parameters provided");
}
if (method.callbacks == 1) {
@@ -7,7 +7,6 @@
#pragma once
#include <folly/Conv.h>
#include <folly/dynamic.h>
#include <react/debug/react_native_expect.h>
#include <react/renderer/attributedstring/AttributedString.h>
@@ -250,7 +249,7 @@ inline void fromRawValue(
}
inline std::string toString(const FontWeight& fontWeight) {
return folly::to<std::string>((int)fontWeight);
return std::to_string((int)fontWeight);
}
inline void fromRawValue(
@@ -967,8 +966,8 @@ inline void fromRawValue(
}
inline std::string toString(const AttributedString::Range& range) {
return "{location: " + folly::to<std::string>(range.location) +
", length: " + folly::to<std::string>(range.length) + "}";
return "{location: " + std::to_string(range.location) +
", length: " + std::to_string(range.length) + "}";
}
#ifdef ANDROID
@@ -376,8 +376,8 @@ std::string ShadowNode::getDebugName() const {
}
std::string ShadowNode::getDebugValue() const {
return "r" + folly::to<std::string>(revision_) + "/sr" +
folly::to<std::string>(state_ ? state_->getRevision() : 0) +
return "r" + std::to_string(revision_) + "/sr" +
std::to_string(state_ ? state_->getRevision() : 0) +
(getSealed() ? "/sealed" : "") +
(getProps()->nativeId.empty() ? "" : "/id=" + getProps()->nativeId);
}
@@ -399,7 +399,7 @@ SharedDebugStringConvertibleList ShadowNode::getDebugChildren() const {
SharedDebugStringConvertibleList ShadowNode::getDebugProps() const {
return props_->getDebugProps() +
SharedDebugStringConvertibleList{
debugStringConvertibleItem("tag", folly::to<std::string>(getTag()))};
debugStringConvertibleItem("tag", std::to_string(getTag()))};
}
#endif
@@ -7,12 +7,14 @@
#pragma once
#include <array>
#include <unordered_map>
#include <glog/logging.h>
#include <react/debug/react_native_expect.h>
#include <react/renderer/core/PropsParserContext.h>
#include <react/renderer/core/RawProps.h>
#include <react/renderer/debug/DebugStringConvertible.h>
#include <react/renderer/graphics/Color.h>
#include <react/renderer/graphics/Float.h>
#include <react/renderer/graphics/PlatformColorParser.h>
@@ -44,11 +46,16 @@ inline folly::dynamic toDynamic(const SharedColor& color) {
inline std::string toString(const SharedColor& value) {
ColorComponents components = colorComponentsFromColor(value);
auto ratio = 255.f;
return "rgba(" + folly::to<std::string>(round(components.red * ratio)) +
", " + folly::to<std::string>(round(components.green * ratio)) + ", " +
folly::to<std::string>(round(components.blue * ratio)) + ", " +
folly::to<std::string>(round(components.alpha * ratio)) + ")";
std::array<char, 255> buffer{};
std::snprintf(
buffer.data(),
buffer.size(),
"rgba(%.0f, %.0f, %.0f, %.0f)",
components.red * 255.f,
components.green * 255.f,
components.blue * 255.f,
components.alpha * 255.f);
return buffer.data();
}
#pragma mark - Geometry
@@ -208,14 +215,14 @@ inline void fromRawValue(
LOG(ERROR) << "Unsupported CornerInsets type";
}
#if RN_DEBUG_STRING_CONVERTIBLE
inline std::string toString(const Point& point) {
return "{" + folly::to<std::string>(point.x) + ", " +
folly::to<std::string>(point.y) + "}";
return "{" + toString(point.x) + ", " + toString(point.y) + "}";
}
inline std::string toString(const Size& size) {
return "{" + folly::to<std::string>(size.width) + ", " +
folly::to<std::string>(size.height) + "}";
return "{" + toString(size.width) + ", " + toString(size.height) + "}";
}
inline std::string toString(const Rect& rect) {
@@ -223,17 +230,18 @@ inline std::string toString(const Rect& rect) {
}
inline std::string toString(const EdgeInsets& edgeInsets) {
return "{" + folly::to<std::string>(edgeInsets.left) + ", " +
folly::to<std::string>(edgeInsets.top) + ", " +
folly::to<std::string>(edgeInsets.right) + ", " +
folly::to<std::string>(edgeInsets.bottom) + "}";
return "{" + toString(edgeInsets.left) + ", " + toString(edgeInsets.top) +
", " + toString(edgeInsets.right) + ", " + toString(edgeInsets.bottom) +
"}";
}
inline std::string toString(const CornerInsets& cornerInsets) {
return "{" + folly::to<std::string>(cornerInsets.topLeft) + ", " +
folly::to<std::string>(cornerInsets.topRight) + ", " +
folly::to<std::string>(cornerInsets.bottomLeft) + ", " +
folly::to<std::string>(cornerInsets.bottomRight) + "}";
return "{" + toString(cornerInsets.topLeft) + ", " +
toString(cornerInsets.topRight) + ", " +
toString(cornerInsets.bottomLeft) + ", " +
toString(cornerInsets.bottomRight) + "}";
}
#endif
} // namespace facebook::react
@@ -7,8 +7,11 @@
#include "DebugStringConvertible.h"
#include <folly/Conv.h>
#include <folly/Format.h>
#include <array>
#include <cinttypes>
#include <cstdio>
#include <double-conversion/double-conversion.h>
namespace facebook::react {
@@ -125,26 +128,34 @@ SharedDebugStringConvertibleList DebugStringConvertible::getDebugProps() const {
/*
* `toString`-family implementation.
*/
std::string toString(const std::string& value) {
return value;
}
std::string toString(const int& value) {
return folly::to<std::string>(value);
}
std::string toString(const bool& value) {
return folly::to<std::string>(value);
}
std::string toString(const float& value) {
return folly::to<std::string>(value);
}
std::string toString(const double& value) {
return folly::to<std::string>(value);
// Format taken from folly's toString
static double_conversion::DoubleToStringConverter conv(
0,
"Infinity",
"NaN",
'E',
-6, // detail::kConvMaxDecimalInShortestLow,
21, // detail::kConvMaxDecimalInShortestHigh,
6, // max leading padding zeros
1); // max trailing padding zeros
std::array<char, 256> buffer{};
double_conversion::StringBuilder builder(buffer.data(), buffer.size());
conv.ToShortest(value, &builder);
return builder.Finalize();
}
std::string toString(const void* value) {
if (value == nullptr) {
return "null";
}
return folly::sformat("0x{0:016x}", reinterpret_cast<size_t>(value));
std::array<char, 20> buffer{};
std::snprintf(
buffer.data(),
buffer.size(),
"0x%" PRIXPTR,
reinterpret_cast<uintptr_t>(value));
return buffer.data();
}
#endif
@@ -90,15 +90,24 @@ class DebugStringConvertible {};
/*
* Set of particular-format-opinionated functions that convert base types to
* `std::string`; practically incapsulate `folly:to<>` and `folly::format`.
* `std::string`
*/
std::string toString(const std::string& value);
std::string toString(const int& value);
std::string toString(const bool& value);
std::string toString(const float& value);
std::string toString(const double& value);
std::string toString(const void* value);
inline std::string toString(const std::string& value) {
return value;
}
inline std::string toString(const int& value) {
return std::to_string(value);
}
inline std::string toString(const bool& value) {
return value ? "true" : "false";
}
inline std::string toString(const float& value) {
return toString(static_cast<double>(value));
}
template <typename T>
std::string toString(const std::optional<T>& value) {
if (!value) {
@@ -330,7 +330,7 @@ void ReactInstance::registerSegment(
<< segmentId;
runtimeScheduler_->scheduleWork([=](jsi::Runtime& runtime) {
TraceSection s("ReactInstance::registerSegment");
const auto tag = folly::to<std::string>(segmentId);
auto tag = std::to_string(segmentId);
auto script = JSBigFileString::fromPath(segmentPath);
if (script->size() == 0) {
throw std::invalid_argument(