rtengine/src/tools/assetc/uidtable.c
2024-01-16 16:10:56 +01:00

69 lines
2.0 KiB
C

#include "processing.h"
#include "utils.h"
#define RT_DEFINE_UIDTAB_FILE_STRUCTURES
#include "runtime/threading.h"
#include "runtime/uidtab.h"
#include <xxhash/xxhash.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
static rt_uidtab_entry *_entries;
static size_t _entry_capacity;
static size_t _entry_count;
rt_uid rtCalculateUID(const char *name) {
assert(sizeof(XXH32_hash_t) == sizeof(rt_uid));
size_t len = strlen(name);
return (rt_uid)XXH32(name, len, 0);
}
rt_result rtAddUIDTabEntry(rt_file_id package_fid, rt_uid uid, uint64_t offset, uint64_t size) {
assert(rtIsMainThread());
if (_entry_count == _entry_capacity) {
size_t new_cap = (_entry_capacity > 0) ? _entry_capacity * 2 : 256;
void *t = realloc(_entries, sizeof(rt_uidtab_entry) * new_cap);
if (!t)
return RT_UNKNOWN_ERROR;
_entry_capacity = new_cap;
_entries = t;
}
_entries[_entry_count].file = package_fid;
_entries[_entry_count].offset = offset;
_entries[_entry_count].size = size;
_entries[_entry_count].uid = uid;
_entry_count++;
return RT_SUCCESS;
}
rt_result rtWriteUIDTab(void) {
rt_uidtab_header header;
XXH64_hash_t checksum = XXH3_64bits(_entries, sizeof(rt_uidtab_entry) * _entry_count);
XXH64_canonicalFromHash(&header.checksum, checksum);
header.num_entries = (uint32_t)_entry_count;
FILE *f = fopen("data/uidtab.bin", "wb");
if (!f) {
rtReportError("ASSETC", "Failed to open 'uidtab.bin' for writing.");
return RT_UNKNOWN_ERROR;
}
if (fwrite(&header, sizeof(header), 1, f) != 1) {
rtReportError("ASSETC", "Failed to write header to 'uidtab.bin'");
fclose(f);
return RT_UNKNOWN_ERROR;
}
if (fwrite(_entries, sizeof(rt_uidtab_entry), _entry_count, f) != _entry_count) {
rtReportError("ASSETC", "Failed to write entries to 'uidtab.bin'");
fclose(f);
return RT_UNKNOWN_ERROR;
}
fclose(f);
return RT_SUCCESS;
}