Skip to content

Commit

Permalink
feat: Move Hash.hpp into core codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
mrousavy committed Jul 13, 2024
1 parent d2b0ded commit 1186148
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 15 deletions.
16 changes: 1 addition & 15 deletions packages/nitro-codegen/src/createPlatformSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,8 +324,7 @@ ${createFileMetadataString(`${typename}.hpp`)}
#pragma once
#include <cstddef>
#include <cstdint>
#include <NitroModules/Hash.hpp>
#include <NitroModules/JSIConverter.hpp>
enum class ${typename} {
Expand All @@ -336,19 +335,6 @@ namespace margelo {
// C++ ${typename} <> JS ${typename} (union)
template <> struct JSIConverter<${typename}> {
static constexpr uint64_t hashString(const char* str, size_t length) {
// Uses the FNV-1a hashing algorithm
uint64_t hash = 14695981039346656037ull; // FNV offset basis
const uint64_t fnv_prime = 1099511628211ull;
for (size_t i = 0; i < length; ++i) {
hash ^= static_cast<uint64_t>(str[i]);
hash *= fnv_prime;
}
return hash;
}
static ${typename} fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
std::string unionValue = JSIConverter<std::string>::fromJSI(runtime, arg);
switch (hashString(unionValue.c_str(), unionValue.size())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "Dispatcher.hpp"
#include "FunctionCache.hpp"
#include "ArrayBuffer.hpp"
#include "Hash.hpp"
#include <array>
#include <future>
#include <jsi/jsi.h>
Expand Down
33 changes: 33 additions & 0 deletions packages/react-native-nitro-modules/cpp/utils/Hash.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//
// Hash.hpp
// Pods
//
// Created by Marc Rousavy on 14.07.24.
//

#pragma once

#include <cstddef>
#include <cstdint>

namespace margelo {

/**
* Hashes the given C-String using the FNV-1a hashing algorithm.
*
* This function can be used at compile time as a constexpr to build
* statically optimized switch statements.
*/
constexpr uint64_t hashString(const char* str, size_t length) {
uint64_t hash = 14695981039346656037ull; // FNV offset basis
const uint64_t fnv_prime = 1099511628211ull;

for (size_t i = 0; i < length; ++i) {
hash ^= static_cast<uint64_t>(str[i]);
hash *= fnv_prime;
}

return hash;
}

}

0 comments on commit 1186148

Please sign in to comment.