diff --git a/LICENSES/BSD-2-Clause b/LICENSES/BSD-2-Clause index 6c86157a..6535ce92 100644 --- a/LICENSES/BSD-2-Clause +++ b/LICENSES/BSD-2-Clause @@ -1,5 +1,3 @@ -Copyright (c) 2010, Andrea Mazzoleni. All rights reserved. - Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: diff --git a/cmdline/museair.c b/cmdline/museair.c index 8bbf8e92..2f765e9e 100644 --- a/cmdline/museair.c +++ b/cmdline/museair.c @@ -150,7 +150,7 @@ static const uint64_t MUSEAIR_CONSTANT[13] = { do { \ l = a; \ h = b; \ - util_mum(&l, &h); \ + tommy_mum(&l, &h); \ } while (0) #define likely(a) tommy_likely(a) diff --git a/cmdline/scan.c b/cmdline/scan.c index cc316bc4..1664ca05 100644 --- a/cmdline/scan.c +++ b/cmdline/scan.c @@ -20,8 +20,8 @@ static const char* es(int err) * If the file metadata (size and timestamp) is known to be synchronized with disk. * * Always set on POSIX where stat()/lstat() returns coherent metadata. On Windows NTFS, - * directory enumeration may return stale size/mtime for hardlinks until synchronized - * via lstat_sync() (GetFileInformationByHandle). + * directory enumeration may return stale size/mtime for open/modified files and hardlinks + * until synchronized via lstat_sync() (GetFileInformationByHandle). */ #define DISCOVERY_IS_SCAN_SYNCED 0x1 @@ -1655,13 +1655,24 @@ static int scan_sub(struct snapraid_scan* scan, int level, int is_diff, char* pa if (!st) st = DSTAT(path_next, dd, &st_buf); + existing = tommy_hashdyn_search(&disk->pathset, file_path_compare_to_arg, sub_next, file_path_hash(sub_next)); + if (existing) + file_flag_set(existing, FILE_IS_DISCOVERED); + #if HAVE_LSTAT_SYNC /* * In Windows fast directory enumeration, st_ino may be missing (0). - * Only st_ino is required for file identity and hardlink tracking; - * we call lstat_sync() only when st_ino is missing to avoid expensive file opens. + * In addition, directory enumeration may report stale size and mtime + * for files currently open or being written to. + * Refresh via lstat_sync() if st_ino is missing, or if the metadata + * is not synchronized and the file is new or modified. */ - if (st->st_ino == INODE_INVALID) { + if (st->st_ino == INODE_INVALID + || (st->st_sync == 0 + && (!existing + || existing->size != st->st_size + || existing->mtime_sec != st->st_mtime + || existing->mtime_nsec != STAT_NSEC(st)))) { if (lstat_sync(path_next, st, 0) != 0) { /* LCOV_EXCL_START */ log_tag("%s:%u:%s:%s: Stat error. %s.\n", es(errno), 0, disk->name, esc_tag(path_next), strerror(errno)); @@ -1672,10 +1683,6 @@ static int scan_sub(struct snapraid_scan* scan, int level, int is_diff, char* pa } #endif - existing = tommy_hashdyn_search(&disk->pathset, file_path_compare_to_arg, sub_next, file_path_hash(sub_next)); - if (existing) - file_flag_set(existing, FILE_IS_DISCOVERED); - scan_file_discover(scan, sub_next, st); processed = 1; } else { @@ -1937,8 +1944,8 @@ static int state_diffscan(struct snapraid_state* state, int is_diff) * - Each disk is read only by its scan thread, enumerating files and populating * file_discovery_list without observable SnapRAID classification side effects. * - No old file, link, directory, or parity allocation is removed. - * - Inode collisions on volatile-hardlink filesystems trigger selective lstat_sync() - * to normalize authoritative metadata across hardlink groups before Apply. + * - New/modified files and inode collisions on volatile filesystems trigger selective + * lstat_sync() to obtain authoritative metadata before Apply. */ for (i = scanlist; i != 0; i = i->next) { struct snapraid_scan* scan = i->data; diff --git a/cmdline/selftest.c b/cmdline/selftest.c index ccd02188..9b242774 100644 --- a/cmdline/selftest.c +++ b/cmdline/selftest.c @@ -51,25 +51,25 @@ struct hash_test_vector { * Test vectors for tommy_hash32 */ static struct hash32_test_vector TEST_HASH32[] = { - { "", 0, 0x3ba63d24, 0xa766795d }, - { "a", 1, 0xc27589e2, 0xa766795d }, - { "abc", 3, 0x4f0589dd, 0xa766795d }, - { "message digest", 14, 0x7bd2e191, 0xa766795d }, - { "abcdefghijklmnopqrstuvwxyz", 26, 0xa1eebba8, 0xa766795d }, - { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 62, 0xc84d4c51, 0xa766795d }, - { "The quick brown fox jumps over the lazy dog", 43, 0x294e8a7b, 0xa766795d }, - { "\x00", 1, 0x3e1fbed8, 0xa766795d }, - { "\x16\x27", 2, 0x00233fc6, 0xa766795d }, - { "\xe2\x56\xb4", 3, 0xd3f61ec1, 0xa766795d }, - { "\xc9\x4d\x9c\xda", 4, 0xfa10da80, 0xa766795d }, - { "\x79\xf1\x29\x69\x5d", 5, 0xcd5e7468, 0xa766795d }, - { "\x00\x7e\xdf\x1e\x31\x1c", 6, 0x8ba76f9b, 0xa766795d }, - { "\x2a\x4c\xe1\xff\x9e\x6f\x53", 7, 0xbf2129d0, 0xa766795d }, - { "\xba\x02\xab\x18\x30\xc5\x0e\x8a", 8, 0xc3d26370, 0xa766795d }, - { "\xec\x4e\x7a\x72\x1e\x71\x2a\xc9\x33", 9, 0xa6840538, 0xa766795d }, - { "\xfd\xe2\x9c\x0f\x72\xb7\x08\xea\xd0\x78", 10, 0x36115feb, 0xa766795d }, - { "\x65\xc4\x8a\xb8\x80\x86\x9a\x79\x00\xb7\xae", 11, 0x48a3b1fb, 0xa766795d }, - { "\x77\xe9\xd7\x80\x0e\x3f\x5c\x43\xc8\xc2\x46\x39", 12, 0x23412f54, 0xa766795d }, + { "", 0, 0x1138f522, 0xa766795d }, + { "a", 1, 0x3366e86d, 0xa766795d }, + { "abc", 3, 0x7a017599, 0xa766795d }, + { "message digest", 14, 0xd11d9402, 0xa766795d }, + { "abcdefghijklmnopqrstuvwxyz", 26, 0x9e379e7b, 0xa766795d }, + { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 62, 0x429490b3, 0xa766795d }, + { "The quick brown fox jumps over the lazy dog", 43, 0xa720287c, 0xa766795d }, + { "\x00", 1, 0xf0afd007, 0xa766795d }, + { "\x16\x27", 2, 0x7d78b59a, 0xa766795d }, + { "\xe2\x56\xb4", 3, 0x1690ec86, 0xa766795d }, + { "\xc9\x4d\x9c\xda", 4, 0xa9efc35d, 0xa766795d }, + { "\x79\xf1\x29\x69\x5d", 5, 0xf138ecc1, 0xa766795d }, + { "\x00\x7e\xdf\x1e\x31\x1c", 6, 0xb3f64b75, 0xa766795d }, + { "\x2a\x4c\xe1\xff\x9e\x6f\x53", 7, 0x27f94e67, 0xa766795d }, + { "\xba\x02\xab\x18\x30\xc5\x0e\x8a", 8, 0x3770a9f5, 0xa766795d }, + { "\xec\x4e\x7a\x72\x1e\x71\x2a\xc9\x33", 9, 0xd98ebad1, 0xa766795d }, + { "\xfd\xe2\x9c\x0f\x72\xb7\x08\xea\xd0\x78", 10, 0xe7f0bdc0, 0xa766795d }, + { "\x65\xc4\x8a\xb8\x80\x86\x9a\x79\x00\xb7\xae", 11, 0xaf9a9089, 0xa766795d }, + { "\x77\xe9\xd7\x80\x0e\x3f\x5c\x43\xc8\xc2\x46\x39", 12, 0x605ceb65, 0xa766795d }, { 0, 0, 0, 0 } }; @@ -77,29 +77,29 @@ static struct hash32_test_vector TEST_HASH32[] = { * Test vectors for tommy_strhash32 */ struct strhash32_test_vector TEST_STRHASH32[] = { - { "", 0x3ba63d24, 0xa766795d }, - { "a", 0xc27589e2, 0xa766795d }, - { "abc", 0x4f0589dd, 0xa766795d }, - { "message digest", 0x7bd2e191, 0xa766795d }, - { "abcdefghijklmnopqrstuvwxyz", 0xa1eebba8, 0xa766795d }, - { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 0xc84d4c51, 0xa766795d }, - { "The quick brown fox jumps over the lazy dog", 0x294e8a7b, 0xa766795d }, - { "\xff", 0x6ae84401, 0xa766795d }, - { "\x16\x27", 0x00233fc6, 0xa766795d }, - { "\xe2\x56\xb4", 0xd3f61ec1, 0xa766795d }, - { "\xc9\x4d\x9c\xda", 0xfa10da80, 0xa766795d }, - { "\x79\xf1\x29\x69\x5d", 0xcd5e7468, 0xa766795d }, - { "\xff\x7e\xdf\x1e\x31\x1c", 0xe135b2e2, 0xa766795d }, - { "\x2a\x4c\xe1\xff\x9e\x6f\x53", 0xbf2129d0, 0xa766795d }, - { "\xba\x02\xab\x18\x30\xc5\x0e\x8a", 0xc3d26370, 0xa766795d }, - { "\xec\x4e\x7a\x72\x1e\x71\x2a\xc9\x33", 0xa6840538, 0xa766795d }, - { "\xfd\xe2\x9c\x0f\x72\xb7\x08\xea\xd0\x78", 0x36115feb, 0xa766795d }, - { "\x65\xc4\x8a\xb8\x80\x86\x9a\x79\xff\xb7\xae", 0xef961a79, 0xa766795d }, - { "\x77\xe9\xd7\x80\x0e\x3f\x5c\x43\xc8\xc2\x46\x39", 0x23412f54, 0xa766795d }, - { "\x87\xd8\x61\x61\x4c\x89\x17\x4e\xa1\xa4\xef\x13\xa9", 0x04332eac, 0xa766795d }, - { "\xfe\xa6\x5b\xc2\xda\xe8\x95\xd4\x64\xab\x4c\x39\x58\x29", 0xd3025b16, 0xa766795d }, - { "\x94\x49\xc0\x78\xa0\x80\xda\xc7\x71\x4e\x17\x37\xa9\x7c\x40", 0x4ce44257, 0xa766795d }, - { "\x53\x7e\x36\xb4\x2e\xc9\xb9\xcc\x18\x3e\x9a\x5f\xfc\xb7\xb0\x61", 0x47d86f33, 0xa766795d }, + { "", 0x1138f522, 0xa766795d }, + { "a", 0x3366e86d, 0xa766795d }, + { "abc", 0x7a017599, 0xa766795d }, + { "message digest", 0xd11d9402, 0xa766795d }, + { "abcdefghijklmnopqrstuvwxyz", 0x9e379e7b, 0xa766795d }, + { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 0x429490b3, 0xa766795d }, + { "The quick brown fox jumps over the lazy dog", 0xa720287c, 0xa766795d }, + { "\xff", 0xa9d0ff62, 0xa766795d }, + { "\x16\x27", 0x7d78b59a, 0xa766795d }, + { "\xe2\x56\xb4", 0x1690ec86, 0xa766795d }, + { "\xc9\x4d\x9c\xda", 0xa9efc35d, 0xa766795d }, + { "\x79\xf1\x29\x69\x5d", 0xf138ecc1, 0xa766795d }, + { "\xff\x7e\xdf\x1e\x31\x1c", 0xc9633d79, 0xa766795d }, + { "\x2a\x4c\xe1\xff\x9e\x6f\x53", 0x27f94e67, 0xa766795d }, + { "\xba\x02\xab\x18\x30\xc5\x0e\x8a", 0x3770a9f5, 0xa766795d }, + { "\xec\x4e\x7a\x72\x1e\x71\x2a\xc9\x33", 0xd98ebad1, 0xa766795d }, + { "\xfd\xe2\x9c\x0f\x72\xb7\x08\xea\xd0\x78", 0xe7f0bdc0, 0xa766795d }, + { "\x65\xc4\x8a\xb8\x80\x86\x9a\x79\xff\xb7\xae", 0x1c63af47, 0xa766795d }, + { "\x77\xe9\xd7\x80\x0e\x3f\x5c\x43\xc8\xc2\x46\x39", 0x605ceb65, 0xa766795d }, + { "\x87\xd8\x61\x61\x4c\x89\x17\x4e\xa1\xa4\xef\x13\xa9", 0x1a41ce84, 0xa766795d }, + { "\xfe\xa6\x5b\xc2\xda\xe8\x95\xd4\x64\xab\x4c\x39\x58\x29", 0xae824889, 0xa766795d }, + { "\x94\x49\xc0\x78\xa0\x80\xda\xc7\x71\x4e\x17\x37\xa9\x7c\x40", 0x879c5032, 0xa766795d }, + { "\x53\x7e\x36\xb4\x2e\xc9\xb9\xcc\x18\x3e\x9a\x5f\xfc\xb7\xb0\x61", 0x5234d367, 0xa766795d }, { 0, 0, 0 } }; @@ -107,25 +107,25 @@ struct strhash32_test_vector TEST_STRHASH32[] = { * Test vectors for tommy_hash64 */ static struct hash64_test_vector TEST_HASH64[] = { - { "", 0, 0xf1999eea212f89e6ULL, 0x2f022773a766795dULL }, - { "a", 1, 0x6af55c57ef3cc6e2ULL, 0x2f022773a766795dULL }, - { "abc", 3, 0x8a09859573f3ba72ULL, 0x2f022773a766795dULL }, - { "message digest", 14, 0x08a48193f341bef5ULL, 0x2f022773a766795dULL }, - { "abcdefghijklmnopqrstuvwxyz", 26, 0x8761b9f83f99b36dULL, 0x2f022773a766795dULL }, - { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 62, 0x6f9a23bb4217ad12ULL, 0x2f022773a766795dULL }, - { "The quick brown fox jumps over the lazy dog", 43, 0x33e3651d073f9942ULL, 0x2f022773a766795dULL }, - { "\x00", 1, 0x9360785dad01a14eULL, 0x2f022773a766795dULL }, - { "\x16\x27", 2, 0x9d411c7d088f8c1eULL, 0x2f022773a766795dULL }, - { "\xe2\x56\xb4", 3, 0xa20865547db581afULL, 0x2f022773a766795dULL }, - { "\xc9\x4d\x9c\xda", 4, 0xb4eb664b81e7058dULL, 0x2f022773a766795dULL }, - { "\x79\xf1\x29\x69\x5d", 5, 0xf0b386ad052571b4ULL, 0x2f022773a766795dULL }, - { "\x00\x7e\xdf\x1e\x31\x1c", 6, 0xdd3b8851d859c7d4ULL, 0x2f022773a766795dULL }, - { "\x2a\x4c\xe1\xff\x9e\x6f\x53", 7, 0xa8b94da524aabf49ULL, 0x2f022773a766795dULL }, - { "\xba\x02\xab\x18\x30\xc5\x0e\x8a", 8, 0xb913a803aea6d51dULL, 0x2f022773a766795dULL }, - { "\xec\x4e\x7a\x72\x1e\x71\x2a\xc9\x33", 9, 0xb6961500a25f63beULL, 0x2f022773a766795dULL }, - { "\xfd\xe2\x9c\x0f\x72\xb7\x08\xea\xd0\x78", 10, 0xfa6dccb9650a1d28ULL, 0x2f022773a766795dULL }, - { "\x65\xc4\x8a\xb8\x80\x86\x9a\x79\x00\xb7\xae", 11, 0xc95d0a87ec8c2a98ULL, 0x2f022773a766795dULL }, - { "\x77\xe9\xd7\x80\x0e\x3f\x5c\x43\xc8\xc2\x46\x39", 12, 0x15901950afd60cd2ULL, 0x2f022773a766795dULL }, + { "", 0, 0xf64d2d2164ca4e35ULL, 0x2f022773a766795dULL }, + { "a", 1, 0xcb0b7863fd912608ULL, 0x2f022773a766795dULL }, + { "abc", 3, 0x023adbd4412dfbc2ULL, 0x2f022773a766795dULL }, + { "message digest", 14, 0x8d16f620b58a030eULL, 0x2f022773a766795dULL }, + { "abcdefghijklmnopqrstuvwxyz", 26, 0xa615ea6b87f2b63fULL, 0x2f022773a766795dULL }, + { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 62, 0xb9f145676ebdb4fcULL, 0x2f022773a766795dULL }, + { "The quick brown fox jumps over the lazy dog", 43, 0x99b05c9548b523dcULL, 0x2f022773a766795dULL }, + { "\x00", 1, 0x432204e0ea8617fbULL, 0x2f022773a766795dULL }, + { "\x16\x27", 2, 0x5118c58166c6ab3eULL, 0x2f022773a766795dULL }, + { "\xe2\x56\xb4", 3, 0x29484604a9976acbULL, 0x2f022773a766795dULL }, + { "\xc9\x4d\x9c\xda", 4, 0xf000ac44a9f98f4aULL, 0x2f022773a766795dULL }, + { "\x79\xf1\x29\x69\x5d", 5, 0x9603fc74ec52e5aaULL, 0x2f022773a766795dULL }, + { "\x00\x7e\xdf\x1e\x31\x1c", 6, 0xd39f549b363c8e2bULL, 0x2f022773a766795dULL }, + { "\x2a\x4c\xe1\xff\x9e\x6f\x53", 7, 0x1be47d9f53a2a31dULL, 0x2f022773a766795dULL }, + { "\xba\x02\xab\x18\x30\xc5\x0e\x8a", 8, 0xe3fa24e31af8c4ebULL, 0x2f022773a766795dULL }, + { "\xec\x4e\x7a\x72\x1e\x71\x2a\xc9\x33", 9, 0xef8c3dcec426a25dULL, 0x2f022773a766795dULL }, + { "\xfd\xe2\x9c\x0f\x72\xb7\x08\xea\xd0\x78", 10, 0xed0be01a88bde7cbULL, 0x2f022773a766795dULL }, + { "\x65\xc4\x8a\xb8\x80\x86\x9a\x79\x00\xb7\xae", 11, 0xf9b50d9db5dfa543ULL, 0x2f022773a766795dULL }, + { "\x77\xe9\xd7\x80\x0e\x3f\x5c\x43\xc8\xc2\x46\x39", 12, 0x695329dad2094e8aULL, 0x2f022773a766795dULL }, { 0, 0, 0, 0 } }; diff --git a/cmdline/util.c b/cmdline/util.c index 8cfbde5b..2cc659b6 100644 --- a/cmdline/util.c +++ b/cmdline/util.c @@ -7,6 +7,7 @@ #include "util.h" #include "raid/cpu.h" #include "raid/memory.h" +#include "tommyds/tommyhash.h" /****************************************************************************/ /* memory */ @@ -610,112 +611,6 @@ static inline void util_write64(void* ptr, uint64_t v) memcpy(ptr, &v, sizeof(v)); } -/** - * 64*64 -> 128bit multiply function. - * - * @param A Address of 64-bit number. - * @param B Address of 64-bit number. - * - * Calculates 128-bit C = *A * *B. - * - * Overwrites A contents with C's low 64 bits. - * Overwrites B contents with C's high 64 bits. - */ -#if defined(__x86_64__) || defined(_M_X64) -/** - * This is intentionally placed before the __SIZEOF_INT128__ implementation. - * - * This implementation happens to generate more efficient code. - * While this likely depends only on the compiler, as long as it remains faster, - * we will keep it in this order. - */ -static inline void util_mum(uint64_t* A, uint64_t* B) -{ - uint64_t a = *A; - uint64_t b = *B; - uint64_t low, high; - - __asm__ ( - "mulq %3" - : "=a" (low), "=d" (high) - : "a" (a), "rm" (b) - : "cc" - ); - - *A = low; - *B = high; -} -#elif defined(__SIZEOF_INT128__) -static inline void util_mum(uint64_t* A, uint64_t* B) -{ - __uint128_t product = ((__uint128_t)*A) * ((__uint128_t)*B); - *A = (uint64_t)product; - *B = (uint64_t)(product >> 64); -} -#elif defined(__aarch64__) || defined(_M_ARM64) -/** - * This is intentionally placed after the __SIZEOF_INT128__ implementation. - * - * Although the code looks correct, there is a report of this - * implementation failing the self-test on macOS (Darwin 25.4.0, arm64) - * with Apple clang 21.0.0 (clang-2100.0.123.102). - * - * See: https://github.com/amadvance/snapraid/issues/43 - * - * Note that the implementation is the same of OpenSSL: - * - * #elif defined(__aarch64__) && defined(SIXTY_FOUR_BIT_LONG) - * #if defined(__GNUC__) && __GNUC__ >= 2 - * #define BN_UMULT_HIGH(a, b) ({ \ - * register BN_ULONG ret; \ - * asm ("umulh %0,%1,%2" \ - * : "=r"(ret) \ - * : "r"(a), "r"(b)); \ - * ret; }) - * #endif - * #endif - * - * See: https://github.com/openssl/openssl/blob/0463cbf185680e66a3a8960f10cd33001377d28e/crypto/bn/bn_local.h#L439 - */ -static inline void util_mum(uint64_t* A, uint64_t* B) -{ - uint64_t a = *A; - uint64_t b = *B; - uint64_t low = a * b; - uint64_t high; - __asm__ ( - "umulh %0, %1, %2" - : "=r" (high) - : "r" (a), "r" (b) - ); - *A = low; - *B = high; -} -#else -static inline void util_mum(uint64_t* A, uint64_t* B) -{ - uint64_t a = *A; - uint64_t b = *B; - - uint64_t a_lo = (uint32_t)a; - uint64_t a_hi = a >> 32; - uint64_t b_lo = (uint32_t)b; - uint64_t b_hi = b >> 32; - - uint64_t p0 = a_lo * b_lo; - uint64_t p1 = a_lo * b_hi; - uint64_t p2 = a_hi * b_lo; - uint64_t p3 = a_hi * b_hi; - - uint64_t middle = p1 + (p0 >> 32) + (uint32_t)p2; - uint64_t low = (middle << 32) | (uint32_t)p0; - uint64_t high = p3 + (middle >> 32) + (p2 >> 32); - - *A = low; - *B = high; -} -#endif - int util_selftest(void) { /* rotate left 32-bit */ @@ -748,33 +643,33 @@ int util_selftest(void) if (util_rotr64(0x123456789ABCDEF0ULL, 0) != 0x123456789ABCDEF0ULL) return -1; if (util_rotr64(0x123456789ABCDEF0ULL, 64) != 0x123456789ABCDEF0ULL) return -1; - /* util_mum tests */ + /* tommy_mum tests */ uint64_t a, b; /* small values */ a = 3; b = 4; - util_mum(&a, &b); + tommy_mum(&a, &b); if (a != 12 || b != 0) return -1; /* 1 * anything */ a = 0xFFFFFFFFFFFFFFFFULL; b = 1; - util_mum(&a, &b); + tommy_mum(&a, &b); if (a != 0xFFFFFFFFFFFFFFFFULL || b != 0) return -1; /* (2^32) * (2^32) = 2^64 */ a = 1ULL << 32; b = 1ULL << 32; - util_mum(&a, &b); + tommy_mum(&a, &b); if (a != 0 || b != 1) return -1; /* max uint64 * max uint64 */ a = 0xFFFFFFFFFFFFFFFFULL; b = 0xFFFFFFFFFFFFFFFFULL; - util_mum(&a, &b); + tommy_mum(&a, &b); if (a != 1 || b != 0xFFFFFFFFFFFFFFFEULL) return -1; /* larger random-ish test */ a = 0x0123456789ABCDEFULL; b = 0xFEDCBA9876543210ULL; - util_mum(&a, &b); + tommy_mum(&a, &b); if (a != 0x2236D88FE5618CF0ULL || b != 0x121FA00AD77D742ULL) return -1; return 0; diff --git a/tommyds/tommyarray.c b/tommyds/tommyarray.c index ea96782d..2b9c8261 100644 --- a/tommyds/tommyarray.c +++ b/tommyds/tommyarray.c @@ -115,7 +115,7 @@ TOMMY_API void tommy_array_foreach_arg(tommy_array* array, tommy_foreach_arg_fun } } -TOMMY_API tommy_size_t tommy_array_memory_usage(tommy_array* array) +TOMMY_API tommy_size_t tommy_array_memory_usage(const tommy_array* array) { return array->bucket_max * (tommy_size_t)sizeof(void*); } diff --git a/tommyds/tommyarray.h b/tommyds/tommyarray.h index f4b4b225..e05415e7 100644 --- a/tommyds/tommyarray.h +++ b/tommyds/tommyarray.h @@ -8,13 +8,13 @@ * * The grow operation involves an allocation of a new array segment, without reallocating * the already used memory, and thus **not increasing** the heap fragmentation. - * This also implies that the address of the stored elements never change. + * This also implies that the address of the stored elements never changes. * * Allocated segments grow in size exponentially. */ -#ifndef __TOMMYARRAY_H -#define __TOMMYARRAY_H +#ifndef TOMMY_ARRAY_H +#define TOMMY_ARRAY_H #include "tommytypes.h" @@ -80,6 +80,7 @@ TOMMY_API void tommy_array_resize(tommy_array* array, tommy_size_t size); /** * Removes all elements, preserving the allocated capacity. + * Call tommy_array_shrink() after clearing to restore the initial capacity. * Pointed-to objects are not freed. * The array remains initialized and can be reused immediately. */ @@ -95,9 +96,9 @@ tommy_inline void tommy_array_clear(tommy_array* array) TOMMY_API void tommy_array_shrink(tommy_array* array); /** - * Gets a reference of the element at the specified position. + * Gets a reference to the element at the specified position. * You must be sure that space for this position is already - * allocated calling tommy_array_grow(). + * allocated by calling tommy_array_grow(). */ tommy_inline void** tommy_array_ref(tommy_array* array, tommy_size_t pos) { @@ -112,7 +113,7 @@ tommy_inline void** tommy_array_ref(tommy_array* array, tommy_size_t pos) /** * Sets the element at the specified position. * You must be sure that space for this position is already - * allocated calling tommy_array_grow(). + * allocated by calling tommy_array_grow(). */ tommy_inline void tommy_array_set(tommy_array* array, tommy_size_t pos, void* element) { @@ -122,7 +123,7 @@ tommy_inline void tommy_array_set(tommy_array* array, tommy_size_t pos, void* el /** * Gets the element at the specified position. * You must be sure that space for this position is already - * allocated calling tommy_array_grow(). + * allocated by calling tommy_array_grow(). */ tommy_inline void* tommy_array_get(tommy_array* array, tommy_size_t pos) { @@ -159,15 +160,22 @@ tommy_inline void tommy_array_insert_tail(tommy_array* array, void* element) tommy_inline void* tommy_array_remove_tail(tommy_array* array) { assert(array->count != 0); - void* element = tommy_array_tail(array); - tommy_array_resize(array, array->count - 1); + + tommy_size_t pos = array->count - 1; + void** ptr = tommy_array_ref(array, pos); + void* element = *ptr; + + /* keep unused slots zero so growing within capacity needs no initialization */ + *ptr = 0; + array->count = pos; + return element; } /** * Checks whether the array is empty. */ -tommy_inline tommy_bool_t tommy_array_empty(tommy_array* array) +tommy_inline tommy_bool_t tommy_array_empty(const tommy_array* array) { return array->count == 0; } @@ -175,7 +183,7 @@ tommy_inline tommy_bool_t tommy_array_empty(tommy_array* array) /** * Gets the initialized size of the array. */ -tommy_inline tommy_size_t tommy_array_size(tommy_array* array) +tommy_inline tommy_size_t tommy_array_size(const tommy_array* array) { return array->count; } @@ -183,7 +191,7 @@ tommy_inline tommy_size_t tommy_array_size(tommy_array* array) /** * Gets the number of elements that fit without further allocation. */ -tommy_inline tommy_size_t tommy_array_capacity(tommy_array* array) +tommy_inline tommy_size_t tommy_array_capacity(const tommy_array* array) { return array->bucket_max; } @@ -208,6 +216,10 @@ tommy_inline void tommy_array_swap(tommy_array* first, tommy_array* second) * * \param array Array to iterate. * \param func Function to call with each element. + * + * If the callback frees the objects, the array retains dangling + * pointers. Call tommy_array_clear() before reusing it, or + * tommy_array_done() to release its storage. */ TOMMY_API void tommy_array_foreach(tommy_array* array, tommy_foreach_func* func); @@ -223,7 +235,7 @@ TOMMY_API void tommy_array_foreach_arg(tommy_array* array, tommy_foreach_arg_fun /** * Gets the size of allocated memory. */ -TOMMY_API tommy_size_t tommy_array_memory_usage(tommy_array* array); +TOMMY_API tommy_size_t tommy_array_memory_usage(const tommy_array* array); #endif diff --git a/tommyds/tommyarrayblkof.c b/tommyds/tommyarrayblkof.c index 72e7ce48..a5b1f070 100644 --- a/tommyds/tommyarrayblkof.c +++ b/tommyds/tommyarrayblkof.c @@ -95,6 +95,8 @@ TOMMY_API void tommy_arrayblkof_shrink(tommy_arrayblkof* array) TOMMY_API void tommy_arrayblkof_foreach(tommy_arrayblkof* array, tommy_foreach_func* func) { + /* cache the element size to avoid reloading it after each callback */ + tommy_size_t element_size = array->element_size; tommy_size_t pos = 0; while (pos < array->count) { @@ -107,7 +109,7 @@ TOMMY_API void tommy_arrayblkof_foreach(tommy_arrayblkof* array, tommy_foreach_f for (tommy_size_t i = 0; i < chunk; ++i) { func(ptr); - ptr += array->element_size; + ptr += element_size; } pos += chunk; @@ -116,6 +118,8 @@ TOMMY_API void tommy_arrayblkof_foreach(tommy_arrayblkof* array, tommy_foreach_f TOMMY_API void tommy_arrayblkof_foreach_arg(tommy_arrayblkof* array, tommy_foreach_arg_func* func, void* arg) { + /* cache the element size to avoid reloading it after each callback */ + tommy_size_t element_size = array->element_size; tommy_size_t pos = 0; while (pos < array->count) { @@ -128,14 +132,14 @@ TOMMY_API void tommy_arrayblkof_foreach_arg(tommy_arrayblkof* array, tommy_forea for (tommy_size_t i = 0; i < chunk; ++i) { func(arg, ptr); - ptr += array->element_size; + ptr += element_size; } pos += chunk; } } -TOMMY_API tommy_size_t tommy_arrayblkof_memory_usage(tommy_arrayblkof* array) +TOMMY_API tommy_size_t tommy_arrayblkof_memory_usage(const tommy_arrayblkof* array) { return array->block_capacity * sizeof(array->block[0]) + array->block_count * TOMMY_ARRAYBLKOF_SIZE * array->element_size; } diff --git a/tommyds/tommyarrayblkof.h b/tommyds/tommyarrayblkof.h index b77157cb..be8d15cb 100644 --- a/tommyds/tommyarrayblkof.h +++ b/tommyds/tommyarrayblkof.h @@ -8,21 +8,28 @@ * The directory of block pointers may be reallocated, but element addresses * never change. * - * This is very similar to ::tommy_arrayblk, but it allows to store elements of any + * This is very similar to ::tommy_arrayblk, but it allows storing elements of any * size and not just pointers. * * The container allocates space for elements but never copies user data into * or out of it. tommy_arrayblkof_ref(), tommy_arrayblkof_tail(), and * tommy_arrayblkof_insert_tail() return an element's address so the caller can * read or write it directly. + * + * \note Only types with fundamental alignment requirements are supported. + * Storage is allocated using calloc(), which does not guarantee the alignment + * required by over-aligned types (e.g. _Alignas(32) or _Alignas(64)). + * When storing typed elements, use sizeof(type) as the element size to + * preserve alignment for every element. */ -#ifndef __TOMMYARRAYBLKOF_H -#define __TOMMYARRAYBLKOF_H +#ifndef TOMMY_ARRAYBLKOF_H +#define TOMMY_ARRAYBLKOF_H #include "tommytypes.h" #include /* for assert */ +#include /* for memset */ /******************************************************************************/ /* array */ @@ -51,7 +58,8 @@ typedef struct tommy_arrayblkof_struct { /** * Initializes the array. - * \param element_size Size in byte of the element to store in the array. + * \param array Array to initialize. + * \param element_size Size in bytes of the element to store in the array. */ TOMMY_API void tommy_arrayblkof_init(tommy_arrayblkof* array, tommy_size_t element_size); @@ -90,6 +98,7 @@ TOMMY_API void tommy_arrayblkof_resize(tommy_arrayblkof* array, tommy_size_t siz /** * Removes all elements, preserving the allocated capacity. + * Call tommy_arrayblkof_shrink() after clearing to restore the initial capacity. * The array remains initialized and can be reused immediately. */ tommy_inline void tommy_arrayblkof_clear(tommy_arrayblkof* array) @@ -104,9 +113,9 @@ tommy_inline void tommy_arrayblkof_clear(tommy_arrayblkof* array) TOMMY_API void tommy_arrayblkof_shrink(tommy_arrayblkof* array); /** - * Gets a reference of the element at the specified position. + * Gets a reference to the element at the specified position. * You must be sure that space for this position is already - * allocated calling tommy_arrayblkof_grow(). + * allocated by calling tommy_arrayblkof_grow(). */ tommy_inline void* tommy_arrayblkof_ref(tommy_arrayblkof* array, tommy_size_t pos) { @@ -142,13 +151,19 @@ tommy_inline void* tommy_arrayblkof_insert_tail(tommy_arrayblkof* array) tommy_inline void tommy_arrayblkof_remove_tail(tommy_arrayblkof* array) { assert(array->count != 0); - tommy_arrayblkof_resize(array, array->count - 1); + + tommy_size_t pos = array->count - 1; + void* ptr = tommy_arrayblkof_ref(array, pos); + + /* keep unused slots zero so growing within capacity needs no initialization */ + memset(ptr, 0, array->element_size); + array->count = pos; } /** * Checks whether the array is empty. */ -tommy_inline tommy_bool_t tommy_arrayblkof_empty(tommy_arrayblkof* array) +tommy_inline tommy_bool_t tommy_arrayblkof_empty(const tommy_arrayblkof* array) { return array->count == 0; } @@ -156,7 +171,7 @@ tommy_inline tommy_bool_t tommy_arrayblkof_empty(tommy_arrayblkof* array) /** * Gets the initialized size of the array. */ -tommy_inline tommy_size_t tommy_arrayblkof_size(tommy_arrayblkof* array) +tommy_inline tommy_size_t tommy_arrayblkof_size(const tommy_arrayblkof* array) { return array->count; } @@ -164,7 +179,7 @@ tommy_inline tommy_size_t tommy_arrayblkof_size(tommy_arrayblkof* array) /** * Gets the number of elements that fit without further allocation. */ -tommy_inline tommy_size_t tommy_arrayblkof_capacity(tommy_arrayblkof* array) +tommy_inline tommy_size_t tommy_arrayblkof_capacity(const tommy_arrayblkof* array) { return array->block_count * TOMMY_ARRAYBLKOF_SIZE; } @@ -190,6 +205,11 @@ tommy_inline void tommy_arrayblkof_swap(tommy_arrayblkof* first, tommy_arrayblko * * \param array Array to iterate. * \param func Function to call with each element. + * + * Elements are stored inside the array: passing free() as the callback + * is invalid. A callback may release resources owned by each element, + * but must not free the element itself. Call tommy_arrayblkof_clear() before + * reusing it, or tommy_arrayblkof_done() to release its storage. */ TOMMY_API void tommy_arrayblkof_foreach(tommy_arrayblkof* array, tommy_foreach_func* func); @@ -205,7 +225,7 @@ TOMMY_API void tommy_arrayblkof_foreach_arg(tommy_arrayblkof* array, tommy_forea /** * Gets the size of allocated memory. */ -TOMMY_API tommy_size_t tommy_arrayblkof_memory_usage(tommy_arrayblkof* array); +TOMMY_API tommy_size_t tommy_arrayblkof_memory_usage(const tommy_arrayblkof* array); #endif diff --git a/tommyds/tommychain.h b/tommyds/tommychain.h index 9d00ddc7..3661f18a 100644 --- a/tommyds/tommychain.h +++ b/tommyds/tommychain.h @@ -9,8 +9,8 @@ * Do not use this directly. Use lists instead. */ -#ifndef __TOMMYCHAIN_H -#define __TOMMYCHAIN_H +#ifndef TOMMY_CHAIN_H +#define TOMMY_CHAIN_H #include "tommytypes.h" @@ -69,28 +69,35 @@ tommy_inline void tommy_chain_concat(tommy_node* first_tail, tommy_node* second_ * and must not be used as an independent chain afterward). * \param cmp Comparison function. */ -tommy_inline void tommy_chain_merge(tommy_chain* first, tommy_chain* second, tommy_compare_func* cmp) +tommy_inline void tommy_chain_merge(tommy_chain* tommy_restrict first, tommy_chain* tommy_restrict second, tommy_compare_func* cmp) { - tommy_node* first_i = first->head; + /* + * comparators must not change the chains, so cache these endpoints across calls. + * also caching first_tail caused register spills with GCC and Clang on x86-64. + */ + tommy_node* first_head = first->head; + tommy_node* second_tail = second->tail; + tommy_node* first_i = first_head; tommy_node* second_i = second->head; /* merge */ while (1) { if (cmp(first_i->data, second_i->data) > 0) { tommy_node* next = second_i->next; - if (first_i == first->head) { + if (first_i == first_head) { tommy_chain_concat(second_i, first_i); - first->head = second_i; + first_head = second_i; + first->head = first_head; } else { tommy_chain_splice(first_i->prev, first_i, second_i, second_i); } - if (second_i == second->tail) + if (second_i == second_tail) break; second_i = next; } else { if (first_i == first->tail) { tommy_chain_concat(first_i, second_i); - first->tail = second->tail; + first->tail = second_tail; break; } first_i = first_i->next; @@ -99,14 +106,36 @@ tommy_inline void tommy_chain_merge(tommy_chain* first, tommy_chain* second, tom } /** - * Merges two chains managing special degenerated cases. + * Merges two chains containing one node each. + * \param first First singleton chain (will contain the result). + * \param second Second singleton chain (consumed by the merge; its descriptor is not cleared + * and must not be used as an independent chain afterward). + * \param cmp Comparison function. + */ +tommy_inline void tommy_chain_merge_singleton(tommy_chain* tommy_restrict first, tommy_chain* tommy_restrict second, tommy_compare_func* cmp) +{ + tommy_node* first_node = first->head; + tommy_node* second_node = second->head; + + /* keep equal elements in their original order for a stable sort */ + if (cmp(first_node->data, second_node->data) <= 0) { + tommy_chain_concat(first_node, second_node); + first->tail = second_node; + } else { + tommy_chain_concat(second_node, first_node); + first->head = second_node; + } +} + +/** + * Merges two chains managing special degenerate cases. * It's functionally equivalent to tommy_chain_merge() but faster with already ordered chains. * \param first First chain (will contain the result). * \param second Second chain (consumed by the merge; its descriptor is not cleared * and must not be used as an independent chain afterward). * \param cmp Comparison function. */ -tommy_inline void tommy_chain_merge_degenerated(tommy_chain* first, tommy_chain* second, tommy_compare_func* cmp) +tommy_inline void tommy_chain_merge_degenerated(tommy_chain* tommy_restrict first, tommy_chain* tommy_restrict second, tommy_compare_func* cmp) { /* identify the condition first <= second */ if (cmp(first->tail->data, second->head->data) <= 0) { @@ -130,7 +159,7 @@ tommy_inline void tommy_chain_merge_degenerated(tommy_chain* first, tommy_chain* * Sorts a chain. * It's a stable merge sort using power of 2 buckets, with O(N*log(N)) complexity, * similar to the one used in the SGI STL libraries and in the Linux Kernel, - * but faster on degenerated cases like already ordered lists. + * but faster on degenerate cases like already ordered lists. * * SGI STL stl_list.h * http://www.sgi.com/tech/stl/stl_list.h @@ -145,7 +174,8 @@ tommy_inline void tommy_chain_mergesort(tommy_chain* chain, tommy_compare_func* { /* * Bit buckets of chains. - * Each bucket contains 2^i nodes or it's empty. + * Each bucket contains 2^(i+1) nodes or it's empty. + * The bucket containing an unpaired final node has one node less. * The chain at address TOMMY_BIT_MAX is an independent variable operating as "carry". * We keep it in the same "bit" vector to avoid reports from the valgrind tool sgcheck. */ @@ -166,9 +196,19 @@ tommy_inline void tommy_chain_mergesort(tommy_chain* chain, tommy_compare_func* bit[TOMMY_SIZE_BIT].tail = node; tommy_node* next = node->next; + /* start with a sorted pair to halve the number of bucket insertions */ + if (node != tail) { + node = next; + /* save the next input node before merging can change the links */ + next = node->next; + tommy_chain second = { node, node }; + tommy_chain_merge_singleton(last, &second, cmp); + } + /* add the bit, propagating the carry */ tommy_size_t i = 0; tommy_size_t mask = counter; + while ((mask & 1) != 0) { tommy_chain_merge_degenerated(&bit[i], last, cmp); mask >>= 1; diff --git a/tommyds/tommyhash.c b/tommyds/tommyhash.c index e9add03f..81822b0d 100644 --- a/tommyds/tommyhash.c +++ b/tommyds/tommyhash.c @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: BSD-2-Clause +// SPDX-License-Identifier: BSD-2-Clause AND MIT // Copyright (C) 2010 Andrea Mazzoleni #include "tommyhash.h" @@ -6,320 +6,164 @@ /******************************************************************************/ /* hash */ -#include /* for memcpy, strlen */ +#include /* for memcpy */ /** * Swap endianness. * They are needed only if BigEndian. */ #if defined(__GNUC__) -#define tommy_swap32(x) __builtin_bswap32(x) -#define tommy_swap64(x) __builtin_bswap64(x) +#define tommy_imp_hash_swap32(x) __builtin_bswap32(x) #else -tommy_inline tommy_uint32_t tommy_swap32(tommy_uint32_t v) +tommy_inline tommy_uint32_t tommy_imp_hash_swap32(tommy_uint32_t v) { return ((v & 0xFF000000) >> 24) | ((v & 0x00FF0000) >> 8) | ((v & 0x0000FF00) << 8) | ((v & 0x000000FF) << 24); } - -tommy_inline tommy_uint64_t tommy_swap64(tommy_uint64_t v) -{ - return ((v & 0xFF00000000000000ULL) >> 56) | - ((v & 0x00FF000000000000ULL) >> 40) | - ((v & 0x0000FF0000000000ULL) >> 24) | - ((v & 0x000000FF00000000ULL) >> 8) | - ((v & 0x00000000FF000000ULL) << 8) | - ((v & 0x0000000000FF0000ULL) << 24) | - ((v & 0x000000000000FF00ULL) << 40) | - ((v & 0x00000000000000FFULL) << 56); -} #endif -tommy_inline tommy_uint32_t tommy_le_uint32_read(const void* ptr) +tommy_inline tommy_uint32_t tommy_imp_hash_le_uint32_read(const void* ptr) { tommy_uint32_t v; memcpy(&v, ptr, sizeof(v)); #if defined(WORDS_BIGENDIAN) || defined(__BIG_ENDIAN__) || \ (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) - v = tommy_swap32(v); + v = tommy_imp_hash_swap32(v); #endif return v; } -tommy_inline tommy_uint64_t tommy_le_uint64_read(const void* ptr) +/******************************************************************************/ +/* a5hash */ + +/** + * a5hash32 and a5hash (64-bit) by Aleksey Vaneev, from https://github.com/avaneev/a5hash. + * Adapted from version 5.25 with little-endian word reads. + * Copyright (c) 2025 Aleksey Vaneev. Released under the MIT license, see LICENSES/MIT. + */ + +tommy_inline void tommy_imp_a5hash_mul(tommy_uint32_t a, tommy_uint32_t b, tommy_uint32_t* lo, tommy_uint32_t* hi) { - tommy_uint64_t v; - memcpy(&v, ptr, sizeof(v)); -#if defined(WORDS_BIGENDIAN) || defined(__BIG_ENDIAN__) || \ - (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) - v = tommy_swap64(v); -#endif - return v; + /* both operands are 32-bit; the full product supplies two state words */ + tommy_uint64_t v = (tommy_uint64_t)a * b; + *lo = (tommy_uint32_t)v; + *hi = v >> 32; } -#define tommy_rot(x, k) \ - (((x) << (k)) | ((x) >> (32 - (k)))) - -#define tommy_rot64(x, k) \ - (((x) << (k)) | ((x) >> (64 - (k)))) - TOMMY_API tommy_uint32_t tommy_hash_u32(tommy_uint32_t init_val, const void* void_key, tommy_size_t key_len) { const unsigned char* key = tommy_cast(const unsigned char*, void_key); - const tommy_uint32_t c1 = 0xcc9e2d51; - const tommy_uint32_t c2 = 0x1b873593; - tommy_uint32_t h = init_val; - tommy_size_t nblocks = key_len / 4; - const unsigned char* tail = key + nblocks * 4; + tommy_uint32_t val01 = 0x55555555; + tommy_uint32_t val10 = 0xaaaaaaaa; + tommy_uint32_t h[4] = { 0x243f6a88, 0x85a308d3, 0xfb0bd3ea, 0x0f58fd47 }; + tommy_uint32_t a, b; + tommy_size_t len = key_len; - while (nblocks >= 2) { - tommy_uint32_t k0 = tommy_le_uint32_read(key); - tommy_uint32_t k1 = tommy_le_uint32_read(key + 4); + h[0] ^= key_len; + h[1] ^= key_len; +#if TOMMY_SIZE_BIT == 64 + tommy_imp_a5hash_mul((key_len >> 32) ^ 0x452821e6, (key_len >> 32) ^ 0x38d01377, &h[2], &h[3]); +#endif + tommy_imp_a5hash_mul(h[1] ^ (init_val & val10), h[0] ^ (init_val & val01), &h[0], &h[1]); - k0 *= c1; - k1 *= c1; + if (len <= 16) { + if (len >= 4) { + const unsigned char* tail = key + len - 4; + a = tommy_imp_hash_le_uint32_read(key); + b = tommy_imp_hash_le_uint32_read(tail); + if (len >= 9) { + tommy_size_t offset = (len / 8) * 4; + tommy_uint32_t c = tommy_imp_hash_le_uint32_read(key + offset); + tommy_uint32_t d = tommy_imp_hash_le_uint32_read(tail - offset); + tommy_imp_a5hash_mul(c + h[2], d + h[3], &h[2], &h[3]); + } + } else { + a = 0; + b = 0; + if (len != 0) { + a = key[0]; + if (len >= 2) + a |= key[1] << 8; + if (len == 3) + a |= key[2] << 16; + } + } + } else { + val01 ^= h[0]; + val10 ^= h[1]; + do { + tommy_uint32_t s1 = h[0]; + tommy_uint32_t s4 = h[3]; + tommy_imp_a5hash_mul(tommy_imp_hash_le_uint32_read(key) + h[0], tommy_imp_hash_le_uint32_read(key + 4) + h[1], &h[0], &h[1]); + tommy_imp_a5hash_mul(tommy_imp_hash_le_uint32_read(key + 8) + h[2], tommy_imp_hash_le_uint32_read(key + 12) + h[3], &h[2], &h[3]); + h[0] += val01; + h[1] += s4; + h[2] += s1; + h[3] += val10; + key += 16; + len -= 16; + } while (len > 16); - k0 = tommy_rot(k0, 15); - k1 = tommy_rot(k1, 15); - - k0 *= c2; - k1 *= c2; - - h ^= k0; - h = tommy_rot(h, 13); - h = h * 5 + 0xe6546b64; - - h ^= k1; - h = tommy_rot(h, 13); - h = h * 5 + 0xe6546b64; - - key += 8; - nblocks -= 2; + /* the last words may overlap the previous block, but stay within the input */ + const unsigned char* tail = key + len; + a = tommy_imp_hash_le_uint32_read(tail - 8); + b = tommy_imp_hash_le_uint32_read(tail - 4); + if (len >= 9) { + tommy_uint32_t c = tommy_imp_hash_le_uint32_read(tail - 16); + tommy_uint32_t d = tommy_imp_hash_le_uint32_read(tail - 12); + tommy_imp_a5hash_mul(c + h[2], d + h[3], &h[2], &h[3]); + } } - if (nblocks) { - tommy_uint32_t k = tommy_le_uint32_read(key); - k *= c1; - k = tommy_rot(k, 15); - k *= c2; - h ^= k; - h = tommy_rot(h, 13); - h = h * 5 + 0xe6546b64; - } - - tommy_uint32_t k = 0; - switch (key_len & 3) { - case 3 : k ^= ((tommy_uint32_t)tail[2]) << 16; /* fallthrough */ - case 2 : k ^= ((tommy_uint32_t)tail[1]) << 8; /* fallthrough */ - case 1 : k ^= (tommy_uint32_t)tail[0]; - k *= c1; - k = tommy_rot(k, 15); - k *= c2; - h ^= k; - } - - h ^= (tommy_uint32_t)key_len; - h ^= h >> 16; - h *= 0x85ebca6b; - h ^= h >> 13; - h *= 0xc2b2ae35; - h ^= h >> 16; - - return h; + h[0] ^= h[2]; + h[1] ^= h[3]; + tommy_imp_a5hash_mul(a + h[0], b + h[1], &h[0], &h[1]); + tommy_imp_a5hash_mul(val01 ^ h[0], h[1], &a, &b); + return a ^ b; } TOMMY_API tommy_uint64_t tommy_hash_u64(tommy_uint64_t init_val, const void* void_key, tommy_size_t key_len) { const unsigned char* key = tommy_cast(const unsigned char*, void_key); - const tommy_uint64_t c1 = 0x87c37b91114253d5ULL; - const tommy_uint64_t c2 = 0x4cf5ad432745937fULL; - tommy_uint64_t h = init_val; - tommy_size_t nblocks = key_len / 8; - const unsigned char* tail = key + nblocks * 8; + tommy_uint64_t val01 = 0x5555555555555555ULL; + tommy_uint64_t val10 = 0xaaaaaaaaaaaaaaaaULL; + tommy_uint64_t h[2] = { (0x452821e638d01377ULL ^ key_len) ^ (init_val & val10), (0x243f6a8885a308d3ULL ^ key_len) ^ (init_val & val01) }; + tommy_size_t len = key_len; - while (nblocks >= 2) { - tommy_uint64_t k0 = tommy_le_uint64_read(key); - tommy_uint64_t k1 = tommy_le_uint64_read(key + 8); - - k0 *= c1; - k1 *= c1; - - k0 = tommy_rot64(k0, 31); - k1 = tommy_rot64(k1, 31); - - k0 *= c2; - k1 *= c2; - - h ^= k0; - h = tommy_rot64(h, 27); - h = h * 5 + 0x52dce729ULL; - - h ^= k1; - h = tommy_rot64(h, 27); - h = h * 5 + 0x52dce729ULL; - - key += 16; - nblocks -= 2; + tommy_mum(&h[0], &h[1]); + if (len > 16) { + val01 ^= h[0]; + val10 ^= h[1]; + do { + /* each 64-bit operand puts the first little-endian word in its high half */ + h[0] ^= (tommy_uint64_t)tommy_imp_hash_le_uint32_read(key) << 32 ^ tommy_imp_hash_le_uint32_read(key + 4); + h[1] ^= (tommy_uint64_t)tommy_imp_hash_le_uint32_read(key + 8) << 32 ^ tommy_imp_hash_le_uint32_read(key + 12); + tommy_mum(&h[0], &h[1]); + h[0] += val01; + h[1] += val10; + key += 16; + len -= 16; + } while (len > 16); } - if (nblocks) { - tommy_uint64_t k = tommy_le_uint64_read(key); - k *= c1; - k = tommy_rot64(k, 31); - k *= c2; - h ^= k; - h = tommy_rot64(h, 27); - h = h * 5 + 0x52dce729ULL; + if (len >= 4) { + const unsigned char* tail = key + len - 4; + tommy_size_t offset = (len / 8) * 4; + h[0] ^= (tommy_uint64_t)tommy_imp_hash_le_uint32_read(key) << 32 | tommy_imp_hash_le_uint32_read(tail); + h[1] ^= (tommy_uint64_t)tommy_imp_hash_le_uint32_read(key + offset) << 32 | tommy_imp_hash_le_uint32_read(tail - offset); + } else if (len != 0) { + h[0] ^= key[0]; + if (len >= 2) + h[0] ^= key[1] << 8; + if (len == 3) + h[0] ^= key[2] << 16; } - tommy_uint64_t k = 0; - switch (key_len & 7) { - case 7 : k ^= ((tommy_uint64_t)tail[6]) << 48; /* fallthrough */ - case 6 : k ^= ((tommy_uint64_t)tail[5]) << 40; /* fallthrough */ - case 5 : k ^= ((tommy_uint64_t)tail[4]) << 32; /* fallthrough */ - case 4 : k ^= ((tommy_uint64_t)tail[3]) << 24; /* fallthrough */ - case 3 : k ^= ((tommy_uint64_t)tail[2]) << 16; /* fallthrough */ - case 2 : k ^= ((tommy_uint64_t)tail[1]) << 8; /* fallthrough */ - case 1 : k ^= (tommy_uint64_t)tail[0]; - k *= c1; - k = tommy_rot64(k, 31); - k *= c2; - h ^= k; - } - - h ^= (tommy_uint64_t)key_len; - h ^= h >> 33; - h *= 0xff51afd7ed558ccdULL; - h ^= h >> 33; - h *= 0xc4ceb9fe1a85ec53ULL; - h ^= h >> 33; - - return h; -} - -TOMMY_API tommy_uint32_t tommy_strhash_u32(tommy_uint32_t init_val, const void* void_key) -{ - const unsigned char* p = tommy_cast(const unsigned char*, void_key); - const tommy_uint32_t c1 = 0xcc9e2d51; - const tommy_uint32_t c2 = 0x1b873593; - tommy_uint32_t h = init_val; - tommy_size_t len = 0; - - if (((tommy_uintptr_t)p & 3) != 0) - return tommy_hash_u32(init_val, void_key, strlen(tommy_cast(const char*, void_key))); - - /* - * Fast path: string pointer is already aligned to 4 bytes. - * This assumes page-granularity protection and page boundaries aligned to - * 4 bytes, so each aligned load stays within a readable page. - * The final load may read up to 3 bytes past the terminator and outside - * the allocated object. Staying within the page avoids a page-boundary - * fault, but an out-of-object read is still undefined behavior in ISO C - * and can be reported by ASan. This path assumes the compiler and runtime - * tolerate these overreads. - */ - while (1) { - tommy_uint32_t v = tommy_le_uint32_read(p); - - if (tommy_haszero_u32(v)) { - tommy_uint32_t z = (v - 0x01010101) & ~v & 0x80808080; - tommy_uint_t zero_idx = tommy_ctz_u32(z) / 8; - - if (zero_idx != 0) { - tommy_uint32_t mask = (1U << (zero_idx * 8)) - 1; - tommy_uint32_t k = v & mask; - k *= c1; - k = tommy_rot(k, 15); - k *= c2; - h ^= k; - len += zero_idx; - } - break; - } - - tommy_uint32_t k = v; - k *= c1; - k = tommy_rot(k, 15); - k *= c2; - h ^= k; - h = tommy_rot(h, 13); - h = h * 5 + 0xe6546b64; - - p += 4; - len += 4; - } - - h ^= len; - h ^= h >> 16; - h *= 0x85ebca6b; - h ^= h >> 13; - h *= 0xc2b2ae35; - h ^= h >> 16; - - return h; -} - -TOMMY_API tommy_uint64_t tommy_strhash_u64(tommy_uint64_t init_val, const void* void_key) -{ - const unsigned char* p = tommy_cast(const unsigned char*, void_key); - const tommy_uint64_t c1 = 0x87c37b91114253d5ULL; - const tommy_uint64_t c2 = 0x4cf5ad432745937fULL; - tommy_uint64_t h = init_val; - tommy_size_t len = 0; - - if (((tommy_uintptr_t)p & 7) != 0) - return tommy_hash_u64(init_val, void_key, strlen(tommy_cast(const char*, void_key))); - - /* - * Fast path: string pointer is already aligned to 8 bytes. - * This assumes page-granularity protection and page boundaries aligned to - * 8 bytes, so each aligned load stays within a readable page. - * The final load may read up to 7 bytes past the terminator and outside - * the allocated object. Staying within the page avoids a page-boundary - * fault, but an out-of-object read is still undefined behavior in ISO C - * and can be reported by ASan. This path assumes the compiler and runtime - * tolerate these overreads. - */ - while (1) { - tommy_uint64_t v = tommy_le_uint64_read(p); - - if (tommy_haszero_u64(v)) { - tommy_uint64_t z = (v - 0x0101010101010101ULL) & ~v & 0x8080808080808080ULL; - tommy_uint_t zero_idx = tommy_ctz_u64(z) / 8; - - if (zero_idx != 0) { - tommy_uint64_t mask = (1ULL << (zero_idx * 8)) - 1; - tommy_uint64_t k = v & mask; - k *= c1; - k = tommy_rot64(k, 31); - k *= c2; - h ^= k; - len += zero_idx; - } - break; - } - - tommy_uint64_t k = v; - k *= c1; - k = tommy_rot64(k, 31); - k *= c2; - h ^= k; - h = tommy_rot64(h, 27); - h = h * 5 + 0x52dce729ULL; - - p += 8; - len += 8; - } - - h ^= len; - h ^= h >> 33; - h *= 0xff51afd7ed558ccdULL; - h ^= h >> 33; - h *= 0xc4ceb9fe1a85ec53ULL; - h ^= h >> 33; - - return h; + tommy_mum(&h[0], &h[1]); + h[0] ^= val01; + tommy_mum(&h[0], &h[1]); + return h[0] ^ h[1]; } diff --git a/tommyds/tommyhash.h b/tommyds/tommyhash.h index 13d2113c..16f01210 100644 --- a/tommyds/tommyhash.h +++ b/tommyds/tommyhash.h @@ -3,100 +3,130 @@ /** \file * Hash functions for the use with ::tommy_hashtable, ::tommy_hashdyn and ::tommy_hashlin. + * + * This module provides hash functions designed for in-memory data structures. + * ::tommy_hash_u32 and ::tommy_strhash_u32 use a5hash32, while + * ::tommy_hash_u64 and ::tommy_strhash_u64 use a5hash (64-bit). + * Reversible integer hash functions are also provided for 32-bit and 64-bit keys. + * + * a5hash32 is intended for 32-bit platforms and uses 32-bit operands with + * full 64-bit multiplication results. a5hash uses 64-bit operands with + * full 128-bit multiplication results. Both algorithms pass SMHasher3 tests. + * + * Prefer the 64-bit version whenever possible, as it provides better resistance + * to collisions, particularly with specially crafted inputs. However, neither + * version is designed to resist deliberate collision attacks. If resistance to + * such attacks is required, use a dedicated hash function designed for that purpose. + * + * All hash functions are intended for runtime in-memory use only and not + * for persistent storage, as hash compatibility across different versions of the + * library is not guaranteed. String and sized buffer hash functions produce + * identical results for 0-terminated strings. */ -#ifndef __TOMMYHASH_H -#define __TOMMYHASH_H +#ifndef TOMMY_HASH_H +#define TOMMY_HASH_H #include "tommytypes.h" +#include /* for strlen */ /******************************************************************************/ /* hash */ /** - * Hash function with a 32 bits result. - * Implementation of MurmurHash3 (x86_32) by Austin Appleby, - * from https://github.com/aappleby/smhasher + * Hash function with a 32-bit result. + * Implementation of a5hash32 by Aleksey Vaneev, + * from https://github.com/avaneev/a5hash + * + * This algorithm is compact, fast on short inputs, and passes SMHasher3 tests. * * \param init_val Initialization value. * Using a different initialization value, you can generate a completely different set of hash values. * Use 0 if not relevant. - * \param void_key Pointer to the data to hash. + * \param void_key Pointer to the data to hash. Must not be NULL, even if key_len is 0. * \param key_len Size of the data to hash. * \note * This function is endianness independent and alignment independent. * It produces identical hash results to ::tommy_strhash_u32 for 0-terminated strings. * Compatibility across different versions of the library is not guaranteed: * this hash is intended for in-memory runtime use only and not for persistent storage. - * It is not state-of-the-art against malicious collision attacks, but it is simple and fast. - * \return The hash value of 32 bits. + * It is non-cryptographic and is not designed to protect against malicious collision attacks. + * \return The 32-bit hash value. */ TOMMY_API tommy_uint32_t tommy_hash_u32(tommy_uint32_t init_val, const void* void_key, tommy_size_t key_len); /** - * Hash function with a 64 bits result. - * Implementation of MurmurHash3 (x64_64) by Austin Appleby, - * from https://github.com/aappleby/smhasher + * Hash function with a 64-bit result. + * Implementation of a5hash (64-bit) by Aleksey Vaneev, + * from https://github.com/avaneev/a5hash + * + * This algorithm is compact, fast on short inputs, and passes SMHasher3 tests. * * \param init_val Initialization value. * Using a different initialization value, you can generate a completely different set of hash values. * Use 0 if not relevant. - * \param void_key Pointer to the data to hash. + * \param void_key Pointer to the data to hash. Must not be NULL, even if key_len is 0. * \param key_len Size of the data to hash. * \note * This function is endianness independent and alignment independent. * It produces identical hash results to ::tommy_strhash_u64 for 0-terminated strings. - * Compatibility across different versions of the library is not guaranteed: - * this hash is intended for in-memory runtime use only and not for persistent storage. - * It is not state-of-the-art against malicious collision attacks, but it is simple and fast. - * \return The hash value of 64 bits. + * It is non-cryptographic and is not designed to protect against malicious collision attacks. + * \return The 64-bit hash value. */ TOMMY_API tommy_uint64_t tommy_hash_u64(tommy_uint64_t init_val, const void* void_key, tommy_size_t key_len); /** - * String hash function with a 32 bits result. - * Implementation is based on MurmurHash3 (x86_32) by Austin Appleby, - * from https://github.com/aappleby/smhasher + * String hash function with a 32-bit result. + * Implementation of a5hash32 by Aleksey Vaneev, + * from https://github.com/avaneev/a5hash * * This hash is designed to handle strings with an unknown length. - * If the string is aligned, it operates in a single pass without calling strlen(). + * It is implemented inline using strlen() followed by ::tommy_hash_u32. + * This gives better performance than scanning for the terminator while hashing. * * \param init_val Initialization value. * Using a different initialization value, you can generate a completely different set of hash values. * Use 0 if not relevant. - * \param void_key Pointer to the string to hash. It has to be 0 terminated. + * \param void_key Pointer to the string to hash. It has to be 0-terminated. * \note * This function is endianness independent and alignment independent. + * It produces identical hash results to ::tommy_hash_u32 for 0-terminated strings. * Compatibility across different versions of the library is not guaranteed: * this hash is intended for in-memory runtime use only and not for persistent storage. - * It is not state-of-the-art against malicious collision attacks, but it is simple and fast. - * \return The hash value of 32 bits. + * It is non-cryptographic and is not designed to protect against malicious collision attacks. + * \return The 32-bit hash value. */ -TOMMY_API tommy_uint32_t tommy_strhash_u32(tommy_uint32_t init_val, const void* void_key); +tommy_inline tommy_uint32_t tommy_strhash_u32(tommy_uint32_t init_val, const void* void_key) +{ + return tommy_hash_u32(init_val, void_key, strlen(tommy_cast(const char*, void_key))); +} /** - * String hash function with a 64 bits result. - * Implementation is based on MurmurHash3 (x64_64) by Austin Appleby, - * from https://github.com/aappleby/smhasher + * String hash function with a 64-bit result. + * Implementation of a5hash (64-bit) by Aleksey Vaneev, + * from https://github.com/avaneev/a5hash * * This hash is designed to handle strings with an unknown length. - * If the string is aligned, it operates in a single pass without calling strlen(). + * It is implemented inline using strlen() followed by ::tommy_hash_u64. + * This gives better performance than scanning for the terminator while hashing. * * \param init_val Initialization value. * Using a different initialization value, you can generate a completely different set of hash values. * Use 0 if not relevant. - * \param void_key Pointer to the string to hash. It has to be 0 terminated. + * \param void_key Pointer to the string to hash. It has to be 0-terminated. * \note * This function is endianness independent and alignment independent. - * Compatibility across different versions of the library is not guaranteed: - * this hash is intended for in-memory runtime use only and not for persistent storage. - * It is not state-of-the-art against malicious collision attacks, but it is simple and fast. - * \return The hash value of 64 bits. + * It produces identical hash results to ::tommy_hash_u64 for 0-terminated strings. + * It is non-cryptographic and is not designed to protect against malicious collision attacks. + * \return The 64-bit hash value. */ -TOMMY_API tommy_uint64_t tommy_strhash_u64(tommy_uint64_t init_val, const void* void_key); +tommy_inline tommy_uint64_t tommy_strhash_u64(tommy_uint64_t init_val, const void* void_key) +{ + return tommy_hash_u64(init_val, void_key, strlen(tommy_cast(const char*, void_key))); +} /** - * Integer reversible hash function for 32 bits. + * Reversible 32-bit integer hash function. * Implementation of the Robert Jenkins "4-byte Integer Hashing", * from http://burtleburtle.net/bob/hash/integer.html */ @@ -114,7 +144,7 @@ tommy_inline tommy_uint32_t tommy_inthash_u32(tommy_uint32_t key) } /** - * Integer reversible hash function for 64 bits. + * Reversible 64-bit integer hash function. * Implementation of the Thomas Wang "Integer Hash Function", * from http://web.archive.org/web/20071223173210/http://www.concentric.net/~Ttwang/tech/inthash.htm */ @@ -131,5 +161,105 @@ tommy_inline tommy_uint64_t tommy_inthash_u64(tommy_uint64_t key) return key; } +/******************************************************************************/ +/* multiplication */ + +/** + * Multiply two 64-bit unsigned numbers to obtain the full 128-bit product. + * + * \param A Address of the first operand, overwritten with the low 64 bits of the product. + * \param B Address of the second operand, overwritten with the high 64 bits of the product. + */ +#if defined(_MSC_VER) && defined(_M_X64) +/** + * MSVC x64 does not support inline assembly, so use its full-product intrinsic. + */ +#pragma intrinsic(_umul128) +tommy_inline void tommy_mum(tommy_uint64_t* A, tommy_uint64_t* B) +{ + tommy_uint64_t high; + tommy_uint64_t low = _umul128(*A, *B, &high); + *A = low; + *B = high; +} +#elif defined(_MSC_VER) && defined(_M_ARM64) +#pragma intrinsic(__umulh) +tommy_inline void tommy_mum(tommy_uint64_t* A, tommy_uint64_t* B) +{ + tommy_uint64_t a = *A; + tommy_uint64_t b = *B; + *A = a * b; + *B = __umulh(a, b); +} +#elif defined(__x86_64__) && (defined(__GNUC__) || defined(__clang__)) +/** + * Keep this before __SIZEOF_INT128__ because the explicit mulq generates more efficient code. + */ +tommy_inline void tommy_mum(tommy_uint64_t* A, tommy_uint64_t* B) +{ + tommy_uint64_t a = *A; + tommy_uint64_t b = *B; + tommy_uint64_t low, high; + + /* require a register to avoid Clang spilling the operand before mulq */ + __asm__ ( + "mulq %3" + : "=a" (low), "=d" (high) + : "a" (a), "r" (b) + : "cc" + ); + + *A = low; + *B = high; +} +#elif defined(__SIZEOF_INT128__) +tommy_inline void tommy_mum(tommy_uint64_t* A, tommy_uint64_t* B) +{ + __uint128_t product = (__uint128_t)*A * *B; + *A = product; + *B = product >> 64; +} +#elif defined(__aarch64__) && (defined(__GNUC__) || defined(__clang__)) +/** + * Keep this after __SIZEOF_INT128__ because the assembly path failed optimized + * hash tests on Apple clang 21.0.0. See https://github.com/amadvance/snapraid/issues/43. + */ +tommy_inline void tommy_mum(tommy_uint64_t* A, tommy_uint64_t* B) +{ + tommy_uint64_t a = *A; + tommy_uint64_t b = *B; + tommy_uint64_t low = a * b; + tommy_uint64_t high; + __asm__ ( + "umulh %0, %1, %2" + : "=r" (high) + : "r" (a), "r" (b) + ); + *A = low; + *B = high; +} +#else +tommy_inline void tommy_mum(tommy_uint64_t* A, tommy_uint64_t* B) +{ + tommy_uint64_t a = *A; + tommy_uint64_t b = *B; + tommy_uint64_t a_lo = (tommy_uint32_t)a; + tommy_uint64_t a_hi = a >> 32; + tommy_uint64_t b_lo = (tommy_uint32_t)b; + tommy_uint64_t b_hi = b >> 32; + tommy_uint64_t p0 = a_lo * b_lo; + tommy_uint64_t p1 = a_lo * b_hi; + tommy_uint64_t p2 = a_hi * b_lo; + tommy_uint64_t p3 = a_hi * b_hi; + + /* retain the carry from the middle words in the high half */ + tommy_uint64_t middle = p1 + (p0 >> 32) + (tommy_uint32_t)p2; + tommy_uint64_t low = (middle << 32) | (tommy_uint32_t)p0; + tommy_uint64_t high = p3 + (middle >> 32) + (p2 >> 32); + *A = low; + *B = high; +} +#endif + #endif diff --git a/tommyds/tommyhashdyn.c b/tommyds/tommyhashdyn.c index 2476e229..42cef903 100644 --- a/tommyds/tommyhashdyn.c +++ b/tommyds/tommyhashdyn.c @@ -34,7 +34,7 @@ TOMMY_API void tommy_hashdyn_clear(tommy_hashdyn* hashdyn) /** * Resize the bucket vector. */ -static void tommy_hashdyn_resize(tommy_hashdyn* hashdyn, tommy_uint_t new_bucket_bit) +static void tommy_imp_hashdyn_resize(tommy_hashdyn* hashdyn, tommy_uint_t new_bucket_bit) { tommy_size_t bucket_bit = hashdyn->bucket_bit; tommy_size_t bucket_max = hashdyn->bucket_max; @@ -55,6 +55,11 @@ static void tommy_hashdyn_resize(tommy_hashdyn* hashdyn, tommy_uint_t new_bucket new_bucket[i + bucket_max] = 0; tommy_hashdyn_node* j = hashdyn->bucket[i]; + if (j && !j->next) { + /* growth keeps old buckets separate, and singleton links are already valid */ + new_bucket[j->index & new_bucket_mask] = j; + continue; + } while (j) { tommy_hashdyn_node* j_next = j->next; tommy_size_t pos = j->index & new_bucket_mask; @@ -72,6 +77,11 @@ static void tommy_hashdyn_resize(tommy_hashdyn* hashdyn, tommy_uint_t new_bucket for (tommy_size_t i = 0; i < bucket_max; ++i) { tommy_hashdyn_node* j = hashdyn->bucket[i]; + if (j && !j->next) { + /* growth keeps old buckets separate, and singleton links are already valid */ + new_bucket[j->index & new_bucket_mask] = j; + continue; + } while (j) { tommy_hashdyn_node* j_next = j->next; tommy_size_t pos = j->index & new_bucket_mask; @@ -116,21 +126,21 @@ static void tommy_hashdyn_resize(tommy_hashdyn* hashdyn, tommy_uint_t new_bucket /** * Grow. */ -tommy_inline void hashdyn_grow_step(tommy_hashdyn* hashdyn) +tommy_inline void tommy_imp_hashdyn_grow_step(tommy_hashdyn* hashdyn) { - /* grow if more than 50% full */ + /* grow if at least 50% full */ if (hashdyn->count >= hashdyn->bucket_max / 2) - tommy_hashdyn_resize(hashdyn, hashdyn->bucket_bit + 1); + tommy_imp_hashdyn_resize(hashdyn, hashdyn->bucket_bit + 1); } /** * Shrink. */ -tommy_inline void hashdyn_shrink_step(tommy_hashdyn* hashdyn) +tommy_inline void tommy_imp_hashdyn_shrink_step(tommy_hashdyn* hashdyn) { - /* shrink if less than 12.5% full */ + /* shrink if at most 12.5% full */ if (hashdyn->count <= hashdyn->bucket_max / 8 && hashdyn->bucket_bit > TOMMY_HASHDYN_BIT) - tommy_hashdyn_resize(hashdyn, hashdyn->bucket_bit - 1); + tommy_imp_hashdyn_resize(hashdyn, hashdyn->bucket_bit - 1); } TOMMY_API void tommy_hashdyn_reserve(tommy_hashdyn* hashdyn, tommy_size_t count) @@ -143,7 +153,7 @@ TOMMY_API void tommy_hashdyn_reserve(tommy_hashdyn* hashdyn, tommy_size_t count) if (bucket_bit <= hashdyn->bucket_bit) return; - tommy_hashdyn_resize(hashdyn, bucket_bit); + tommy_imp_hashdyn_resize(hashdyn, bucket_bit); } TOMMY_API void tommy_hashdyn_shrink(tommy_hashdyn* hashdyn) @@ -156,7 +166,7 @@ TOMMY_API void tommy_hashdyn_shrink(tommy_hashdyn* hashdyn) if (bucket_bit >= hashdyn->bucket_bit) return; - tommy_hashdyn_resize(hashdyn, bucket_bit); + tommy_imp_hashdyn_resize(hashdyn, bucket_bit); } TOMMY_API void tommy_hashdyn_insert(tommy_hashdyn* hashdyn, tommy_hashdyn_node* node, void* data, tommy_hash_t hash) @@ -169,16 +179,30 @@ TOMMY_API void tommy_hashdyn_insert(tommy_hashdyn* hashdyn, tommy_hashdyn_node* ++hashdyn->count; - hashdyn_grow_step(hashdyn); + tommy_imp_hashdyn_grow_step(hashdyn); } TOMMY_API void* tommy_hashdyn_insert_unique(tommy_hashdyn* hashdyn, tommy_hashdyn_node* node, void* data, tommy_search_func* cmp, const void* cmp_arg, tommy_hash_t hash) { - void* existing = tommy_hashdyn_search(hashdyn, cmp, cmp_arg, hash); - if (existing) - return existing; + tommy_hashdyn_node** bucket = &hashdyn->bucket[hash & hashdyn->bucket_mask]; + tommy_hashdyn_node* i = *bucket; + + while (i) { + /* compare keys only for matching full hashes, as the bucket may contain different hashes */ + if (i->index == hash && cmp(cmp_arg, i->data) == 0) + return i->data; + i = i->next; + } + + /* insert before resizing, while the bucket selected for the search is still valid */ + tommy_list_insert_tail(bucket, node, data); + + node->index = hash; + + ++hashdyn->count; + + tommy_imp_hashdyn_grow_step(hashdyn); - tommy_hashdyn_insert(hashdyn, node, data, hash); return data; } @@ -201,7 +225,7 @@ TOMMY_API void* tommy_hashdyn_remove_existing(tommy_hashdyn* hashdyn, tommy_hash --hashdyn->count; - hashdyn_shrink_step(hashdyn); + tommy_imp_hashdyn_shrink_step(hashdyn); return node->data; } @@ -218,7 +242,7 @@ TOMMY_API void* tommy_hashdyn_remove(tommy_hashdyn* hashdyn, tommy_search_func* --hashdyn->count; - hashdyn_shrink_step(hashdyn); + tommy_imp_hashdyn_shrink_step(hashdyn); return node->data; } @@ -260,7 +284,7 @@ TOMMY_API void tommy_hashdyn_foreach_arg(tommy_hashdyn* hashdyn, tommy_foreach_a } } -TOMMY_API tommy_size_t tommy_hashdyn_memory_usage(tommy_hashdyn* hashdyn) +TOMMY_API tommy_size_t tommy_hashdyn_memory_usage(const tommy_hashdyn* hashdyn) { return hashdyn->bucket_max * (tommy_size_t)sizeof(hashdyn->bucket[0]) + tommy_hashdyn_count(hashdyn) * (tommy_size_t)sizeof(tommy_hashdyn_node); @@ -268,11 +292,20 @@ TOMMY_API tommy_size_t tommy_hashdyn_memory_usage(tommy_hashdyn* hashdyn) TOMMY_API void tommy_hashdyn_to_list(tommy_hashdyn* hashdyn, tommy_list* list) { - /* move everything to the list */ - for (tommy_size_t pos = 0; pos < hashdyn->bucket_max; ++pos) - tommy_list_concat(list, &hashdyn->bucket[pos]); + tommy_builder builder; + tommy_node* builder_tail = tommy_builder_init(&builder); - /* clear all */ - tommy_hashdyn_clear(hashdyn); + /* clear buckets as they are transferred to avoid a second scan */ + for (tommy_size_t pos = 0; pos < hashdyn->bucket_max; ++pos) { + tommy_node* head = hashdyn->bucket[pos]; + if (head) { + tommy_node* tail = head->prev; + builder_tail = tommy_builder_concat(builder_tail, head, tail); + } + hashdyn->bucket[pos] = 0; + } + + tommy_list_concat_builder(list, &builder, builder_tail); + hashdyn->count = 0; } diff --git a/tommyds/tommyhashdyn.h b/tommyds/tommyhashdyn.h index 457e2c7b..c31f7efa 100644 --- a/tommyds/tommyhashdyn.h +++ b/tommyds/tommyhashdyn.h @@ -110,8 +110,8 @@ * See the \ref multiindex example for more detail. */ -#ifndef __TOMMYHASHDYN_H -#define __TOMMYHASHDYN_H +#ifndef TOMMY_HASHDYN_H +#define TOMMY_HASHDYN_H #include "tommyhash.h" #include "tommylist.h" @@ -156,8 +156,25 @@ TOMMY_API void tommy_hashdyn_init(tommy_hashdyn* hashdyn); */ TOMMY_API void tommy_hashdyn_done(tommy_hashdyn* hashdyn); +/** + * Exchanges the complete state of two initialized hashtables, including bucket allocations. + * The hashtables must not share nodes. Nodes and objects are not accessed or modified. + * Existing node pointers remain valid and belong to the other hashtable. + * Passing the same hashtable twice has no effect. Both hashtables remain usable and deinitializable. + * \param first The first hashtable. + * \param second The second hashtable. + * \note This operation is O(1) with respect to the number of elements. + */ +tommy_inline void tommy_hashdyn_swap(tommy_hashdyn* first, tommy_hashdyn* second) +{ + tommy_hashdyn tmp = *first; + *first = *second; + *second = tmp; +} + /** * Removes all elements, preserving the allocated buckets. + * Call tommy_hashdyn_shrink() after clearing to restore the initial capacity. * The hashtable remains initialized and can be reused immediately. * Objects are not freed and nodes are not accessed or modified. * Their links must not be used to traverse the previous contents. @@ -171,7 +188,10 @@ TOMMY_API void tommy_hashdyn_clear(tommy_hashdyn* hashdyn); * Pre-allocates buckets for the specified number of elements. * * It ensures that the hashtable has enough buckets allocated to contain - * the specified number of elements without triggering a dynamic resize. + * the specified number of elements without triggering a dynamic resize on insertion. + * Subsequent removals retain the normal shrinking policy and may reduce + * the allocated capacity. + * \param hashdyn Hashtable to reserve space in. * \param count Number of elements to reserve space for. */ TOMMY_API void tommy_hashdyn_reserve(tommy_hashdyn* hashdyn, tommy_size_t count); @@ -200,6 +220,7 @@ TOMMY_API void tommy_hashdyn_insert(tommy_hashdyn* hashdyn, tommy_hashdyn_node* * Otherwise, the candidate is inserted using the normal insertion policy, * and its data field is returned. * Objects are not freed by this call. + * \param hashdyn Hashtable to insert into. * \param node The candidate node. It must not belong to any container. * \param data The object to insert. * \param cmp Compare function called with cmp_arg as first argument and with the element to compare as a second one. @@ -215,6 +236,7 @@ TOMMY_API void* tommy_hashdyn_insert_unique(tommy_hashdyn* hashdyn, tommy_hashdy * You have to provide a compare function and the hash of the element you want to remove. * If the element is not found, 0 is returned. * If more equal elements are present, the first one is removed. + * \param hashdyn Hashtable to remove from. * \param cmp Compare function called with cmp_arg as first argument and with the element to compare as a second one. * The function should return 0 for equal elements, anything other for different elements. * \param cmp_arg Compare argument passed as first argument of the compare function. @@ -227,7 +249,8 @@ TOMMY_API void* tommy_hashdyn_remove(tommy_hashdyn* hashdyn, tommy_search_func* * Gets the bucket of the specified hash. * The bucket is guaranteed to contain ALL the elements with the specified hash, * but it can contain also others. - * You can access elements in the bucket following the ::next pointer until 0. + * You can access elements in the bucket following the tommy_node::next pointer until 0. + * \param hashdyn Hashtable to query. * \param hash Hash of the element to find. * \return The head of the bucket, or 0 if empty. */ @@ -240,6 +263,7 @@ tommy_inline tommy_hashdyn_node* tommy_hashdyn_bucket(tommy_hashdyn* hashdyn, to * Searches an element in the hashtable. * You have to provide a compare function and the hash of the element you want to find. * If more equal elements are present, the first one is returned. + * \param hashdyn Hashtable to search. * \param cmp Compare function called with cmp_arg as first argument and with the element to compare as a second one. * The function should return 0 for equal elements, anything other for different elements. * \param cmp_arg Compare argument passed as first argument of the compare function. @@ -276,6 +300,7 @@ TOMMY_API void* tommy_hashdyn_remove_existing(tommy_hashdyn* hashdyn, tommy_hash * The tommy_node::data field and the number of elements are left unchanged. * No memory allocation, deallocation or resize is performed. * Equal keys are allowed; no uniqueness check is performed. + * \param hashdyn Hashtable containing the node. * \param node The node whose hash is updated. * \param hash The new hash of the element. * \note This operation is O(1). @@ -312,6 +337,10 @@ TOMMY_API void tommy_hashdyn_rehash_existing(tommy_hashdyn* hashdyn, tommy_hashd * // deallocates the hashtable * tommy_hashdyn_done(&hashdyn); * \endcode + * + * If the callback frees the objects, the hashtable retains dangling + * node pointers. Call tommy_hashdyn_clear() before reusing it, or + * tommy_hashdyn_done() to release its storage. */ TOMMY_API void tommy_hashdyn_foreach(tommy_hashdyn* hashdyn, tommy_foreach_func* func); @@ -326,7 +355,7 @@ TOMMY_API void tommy_hashdyn_foreach_arg(tommy_hashdyn* hashdyn, tommy_foreach_a /** * Gets the number of elements. */ -tommy_inline tommy_size_t tommy_hashdyn_count(tommy_hashdyn* hashdyn) +tommy_inline tommy_size_t tommy_hashdyn_count(const tommy_hashdyn* hashdyn) { return hashdyn->count; } @@ -335,7 +364,7 @@ tommy_inline tommy_size_t tommy_hashdyn_count(tommy_hashdyn* hashdyn) * Checks if empty. * \return If the hashtable is empty. */ -tommy_inline tommy_bool_t tommy_hashdyn_empty(tommy_hashdyn* hashdyn) +tommy_inline tommy_bool_t tommy_hashdyn_empty(const tommy_hashdyn* hashdyn) { return hashdyn->count == 0; } @@ -343,7 +372,7 @@ tommy_inline tommy_bool_t tommy_hashdyn_empty(tommy_hashdyn* hashdyn) /** * Gets the number of buckets. */ -tommy_inline tommy_size_t tommy_hashdyn_bucket_count(tommy_hashdyn* hashdyn) +tommy_inline tommy_size_t tommy_hashdyn_bucket_count(const tommy_hashdyn* hashdyn) { return hashdyn->bucket_max; } @@ -352,10 +381,10 @@ tommy_inline tommy_size_t tommy_hashdyn_bucket_count(tommy_hashdyn* hashdyn) * Gets the size of allocated memory. * It includes the size of the ::tommy_hashdyn_node of the stored elements. */ -TOMMY_API tommy_size_t tommy_hashdyn_memory_usage(tommy_hashdyn* hashdyn); +TOMMY_API tommy_size_t tommy_hashdyn_memory_usage(const tommy_hashdyn* hashdyn); /** - * \brief Transfers all elements from the hashtable into a tommy_list. + * Transfers all elements from the hashtable into a tommy_list. * * Removes every element from the \p hashdyn hashtable and inserts them * into the provided \p list (at the tail), preserving the per-bucket order diff --git a/tommyds/tommylist.c b/tommyds/tommylist.c index c410d4ce..a1d4d8ef 100644 --- a/tommyds/tommylist.c +++ b/tommyds/tommylist.c @@ -7,7 +7,7 @@ /** \internal * Setup a list. */ -tommy_inline void tommy_list_set(tommy_list* list, tommy_node* head, tommy_node* tail) +tommy_inline void tommy_imp_list_set(tommy_list* list, tommy_node* head, tommy_node* tail) { head->prev = tail; tail->next = 0; @@ -71,7 +71,7 @@ TOMMY_API void tommy_list_merge(tommy_list* first, tommy_list* second, tommy_com tommy_chain_merge_degenerated(&first_chain, &second_chain, cmp); /* restore the destination list */ - tommy_list_set(first, first_chain.head, first_chain.tail); + tommy_imp_list_set(first, first_chain.head, first_chain.tail); } TOMMY_API void tommy_list_reverse(tommy_list* list) @@ -92,7 +92,7 @@ TOMMY_API void tommy_list_reverse(tommy_list* list) } /* the old head is the new tail */ - tommy_list_set(list, prev, head); + tommy_imp_list_set(list, prev, head); } TOMMY_API void tommy_list_sort(tommy_list* list, tommy_compare_func* cmp) @@ -110,6 +110,6 @@ TOMMY_API void tommy_list_sort(tommy_list* list, tommy_compare_func* cmp) tommy_chain_mergesort(&chain, cmp); /* restore the list */ - tommy_list_set(list, chain.head, chain.tail); + tommy_imp_list_set(list, chain.head, chain.tail); } diff --git a/tommyds/tommylist.h b/tommyds/tommylist.h index 4ad3d719..bfa64160 100644 --- a/tommyds/tommylist.h +++ b/tommyds/tommylist.h @@ -5,7 +5,7 @@ * Double linked list for collisions into hashtables. * * This list is a **doubly** linked list mainly targeted for handling collisions - * into an hashtable, but **usable** also as a generic list. + * into a hashtable, but **usable** also as a generic list. * * The main feature of this list is to require only one pointer to represent the * list, compared to a classic implementation requiring a head **and** a tail pointers. @@ -101,12 +101,12 @@ * \code * // deallocates all the objects iterating the list * tommy_list_foreach(&list, free); - * tommy_list_init(&list); // resets the list before reuse + * tommy_list_clear(&list); // resets the list before reuse * \endcode */ -#ifndef __TOMMYLIST_H -#define __TOMMYLIST_H +#ifndef TOMMY_LIST_H +#define TOMMY_LIST_H #include "tommytypes.h" @@ -118,6 +118,43 @@ */ typedef tommy_node* tommy_list; +/** + * Temporary list builder with an embedded sentinel. + * Initialize with tommy_builder_init() and finish with tommy_list_concat_builder(). + * Keep the builder at the same address until finalization, as node links + * refer to its sentinel. + */ +typedef struct tommy_builder_struct { + tommy_node dummy; /**< Sentinel excluded from the resulting list. */ +} tommy_builder; + +/** + * Initializes an empty builder in O(1). + * \param builder Builder to initialize in its final location. + * \return Initial tail, pointing to the builder's sentinel. + */ +tommy_inline tommy_node* tommy_builder_init(tommy_builder* builder) +{ + builder->dummy.next = 0; + return &builder->dummy; +} + +/** + * Appends a non-empty chain to a builder in O(1), preserving element order. + * \param tail Current tail, initially returned by tommy_builder_init(). + * \param head Head of the non-empty source chain. + * \param last Tail of the source chain. For a single node, pass head again. + * The chains must not share nodes. Inner links must be valid; + * head's prev and last's next may be undefined. + * \return Updated tail to pass to the next append or tommy_list_concat_builder(). + */ +tommy_inline tommy_node* tommy_builder_concat(tommy_node* tail, tommy_node* head, tommy_node* last) +{ + head->prev = tail; + tail->next = head; + return last; +} + /** * Initializes the list. * The list is completely inplace, so it doesn't need to be deinitialized. @@ -127,6 +164,20 @@ tommy_inline void tommy_list_init(tommy_list* list) *list = 0; } +/** + * Removes all elements. + * The list remains initialized and can be reused immediately. + * Objects are not freed and nodes are not accessed or modified. + * Their links must not be used to traverse the previous contents. + * You can call this function after tommy_list_foreach() has freed the objects. + * \param list The list to clear. + * \note This operation is O(1). + */ +tommy_inline void tommy_list_clear(tommy_list* list) +{ + *list = 0; +} + /** * Gets the head of the list. * \return The head node. For empty lists 0 is returned. @@ -351,7 +402,13 @@ tommy_inline void* tommy_list_remove_head(tommy_list* list) if (!node) return 0; - return tommy_list_remove_existing(list, node); + /* the new head must retain the tail pointer in the "circular" prev list */ + if (node->next) + node->next->prev = node->prev; + + *list = node->next; + + return node->data; } /** @@ -363,12 +420,22 @@ tommy_inline void* tommy_list_remove_head(tommy_list* list) */ tommy_inline void* tommy_list_remove_tail(tommy_list* list) { - tommy_node* node = tommy_list_tail(list); + tommy_node* head = tommy_list_head(list); - if (!node) + if (!head) return 0; - return tommy_list_remove_existing(list, node); + tommy_node* node = head->prev; + + /* a single node is also the head, and its links must remain unchanged */ + if (node == head) { + *list = 0; + } else { + head->prev = node->prev; + node->prev->next = 0; + } + + return node->data; } /** @@ -384,7 +451,7 @@ tommy_inline void tommy_list_move_head(tommy_list* list, tommy_node* node) return; tommy_list_remove_existing(list, node); - tommy_list_insert_head(list, node, node->data); + tommy_list_insert_head_not_empty(list, node); } /** @@ -396,11 +463,11 @@ tommy_inline void tommy_list_move_head(tommy_list* list, tommy_node* node) */ tommy_inline void tommy_list_move_tail(tommy_list* list, tommy_node* node) { - if (node == tommy_list_tail(list)) + if (node->next == 0) return; tommy_list_remove_existing(list, node); - tommy_list_insert_tail(list, node, node->data); + tommy_list_insert_tail_not_empty(tommy_list_head(list), node); } /** @@ -462,8 +529,8 @@ tommy_inline void tommy_list_swap(tommy_list* first, tommy_list* second) } /** - * Concats two lists. - * The second list is concatenated at the first list. + * Concatenates two lists. + * The second list is concatenated to the first list. * \param first The first list. * \param second The second list. After this call the list content is undefined, * and you should not use it anymore. @@ -494,8 +561,39 @@ tommy_inline void tommy_list_concat(tommy_list* first, tommy_list* second) } /** - * Prepends two lists. - * The second list is prepended at the first list. + * Appends a builder's chain to a list, preserving element order and restoring list links. + * \param list Destination list, possibly empty. It must not share nodes with the builder. + * \param builder Initialized builder, possibly empty. Its contents are consumed; + * reinitialize it before reuse. + * \param tail Current tail returned by the builder helpers, ignored when empty. + * \note This operation is O(1). An empty builder has no effect. + */ +tommy_inline void tommy_list_concat_builder(tommy_list* list, const tommy_builder* builder, tommy_node* tail) +{ + tommy_node* head = builder->dummy.next; + + if (!head) + return; + + tommy_node* first = *list; + + /* replace the sentinel link so no list node refers to the temporary builder */ + if (first) { + tommy_node* first_tail = first->prev; + first_tail->next = head; + head->prev = first_tail; + first->prev = tail; + } else { + *list = head; + head->prev = tail; + } + + tail->next = 0; +} + +/** + * Prepends a list to another list. + * The second list is prepended to the first list. * \param first The first list. * \param second The second list. After this call the list content is undefined, * and you should not use it anymore. @@ -562,7 +660,8 @@ TOMMY_API void tommy_list_reverse(tommy_list* list); /** * Sorts a list. * It's a stable merge sort with O(N*log(N)) worst complexity. - * It's faster on degenerated cases like partially ordered lists. + * It's faster on degenerate cases like partially ordered lists. + * \param list The list to sort. * \param cmp Compare function called with two elements. * The function should return <0 if the first element is less than the second, ==0 if equal, and >0 if greater. */ @@ -572,19 +671,19 @@ TOMMY_API void tommy_list_sort(tommy_list* list, tommy_compare_func* cmp); * Checks if empty. * \return If the list is empty. */ -tommy_inline tommy_bool_t tommy_list_empty(tommy_list* list) +tommy_inline tommy_bool_t tommy_list_empty(const tommy_list* list) { - return tommy_list_head(list) == 0; + return *list == 0; } /** * Gets the number of elements. * \note This operation is O(n). */ -tommy_inline tommy_size_t tommy_list_count(tommy_list* list) +tommy_inline tommy_size_t tommy_list_count(const tommy_list* list) { tommy_size_t count = 0; - tommy_node* i = tommy_list_head(list); + const tommy_node* i = *list; while (i) { ++count; @@ -620,7 +719,12 @@ tommy_inline tommy_size_t tommy_list_count(tommy_list* list) * * // deallocates all the objects iterating the list * tommy_list_foreach(&list, free); + * tommy_list_clear(&list); // resets the list before reuse * \endcode + * + * If the callback frees the objects, the list retains dangling node + * pointers. Call tommy_list_clear() or tommy_list_init() before reusing it. + * The list has no storage to release. */ tommy_inline void tommy_list_foreach(tommy_list* list, tommy_foreach_func* func) { diff --git a/tommyds/tommytree.c b/tommyds/tommytree.c index 1f9de33e..069401be 100644 --- a/tommyds/tommytree.c +++ b/tommyds/tommytree.c @@ -14,7 +14,7 @@ #define TOMMY_TREE_BALANCE_LEFT ((tommy_size_t)1) #define TOMMY_TREE_BALANCE_RIGHT ((tommy_size_t)2) -tommy_inline int tommy_tree_balance_get(tommy_tree_node* node) +tommy_inline int tommy_imp_tree_balance_get(tommy_tree_node* node) { tommy_size_t balance = node->index & TOMMY_TREE_BALANCE_MASK; @@ -25,7 +25,7 @@ tommy_inline int tommy_tree_balance_get(tommy_tree_node* node) return 0; } -tommy_inline void tommy_tree_balance_set(tommy_tree_node* node, int balance) +tommy_inline void tommy_imp_tree_balance_set(tommy_tree_node* node, int balance) { tommy_size_t value = 0; @@ -37,12 +37,12 @@ tommy_inline void tommy_tree_balance_set(tommy_tree_node* node, int balance) node->index = (node->index & ~TOMMY_TREE_BALANCE_MASK) | value; } -tommy_inline void tommy_tree_parent_set(tommy_tree_node* node, tommy_tree_node* parent) +tommy_inline void tommy_imp_tree_parent_set(tommy_tree_node* node, tommy_tree_node* parent) { node->index = (tommy_size_t)(tommy_uintptr_t)parent | (node->index & TOMMY_TREE_BALANCE_MASK); } -tommy_inline void tommy_tree_replace(tommy_tree* tree, tommy_tree_node* root, tommy_tree_node* node) +tommy_inline void tommy_imp_tree_replace(tommy_tree* tree, tommy_tree_node* root, tommy_tree_node* node) { tommy_tree_node* parent = tommy_tree_parent(root); @@ -55,45 +55,45 @@ tommy_inline void tommy_tree_replace(tommy_tree* tree, tommy_tree_node* root, to } if (node) - tommy_tree_parent_set(node, parent); + tommy_imp_tree_parent_set(node, parent); } -tommy_inline tommy_tree_node* tommy_tree_rotate_left(tommy_tree* tree, tommy_tree_node* root) +tommy_inline tommy_tree_node* tommy_imp_tree_rotate_left(tommy_tree* tree, tommy_tree_node* root) { tommy_tree_node* next = root->next; - tommy_tree_replace(tree, root, next); + tommy_imp_tree_replace(tree, root, next); root->next = next->prev; if (root->next) - tommy_tree_parent_set(root->next, root); + tommy_imp_tree_parent_set(root->next, root); next->prev = root; - tommy_tree_parent_set(root, next); + tommy_imp_tree_parent_set(root, next); return next; } -tommy_inline tommy_tree_node* tommy_tree_rotate_right(tommy_tree* tree, tommy_tree_node* root) +tommy_inline tommy_tree_node* tommy_imp_tree_rotate_right(tommy_tree* tree, tommy_tree_node* root) { tommy_tree_node* prev = root->prev; - tommy_tree_replace(tree, root, prev); + tommy_imp_tree_replace(tree, root, prev); root->prev = prev->next; if (root->prev) - tommy_tree_parent_set(root->prev, root); + tommy_imp_tree_parent_set(root->prev, root); prev->next = root; - tommy_tree_parent_set(root, prev); + tommy_imp_tree_parent_set(root, prev); return prev; } -tommy_inline void tommy_tree_insert_balance(tommy_tree* tree, tommy_tree_node* node) +tommy_inline void tommy_imp_tree_insert_balance(tommy_tree* tree, tommy_tree_node* node) { tommy_tree_node* parent = tommy_tree_parent(node); while (parent) { - int balance = tommy_tree_balance_get(parent); + int balance = tommy_imp_tree_balance_get(parent); if (node == parent->prev) --balance; @@ -102,12 +102,12 @@ tommy_inline void tommy_tree_insert_balance(tommy_tree* tree, tommy_tree_node* n } if (balance == 0) { - tommy_tree_balance_set(parent, balance); + tommy_imp_tree_balance_set(parent, balance); return; } if (balance >= -1 && balance <= 1) { - tommy_tree_balance_set(parent, balance); + tommy_imp_tree_balance_set(parent, balance); node = parent; parent = tommy_tree_parent(parent); continue; @@ -115,39 +115,39 @@ tommy_inline void tommy_tree_insert_balance(tommy_tree* tree, tommy_tree_node* n if (balance == -2) { tommy_tree_node* left = parent->prev; - int left_balance = tommy_tree_balance_get(left); + int left_balance = tommy_imp_tree_balance_get(left); if (left_balance < 0) { - tommy_tree_rotate_right(tree, parent); - tommy_tree_balance_set(parent, 0); - tommy_tree_balance_set(left, 0); + tommy_imp_tree_rotate_right(tree, parent); + tommy_imp_tree_balance_set(parent, 0); + tommy_imp_tree_balance_set(left, 0); } else { tommy_tree_node* middle = left->next; - int middle_balance = tommy_tree_balance_get(middle); + int middle_balance = tommy_imp_tree_balance_get(middle); - tommy_tree_rotate_left(tree, left); - tommy_tree_rotate_right(tree, parent); - tommy_tree_balance_set(parent, middle_balance < 0 ? 1 : 0); - tommy_tree_balance_set(left, middle_balance > 0 ? -1 : 0); - tommy_tree_balance_set(middle, 0); + tommy_imp_tree_rotate_left(tree, left); + tommy_imp_tree_rotate_right(tree, parent); + tommy_imp_tree_balance_set(parent, middle_balance < 0 ? 1 : 0); + tommy_imp_tree_balance_set(left, middle_balance > 0 ? -1 : 0); + tommy_imp_tree_balance_set(middle, 0); } } else { tommy_tree_node* right = parent->next; - int right_balance = tommy_tree_balance_get(right); + int right_balance = tommy_imp_tree_balance_get(right); if (right_balance > 0) { - tommy_tree_rotate_left(tree, parent); - tommy_tree_balance_set(parent, 0); - tommy_tree_balance_set(right, 0); + tommy_imp_tree_rotate_left(tree, parent); + tommy_imp_tree_balance_set(parent, 0); + tommy_imp_tree_balance_set(right, 0); } else { tommy_tree_node* middle = right->prev; - int middle_balance = tommy_tree_balance_get(middle); + int middle_balance = tommy_imp_tree_balance_get(middle); - tommy_tree_rotate_right(tree, right); - tommy_tree_rotate_left(tree, parent); - tommy_tree_balance_set(parent, middle_balance > 0 ? -1 : 0); - tommy_tree_balance_set(right, middle_balance < 0 ? 1 : 0); - tommy_tree_balance_set(middle, 0); + tommy_imp_tree_rotate_right(tree, right); + tommy_imp_tree_rotate_left(tree, parent); + tommy_imp_tree_balance_set(parent, middle_balance > 0 ? -1 : 0); + tommy_imp_tree_balance_set(right, middle_balance < 0 ? 1 : 0); + tommy_imp_tree_balance_set(middle, 0); } } @@ -155,16 +155,19 @@ tommy_inline void tommy_tree_insert_balance(tommy_tree* tree, tommy_tree_node* n } } -tommy_inline void* tommy_tree_insert_impl(tommy_tree* tree, tommy_tree_node* node, void* data, tommy_bool_t unique) +tommy_inline void* tommy_imp_tree_insert(tommy_tree* tree, tommy_tree_node* node, void* data, tommy_bool_t unique) { tommy_tree_node* parent = 0; tommy_tree_node* existing = 0; tommy_tree_node** link = &tree->root; + /* cache the comparator to avoid reloading it after each comparison */ + tommy_compare_func* cmp_func = tree->cmp; while (*link) { - int cmp = tree->cmp(data, (*link)->data); - + /* comparators must not change the tree, so keep the node across the call */ parent = *link; + int cmp = cmp_func(data, parent->data); + if (cmp < 0) link = &parent->prev; else if (cmp == 0 && unique) { @@ -186,25 +189,25 @@ tommy_inline void* tommy_tree_insert_impl(tommy_tree* tree, tommy_tree_node* nod *link = node; ++tree->count; - tommy_tree_insert_balance(tree, node); + tommy_imp_tree_insert_balance(tree, node); return node->data; } TOMMY_API void tommy_tree_insert(tommy_tree* tree, tommy_tree_node* node, void* data) { - tommy_tree_insert_impl(tree, node, data, 0); + tommy_imp_tree_insert(tree, node, data, 0); } TOMMY_API void* tommy_tree_insert_unique(tommy_tree* tree, tommy_tree_node* node, void* data) { - return tommy_tree_insert_impl(tree, node, data, 1); + return tommy_imp_tree_insert(tree, node, data, 1); } -tommy_inline void tommy_tree_remove_balance(tommy_tree* tree, tommy_tree_node* node, tommy_bool_t left_shrunk) +tommy_inline void tommy_imp_tree_remove_balance(tommy_tree* tree, tommy_tree_node* node, tommy_bool_t left_shrunk) { while (node) { - int balance = tommy_tree_balance_get(node); + int balance = tommy_imp_tree_balance_get(node); if (left_shrunk) ++balance; @@ -212,12 +215,12 @@ tommy_inline void tommy_tree_remove_balance(tommy_tree* tree, tommy_tree_node* n --balance; if (balance == -1 || balance == 1) { - tommy_tree_balance_set(node, balance); + tommy_imp_tree_balance_set(node, balance); return; } if (balance == 0) { - tommy_tree_balance_set(node, balance); + tommy_imp_tree_balance_set(node, balance); tommy_tree_node* parent = tommy_tree_parent(node); if (!parent) return; @@ -228,27 +231,27 @@ tommy_inline void tommy_tree_remove_balance(tommy_tree* tree, tommy_tree_node* n if (balance == -2) { tommy_tree_node* left = node->prev; - int left_balance = tommy_tree_balance_get(left); + int left_balance = tommy_imp_tree_balance_get(left); tommy_tree_node* root; if (left_balance <= 0) { - root = tommy_tree_rotate_right(tree, node); + root = tommy_imp_tree_rotate_right(tree, node); if (left_balance == 0) { - tommy_tree_balance_set(node, -1); - tommy_tree_balance_set(left, 1); + tommy_imp_tree_balance_set(node, -1); + tommy_imp_tree_balance_set(left, 1); return; } - tommy_tree_balance_set(node, 0); - tommy_tree_balance_set(left, 0); + tommy_imp_tree_balance_set(node, 0); + tommy_imp_tree_balance_set(left, 0); } else { tommy_tree_node* middle = left->next; - int middle_balance = tommy_tree_balance_get(middle); + int middle_balance = tommy_imp_tree_balance_get(middle); - tommy_tree_rotate_left(tree, left); - root = tommy_tree_rotate_right(tree, node); - tommy_tree_balance_set(node, middle_balance < 0 ? 1 : 0); - tommy_tree_balance_set(left, middle_balance > 0 ? -1 : 0); - tommy_tree_balance_set(middle, 0); + tommy_imp_tree_rotate_left(tree, left); + root = tommy_imp_tree_rotate_right(tree, node); + tommy_imp_tree_balance_set(node, middle_balance < 0 ? 1 : 0); + tommy_imp_tree_balance_set(left, middle_balance > 0 ? -1 : 0); + tommy_imp_tree_balance_set(middle, 0); } node = tommy_tree_parent(root); @@ -260,27 +263,27 @@ tommy_inline void tommy_tree_remove_balance(tommy_tree* tree, tommy_tree_node* n { tommy_tree_node* right = node->next; - int right_balance = tommy_tree_balance_get(right); + int right_balance = tommy_imp_tree_balance_get(right); tommy_tree_node* root; if (right_balance >= 0) { - root = tommy_tree_rotate_left(tree, node); + root = tommy_imp_tree_rotate_left(tree, node); if (right_balance == 0) { - tommy_tree_balance_set(node, 1); - tommy_tree_balance_set(right, -1); + tommy_imp_tree_balance_set(node, 1); + tommy_imp_tree_balance_set(right, -1); return; } - tommy_tree_balance_set(node, 0); - tommy_tree_balance_set(right, 0); + tommy_imp_tree_balance_set(node, 0); + tommy_imp_tree_balance_set(right, 0); } else { tommy_tree_node* middle = right->prev; - int middle_balance = tommy_tree_balance_get(middle); + int middle_balance = tommy_imp_tree_balance_get(middle); - tommy_tree_rotate_right(tree, right); - root = tommy_tree_rotate_left(tree, node); - tommy_tree_balance_set(node, middle_balance > 0 ? -1 : 0); - tommy_tree_balance_set(right, middle_balance < 0 ? 1 : 0); - tommy_tree_balance_set(middle, 0); + tommy_imp_tree_rotate_right(tree, right); + root = tommy_imp_tree_rotate_left(tree, node); + tommy_imp_tree_balance_set(node, middle_balance > 0 ? -1 : 0); + tommy_imp_tree_balance_set(right, middle_balance < 0 ? 1 : 0); + tommy_imp_tree_balance_set(middle, 0); } node = tommy_tree_parent(root); @@ -302,7 +305,7 @@ TOMMY_API void* tommy_tree_remove_existing(tommy_tree* tree, tommy_tree_node* no parent = tommy_tree_parent(node); left_shrunk = parent && node == parent->prev; - tommy_tree_replace(tree, node, child); + tommy_imp_tree_replace(tree, node, child); } else { tommy_tree_node* next = node->next; @@ -311,49 +314,58 @@ TOMMY_API void* tommy_tree_remove_existing(tommy_tree* tree, tommy_tree_node* no parent = tommy_tree_parent(next); if (parent == node) { - tommy_tree_replace(tree, node, next); + tommy_imp_tree_replace(tree, node, next); next->prev = node->prev; - tommy_tree_parent_set(next->prev, next); - tommy_tree_balance_set(next, tommy_tree_balance_get(node)); + tommy_imp_tree_parent_set(next->prev, next); + tommy_imp_tree_balance_set(next, tommy_imp_tree_balance_get(node)); parent = next; left_shrunk = 0; } else { parent->prev = next->next; if (parent->prev) - tommy_tree_parent_set(parent->prev, parent); + tommy_imp_tree_parent_set(parent->prev, parent); - tommy_tree_replace(tree, node, next); + tommy_imp_tree_replace(tree, node, next); next->prev = node->prev; next->next = node->next; - tommy_tree_parent_set(next->prev, next); - tommy_tree_parent_set(next->next, next); - tommy_tree_balance_set(next, tommy_tree_balance_get(node)); + tommy_imp_tree_parent_set(next->prev, next); + tommy_imp_tree_parent_set(next->next, next); + tommy_imp_tree_balance_set(next, tommy_imp_tree_balance_get(node)); left_shrunk = 1; } } --tree->count; if (parent) - tommy_tree_remove_balance(tree, parent, left_shrunk); + tommy_imp_tree_remove_balance(tree, parent, left_shrunk); return data; } -tommy_inline void tommy_tree_to_list_node(tommy_tree_node* node, tommy_list* list) -{ - if (node) { - tommy_tree_node* right = node->next; - - tommy_tree_to_list_node(node->prev, list); - /* list insertion overwrites child links, so keep the right subtree reachable */ - tommy_list_insert_tail(list, node, node->data); - tommy_tree_to_list_node(right, list); - } -} - TOMMY_API void tommy_tree_to_list(tommy_tree* tree, tommy_list* list) { - tommy_tree_to_list_node(tree->root, list); + /* AVL height is less than twice the bit width of its node count */ + tommy_tree_node* stack[2 * TOMMY_SIZE_BIT]; + tommy_size_t depth = 0; + tommy_tree_node* node = tree->root; + tommy_builder builder; + tommy_node* builder_tail = tommy_builder_init(&builder); + + while (node || depth) { + while (node) { + stack[depth] = node; + ++depth; + node = node->prev; + } + + node = stack[--depth]; + /* chain appending overwrites child links, so keep the right subtree reachable */ + tommy_tree_node* next = node->next; + builder_tail = tommy_builder_concat(builder_tail, node, node); + node = next; + } + + tommy_list_concat_builder(list, &builder, builder_tail); tommy_tree_clear(tree); } @@ -401,7 +413,7 @@ TOMMY_API void tommy_tree_foreach_arg(tommy_tree* tree, tommy_foreach_arg_func* } } -TOMMY_API tommy_size_t tommy_tree_memory_usage(tommy_tree* tree) +TOMMY_API tommy_size_t tommy_tree_memory_usage(const tommy_tree* tree) { return tommy_tree_count(tree) * sizeof(tommy_tree_node); } diff --git a/tommyds/tommytree.h b/tommyds/tommytree.h index 9492238a..c6c5f0ab 100644 --- a/tommyds/tommytree.h +++ b/tommyds/tommytree.h @@ -68,6 +68,20 @@ * } * \endcode * + * \anchor tommy_tree_iterator_validity + * Iterators are pointers to nodes contained in the tree. + * Inserting elements or removing other nodes between iterator calls does not + * invalidate pointers to nodes that remain in the tree. + * Subsequent next/prev calls use the current contents and ordering; + * inserted elements may become visible and removed elements are skipped. + * + * Removing the pointed node invalidates its use as an iterator, even if + * its storage has not been freed. To continue traversal after removing + * the current node, obtain the next or previous node before removal. + * + * Keys and fields used for ordering must not be modified while contained. + * Concurrent traversal and modification require external synchronization. + * * To remove the first element with a given key in tree order, call * tommy_tree_remove() providing the key to search and remove. * @@ -108,8 +122,8 @@ * \endcode */ -#ifndef __TOMMYTREE_H -#define __TOMMYTREE_H +#ifndef TOMMY_TREE_H +#define TOMMY_TREE_H #include "tommytypes.h" #include "tommylist.h" @@ -137,6 +151,7 @@ typedef struct tommy_tree_struct { /** * Initializes the tree. + * \param tree The tree to initialize. * \param cmp The comparison function that defines the order in the tree. */ tommy_inline void tommy_tree_init(tommy_tree* tree, tommy_compare_func* cmp) @@ -181,6 +196,7 @@ tommy_inline void tommy_tree_clear(tommy_tree* tree) * Equal elements are visited in insertion order. * You have to provide the pointer of the node embedded into the object and * the pointer to the object. + * \param tree The tree. * \param node Pointer to the node embedded into the object to insert. * \param data Pointer to the object to insert. */ @@ -191,6 +207,7 @@ TOMMY_API void tommy_tree_insert(tommy_tree* tree, tommy_tree_node* node, void* * If found, the first equal element in tree order is returned and the * candidate node is left unchanged. Otherwise the candidate is inserted * and its data field is returned. + * \param tree The tree. * \param node Pointer to the node embedded into the object to insert. * \param data Pointer to the object to insert. * \return The first equal element, or data if the candidate was inserted. @@ -213,6 +230,8 @@ TOMMY_API void tommy_tree_to_list(tommy_tree* tree, tommy_list* list); /** * Removes an element from the tree. * You must already have the address of the element to remove. + * \param tree The tree. + * \param node The node to remove. * \return The tommy_node::data field of the node removed. */ TOMMY_API void* tommy_tree_remove_existing(tommy_tree* tree, tommy_tree_node* node); @@ -229,6 +248,7 @@ tommy_inline tommy_tree_node* tommy_tree_parent(tommy_tree_node* node) /** * Gets the node following the specified one in tree order. + * See \ref tommy_tree_iterator_validity for iterator validity across insertions and removals. * \param node Node contained in the tree. * \return The following node. For the tail node 0 is returned. */ @@ -252,6 +272,7 @@ tommy_inline tommy_tree_node* tommy_tree_next(tommy_tree_node* node) /** * Gets the node preceding the specified one in tree order. + * See \ref tommy_tree_iterator_validity for iterator validity across insertions and removals. * \param node Node contained in the tree. * \return The preceding node. For the head node 0 is returned. */ @@ -346,6 +367,10 @@ tommy_inline void* tommy_tree_remove_tail(tommy_tree* tree) * * The cmp_arg argument will be the first argument of the comparison function, * and it can be of a different type than the objects in the tree. + * \param tree The tree. + * \param cmp Comparison function called with cmp_arg and the object in the tree. + * \param cmp_arg Search key, which may have a different type from tree objects. + * \return The first equal element in tree order, or 0 if not found. */ tommy_inline void* tommy_tree_search_compare(tommy_tree* tree, tommy_compare_func* cmp, const void* cmp_arg) { @@ -353,14 +378,16 @@ tommy_inline void* tommy_tree_search_compare(tommy_tree* tree, tommy_compare_fun void* candidate = 0; while (node) { - int c = cmp(cmp_arg, node->data); + /* comparators must not change the tree, so retain the data across the call */ + void* data = node->data; + int c = cmp(cmp_arg, data); if (c < 0) node = node->prev; else if (c > 0) node = node->next; else { - candidate = node->data; + candidate = data; node = node->prev; } } @@ -371,6 +398,7 @@ tommy_inline void* tommy_tree_search_compare(tommy_tree* tree, tommy_compare_fun /** * Searches an element in the tree. * If the element is not found, 0 is returned. + * \param tree The tree. * \param data Element used for comparison. * \return The first equal element in tree order, or 0 if none. */ @@ -388,6 +416,10 @@ tommy_inline void* tommy_tree_search(tommy_tree* tree, const void* data) * * The cmp_arg argument will be the first argument of the comparison function, * and it can be of a different type than the objects in the tree. + * \param tree The tree. + * \param cmp Comparison function called with cmp_arg and the object in the tree. + * \param cmp_arg Search key, which may have a different type from tree objects. + * \return The first element in tree order with key greater or equal, or 0 if none. */ tommy_inline void* tommy_tree_search_greater_equal_compare(tommy_tree* tree, tommy_compare_func* cmp, const void* cmp_arg) { @@ -395,10 +427,12 @@ tommy_inline void* tommy_tree_search_greater_equal_compare(tommy_tree* tree, tom void* candidate = 0; while (node) { - int c = cmp(cmp_arg, node->data); + /* comparators must not change the tree, so retain the data across the call */ + void* data = node->data; + int c = cmp(cmp_arg, data); if (c <= 0) { - candidate = node->data; + candidate = data; node = node->prev; } else { node = node->next; @@ -411,6 +445,7 @@ tommy_inline void* tommy_tree_search_greater_equal_compare(tommy_tree* tree, tom /** * Searches an element in the tree with key greater or equal than the specified one. * If no such element exists, 0 is returned. + * \param tree The tree. * \param data Element used for comparison. * \return The first element in tree order with key greater or equal, or 0 if none. */ @@ -423,6 +458,7 @@ tommy_inline void* tommy_tree_search_greater_equal(tommy_tree* tree, const void* * Searches the first element in tree order with key strictly greater than the specified one using a specific comparison function. * The function must define a suborder of the tree comparison function. * Equivalent elements are excluded from the result. + * \param tree The tree. * \param cmp Comparison function called with cmp_arg and the object in the tree. * \param cmp_arg Search key, which may have a different type from tree objects. * \return The first strictly greater element, or 0 if none. @@ -433,10 +469,12 @@ tommy_inline void* tommy_tree_search_greater_compare(tommy_tree* tree, tommy_com void* candidate = 0; while (node) { - int c = cmp(cmp_arg, node->data); + /* comparators must not change the tree, so retain the data across the call */ + void* data = node->data; + int c = cmp(cmp_arg, data); if (c < 0) { - candidate = node->data; + candidate = data; node = node->prev; } else { node = node->next; @@ -449,6 +487,7 @@ tommy_inline void* tommy_tree_search_greater_compare(tommy_tree* tree, tommy_com /** * Searches the first element in tree order with key strictly greater than the specified one. * If no such element exists, 0 is returned. + * \param tree The tree. * \param data Element used for comparison. * \return The first strictly greater element, or 0 if none. */ @@ -466,6 +505,10 @@ tommy_inline void* tommy_tree_search_greater(tommy_tree* tree, const void* data) * * The cmp_arg argument will be the first argument of the comparison function, * and it can be of a different type than the objects in the tree. + * \param tree The tree. + * \param cmp Comparison function called with cmp_arg and the object in the tree. + * \param cmp_arg Search key, which may have a different type from tree objects. + * \return The last element in tree order with key less or equal, or 0 if none. */ tommy_inline void* tommy_tree_search_less_equal_compare(tommy_tree* tree, tommy_compare_func* cmp, const void* cmp_arg) { @@ -473,12 +516,14 @@ tommy_inline void* tommy_tree_search_less_equal_compare(tommy_tree* tree, tommy_ void* candidate = 0; while (node) { - int c = cmp(cmp_arg, node->data); + /* comparators must not change the tree, so retain the data across the call */ + void* data = node->data; + int c = cmp(cmp_arg, data); if (c < 0) { node = node->prev; } else { - candidate = node->data; + candidate = data; node = node->next; } } @@ -489,6 +534,7 @@ tommy_inline void* tommy_tree_search_less_equal_compare(tommy_tree* tree, tommy_ /** * Searches an element in the tree with key less or equal than the specified one. * If no such element exists, 0 is returned. + * \param tree The tree. * \param data Element used for comparison. * \return The last element in tree order with key less or equal, or 0 if none. */ @@ -501,9 +547,10 @@ tommy_inline void* tommy_tree_search_less_equal(tommy_tree* tree, const void* da * Searches the last element in tree order with key strictly less than the specified one using a specific comparison function. * The function must define a suborder of the tree comparison function. * Equivalent elements are excluded from the result. + * \param tree The tree. * \param cmp Comparison function called with cmp_arg and the object in the tree. * \param cmp_arg Search key, which may have a different type from tree objects. - * \return The last strictly lesser element, or 0 if none. + * \return The last strictly less element, or 0 if none. */ tommy_inline void* tommy_tree_search_less_compare(tommy_tree* tree, tommy_compare_func* cmp, const void* cmp_arg) { @@ -511,10 +558,12 @@ tommy_inline void* tommy_tree_search_less_compare(tommy_tree* tree, tommy_compar void* candidate = 0; while (node) { - int c = cmp(cmp_arg, node->data); + /* comparators must not change the tree, so retain the data across the call */ + void* data = node->data; + int c = cmp(cmp_arg, data); if (c > 0) { - candidate = node->data; + candidate = data; node = node->next; } else { node = node->prev; @@ -527,8 +576,9 @@ tommy_inline void* tommy_tree_search_less_compare(tommy_tree* tree, tommy_compar /** * Searches the last element in tree order with key strictly less than the specified one. * If no such element exists, 0 is returned. + * \param tree The tree. * \param data Element used for comparison. - * \return The last strictly lesser element, or 0 if none. + * \return The last strictly less element, or 0 if none. */ tommy_inline void* tommy_tree_search_less(tommy_tree* tree, const void* data) { @@ -540,6 +590,7 @@ tommy_inline void* tommy_tree_search_less(tommy_tree* tree, const void* data) * The comparison function must define a suborder of the original one. * The cmp_arg argument is passed as the first argument of the comparison * function and may have a different type than the objects in the tree. + * \param tree The tree. * \param cmp Comparison function used to find the element. * \param cmp_arg Argument passed to the comparison function. * \return The first equal element in tree order, or 0 if not found. @@ -571,6 +622,7 @@ tommy_inline void* tommy_tree_remove_compare(tommy_tree* tree, tommy_compare_fun /** * Searches and removes an element. * If the element is not found, 0 is returned. + * \param tree The tree. * \param data Element used for comparison. * \return The first equal element in tree order, or 0 if not found. */ @@ -607,7 +659,12 @@ tommy_inline void* tommy_tree_remove(tommy_tree* tree, const void* data) * * // deallocates all the objects iterating the tree * tommy_tree_foreach(&tree, free); + * tommy_tree_clear(&tree); // resets the tree before reuse * \endcode + * + * If the callback frees the objects, the tree retains dangling node + * pointers. Call tommy_tree_clear() or tommy_tree_init() before reusing it. + * The tree has no storage to release. */ TOMMY_API void tommy_tree_foreach(tommy_tree* tree, tommy_foreach_func* func); @@ -623,7 +680,7 @@ TOMMY_API void tommy_tree_foreach_arg(tommy_tree* tree, tommy_foreach_arg_func* * Checks if empty. * \return If the tree is empty. */ -tommy_inline tommy_bool_t tommy_tree_empty(tommy_tree* tree) +tommy_inline tommy_bool_t tommy_tree_empty(const tommy_tree* tree) { return tree->root == 0; } @@ -631,7 +688,7 @@ tommy_inline tommy_bool_t tommy_tree_empty(tommy_tree* tree) /** * Gets the number of elements. */ -tommy_inline tommy_size_t tommy_tree_count(tommy_tree* tree) +tommy_inline tommy_size_t tommy_tree_count(const tommy_tree* tree) { return tree->count; } @@ -640,7 +697,7 @@ tommy_inline tommy_size_t tommy_tree_count(tommy_tree* tree) * Gets the size of allocated memory. * It includes the size of the ::tommy_tree_node of the stored elements. */ -TOMMY_API tommy_size_t tommy_tree_memory_usage(tommy_tree* tree); +TOMMY_API tommy_size_t tommy_tree_memory_usage(const tommy_tree* tree); #endif diff --git a/tommyds/tommytypes.h b/tommyds/tommytypes.h index 155ffb1d..0b63d4fd 100644 --- a/tommyds/tommytypes.h +++ b/tommyds/tommytypes.h @@ -5,8 +5,25 @@ * Generic types. */ -#ifndef __TOMMYTYPES_H -#define __TOMMYTYPES_H +#ifndef TOMMY_TYPES_H +#define TOMMY_TYPES_H + +/******************************************************************************/ +/* memory bounds checking */ + +/** + * Enable bounds-safe implementations when compiling with AddressSanitizer + * or Fil-C. These environments detect accesses beyond allocated objects, + * including intentional overreads that remain within a readable memory page. + * Normal builds retain the faster implementations. + */ +#if defined(__SANITIZE_ADDRESS__) || defined(__FILC__) +#define TOMMY_MEMORY_BOUNDS_CHECK 1 +#elif defined(__has_feature) +#define TOMMY_MEMORY_BOUNDS_CHECK __has_feature(address_sanitizer) +#else +#define TOMMY_MEMORY_BOUNDS_CHECK 0 +#endif /******************************************************************************/ /* types */ @@ -14,15 +31,18 @@ #include #ifdef _MSC_VER +#include typedef unsigned tommy_uint32_t; /**< Generic uint32_t type. */ typedef unsigned _int64 tommy_uint64_t; /**< Generic uint64_t type. */ typedef size_t tommy_uintptr_t; /**< Generic uintptr_t type. */ #ifdef _WIN64 #define TOMMY_SIZE_BIT 64 +#define TOMMY_SIZE_MAX _UI64_MAX typedef unsigned _int64 tommy_size_t; /**< Generic size_t type. */ typedef _int64 tommy_ssize_t; /**< Generic ssize_t type. */ #else #define TOMMY_SIZE_BIT 32 +#define TOMMY_SIZE_MAX UINT_MAX typedef unsigned tommy_size_t; /**< Generic size_t type. */ typedef int tommy_ssize_t; /**< Generic ssize_t type. */ #endif @@ -33,10 +53,12 @@ typedef uint64_t tommy_uint64_t; /**< Generic uint64_t type. */ typedef uintptr_t tommy_uintptr_t; /**< Generic uintptr_t type. */ #if SIZE_MAX == UINT64_MAX #define TOMMY_SIZE_BIT 64 +#define TOMMY_SIZE_MAX SIZE_MAX typedef uint64_t tommy_size_t; /**< Generic size_t type. */ typedef int64_t tommy_ssize_t; /**< Generic ssize_t type. */ #elif SIZE_MAX == UINT32_MAX #define TOMMY_SIZE_BIT 32 +#define TOMMY_SIZE_MAX SIZE_MAX typedef uint32_t tommy_size_t; /**< Generic size_t type. */ typedef int32_t tommy_ssize_t; /**< Generic ssize_t type. */ #else @@ -99,7 +121,7 @@ typedef tommy_uint32_t tommy_uint_t; #endif /******************************************************************************/ -/* modificators */ +/* modifiers */ /** \internal * Definition of TOMMY_API. @@ -124,7 +146,7 @@ typedef tommy_uint32_t tommy_uint_t; * Definition of the restrict keyword if available. */ #if !defined(tommy_restrict) -#if __STDC_VERSION__ >= 199901L +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define tommy_restrict restrict #elif defined(_MSC_VER) || defined(__GNUC__) #define tommy_restrict __restrict @@ -208,6 +230,7 @@ typedef struct tommy_node_struct { * Index of the node. * With tries this field is used to store the key. * With hashtables this field is used to store the hash value. + * With trees this field is used to store the parent pointer and balance factor. * With lists this field is not used. */ tommy_size_t index; @@ -247,12 +270,12 @@ typedef int tommy_compare_func(const void* obj_a, const void* obj_b); /** * Search function for elements. - * \param arg Pointer to the value to search as passed at the search function. + * \param arg Pointer to the value to search as passed to the search function. * \param obj Pointer to the object to compare to. * \return ==0 if the value matches the element. !=0 if different. * * The first argument is a pointer to the value to search exactly - * as it's passed at the search function called. + * as it's passed to the search function called. * The second argument is a pointer to the object inside the hashtable to compare. * * The return value has to be 0 if the values are equal. != 0 if they are different. @@ -316,7 +339,7 @@ typedef void tommy_foreach_arg_func(void* arg, void* obj); /** \internal * Integer log2 for constants. - * You can use it only for exact power of 2 up to 256. + * You can use it only for exact powers of 2 up to 256. */ #define TOMMY_ILOG2(value) ((value) == 256 ? 8 : (value) == 128 ? 7 : (value) == 64 ? 6 : (value) == 32 ? 5 : (value) == 16 ? 4 : (value) == 8 ? 3 : (value) == 4 ? 2 : (value) == 2 ? 1 : 0) @@ -358,7 +381,7 @@ tommy_inline tommy_uint_t tommy_ilog2_u32(tommy_uint32_t value) #else /* find the log base 2 of an N-bit integer in O(lg(N)) operations with multiply and lookup */ /* from http://graphics.stanford.edu/~seander/bithacks.html */ - static unsigned char TOMMY_DE_BRUIJN_INDEX_ILOG2[32] = { + static const unsigned char TOMMY_DE_BRUIJN_INDEX_ILOG2[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; @@ -375,6 +398,11 @@ tommy_inline tommy_uint_t tommy_ilog2_u32(tommy_uint32_t value) /** * Bit scan reverse or integer log2 for 64 bits. + * Return the bit index of the most significant 1 bit. + * + * If no bit is set, the result is undefined. + * \param value Value to scan. 0 is not allowed. + * \return The index of the most significant bit set. */ tommy_inline tommy_uint_t tommy_ilog2_u64(tommy_uint64_t value) { @@ -424,6 +452,11 @@ tommy_inline tommy_uint_t tommy_ctz_u32(tommy_uint32_t value) /** * Bit scan forward or trailing zero count for 64 bits. + * Return the bit index of the least significant 1 bit. + * + * If no bit is set, the result is undefined. + * \param value Value to scan. 0 is not allowed. + * \return The index of the least significant bit set. */ tommy_inline tommy_uint_t tommy_ctz_u64(tommy_uint64_t value) { @@ -446,6 +479,7 @@ tommy_inline tommy_uint_t tommy_ctz_u64(tommy_uint64_t value) /** * Rounds up to the next power of 2. * For the value 0, the result is undefined. + * \param value Value to round up. * \return The smallest power of 2 not less than the specified value. */ tommy_inline tommy_uint32_t tommy_roundup_pow2_u32(tommy_uint32_t value) @@ -466,6 +500,9 @@ tommy_inline tommy_uint32_t tommy_roundup_pow2_u32(tommy_uint32_t value) /** * Rounds up to the next power of 2 for 64 bits. + * For the value 0, the result is undefined. + * \param value Value to round up. + * \return The smallest power of 2 not less than the specified value. */ tommy_inline tommy_uint64_t tommy_roundup_pow2_u64(tommy_uint64_t value) { @@ -482,7 +519,8 @@ tommy_inline tommy_uint64_t tommy_roundup_pow2_u64(tommy_uint64_t value) } /** - * Check if the specified word has a byte at 0. + * Checks if the specified word has a byte at 0. + * \param value Value to check. * \return 0 or 1. */ tommy_inline int tommy_haszero_u32(tommy_uint32_t value) @@ -491,7 +529,8 @@ tommy_inline int tommy_haszero_u32(tommy_uint32_t value) } /** - * Check if the specified 64-bit word has a byte at 0. + * Checks if the specified 64-bit word has a byte at 0. + * \param value Value to check. * \return 0 or 1. */ tommy_inline int tommy_haszero_u64(tommy_uint64_t value)