struct hash *hash_new(unsigned int n_buckets, void (*free_value)(void *value)) { struct hash *hash; n_buckets = ALIGN_POWER2(n_buckets); hash = calloc(1, sizeof(struct hash) + n_buckets * sizeof(struct hash_bucket)); if (hash == NULL) return NULL; hash->n_buckets = n_buckets; hash->free_value = free_value; hash->step = n_buckets / 32; if (hash->step == 0) hash->step = 4; else if (hash->step > 64) hash->step = 64; return hash; }
static void test_align_power2(void) { unsigned long i, p2; log_info("/* %s */", __func__); assert_se(ALIGN_POWER2(0) == 0); assert_se(ALIGN_POWER2(1) == 1); assert_se(ALIGN_POWER2(2) == 2); assert_se(ALIGN_POWER2(3) == 4); assert_se(ALIGN_POWER2(12) == 16); assert_se(ALIGN_POWER2(ULONG_MAX) == 0); assert_se(ALIGN_POWER2(ULONG_MAX - 1) == 0); assert_se(ALIGN_POWER2(ULONG_MAX - 1024) == 0); assert_se(ALIGN_POWER2(ULONG_MAX / 2) == ULONG_MAX / 2 + 1); assert_se(ALIGN_POWER2(ULONG_MAX + 1) == 0); for (i = 1; i < 131071; ++i) { for (p2 = 1; p2 < i; p2 <<= 1) /* empty */ ; assert_se(ALIGN_POWER2(i) == p2); } for (i = ULONG_MAX - 1024; i < ULONG_MAX; ++i) { for (p2 = 1; p2 && p2 < i; p2 <<= 1) /* empty */ ; assert_se(ALIGN_POWER2(i) == p2); } }