Skip to content

Instantly share code, notes, and snippets.

@norcalli
Created October 6, 2021 23:55
Show Gist options
  • Save norcalli/1e6ec61fb65fd4baa52b130417e722f8 to your computer and use it in GitHub Desktop.
Save norcalli/1e6ec61fb65fd4baa52b130417e722f8 to your computer and use it in GitHub Desktop.
// runc clang: -g -shared -fPIC -maes -mssse3
#include "/k/runc/include/sqlite-amalgamation-3360000//sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#include "/k/runc/include/ak/ak_types.h"
#include "/k/runc/include/meow_hash/meow_hash_x64_aesni.h"
#include <assert.h>
static void
sq_meowhash(
sqlite3_context* context,
int argc,
sqlite3_value** argv)
{
assert(argc == 1);
u8_array Blob = {};
if (sqlite3_value_type(argv[0]) == SQLITE_BLOB)
{
usize Length = sqlite3_value_bytes(argv[0]);
Blob = (u8_array){
(u8*)sqlite3_value_blob(argv[0]),
Length,
};
}
else if (sqlite3_value_type(argv[0]) == SQLITE_TEXT)
{
usize Length = sqlite3_value_bytes(argv[0]);
Blob = (u8_array){
(u8*)sqlite3_value_text(argv[0]),
Length,
};
}
else
{
sqlite3_result_error(context, "invalid input (need text or blob)", -1);
return;
}
// TODO use 000000000 for empty inputs or do the hash?
meow_u128 HashValue = _mm_setzero_si128();
if (ArrayIsNotEmpty(Blob))
{
u8 KeySeed[ARRAYLEN(MeowDefaultSeed)];
HashValue = MeowHash(KeySeed, Blob.Length, Blob.Data);
}
else
{
sqlite3_result_error(context, "empty input", -1);
}
int FormattedLength = 8 * 4 + 3;
char* HashFormatted = sqlite3_mprintf("%08X-%08X-%08X-%08X",
MeowU32From(HashValue, 3),
MeowU32From(HashValue, 2),
MeowU32From(HashValue, 1),
MeowU32From(HashValue, 0));
sqlite3_result_text(context, HashFormatted, FormattedLength, sqlite3_free);
}
#ifdef _WIN32
__declspec(dllexport)
#endif
int sqlite3_sqmeowhash_init(
sqlite3* db,
char** pzErrMsg,
const sqlite3_api_routines* pApi)
{
int rc = SQLITE_OK;
SQLITE_EXTENSION_INIT2(pApi);
(void)pzErrMsg; /* Unused parameter */
// clang-format off
#define CheckError() if (rc != SQLITE_OK) return rc
// clang-format on
rc = sqlite3_create_function(db,
"meowhash",
1, /* narg */
SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
0,
sq_meowhash,
0,
0);
CheckError();
return rc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment