Files
nitro/packages/react-native-nitro-modules/cpp/utils/FastVectorCopy.hpp
T
Marc RousavyandGitHub 03e4c5098c perf: Allow fast path for primitively copyable arrays (#867)
* perf: Allow fast path for primitively copyable arrays

* feat: Better fast copy to Swift

* idk if this makes a difference tbh

* More readable

* fix: Use `std::span` to make it safer

* fix: Allow fast path for simple `memcpy`

* Update NitroTest-Swift-Cxx-Bridge.hpp

* feat: Move to `FastVectorCopy`

* fix: Just check if `needsSpecialHandling`

* chore: Lint C++

* fix: Name prefixes

* fix: Replace `reserve` with alloc
2025-09-24 12:22:08 +02:00

42 lines
1008 B
C++

//
// FastVectorCopy.hpp
// NitroModules
//
// Created by Marc Rousavy on 22.09.25.
//
#pragma once
#include <span>
#include <type_traits>
#include <vector>
namespace margelo::nitro {
/**
* Copies `data` into an `std::vector` as fast as possible.
*
* If the type is trivially copyable (aka if it does not have a copy constructor),
* the data will be bulk-memcopied.
*/
template <typename T>
std::vector<T> FastVectorCopy(const T* data, size_t size) {
if (data == nullptr || size == 0) [[unlikely]] {
// It's an empty vector.
return std::vector<T>();
}
if constexpr (std::is_trivially_copyable_v<T>) {
// FAST: Type does not have a copy constructor - simply memcpy it
std::vector<T> vector(size);
std::memcpy(vector.data(), data, size * sizeof(T));
return vector;
} else {
// SLOW: Type needs to be iterated to copy-construct it
std::span<const T> span(data, size);
return std::vector<T>(span.begin(), span.end());
}
}
} // namespace margelo::nitro