Skip to content

Feature: allow setting custom capacity#15

Open
koutoftimer wants to merge 2 commits intoMashpoe:mainfrom
koutoftimer:feature/allow-custom-capacity
Open

Feature: allow setting custom capacity#15
koutoftimer wants to merge 2 commits intoMashpoe:mainfrom
koutoftimer:feature/allow-custom-capacity

Conversation

@koutoftimer
Copy link
Copy Markdown

Pushed changes upsteam.

In my use case, I know maximum amount of keys/buckets of the map and I wanted a way to set capacity.

I ended up supporting both:

  • at compilation time via HASHMAP_DEFAULT_CAPACITY
  • at runtime as optional .capacity = <value> argument to hashmap_create.

Splitting `hashmap_create` into `hashmap_create_impl` and
`hashmap_create_opts` is required to maintain backward compatibility and
improve UX, because C doesn't not allow optional arguments.
@koutoftimer
Copy link
Copy Markdown
Author

koutoftimer commented Dec 2, 2025

It is possible to move HASHMAP_DEFAULT_CAPACITY to header file in order to explicitly set .capacity to HASHMAP_DEFAULT_CAPACITY and prevent zero initialization ambiguvity.

#ifndef HASHMAP_DEFAULT_CAPACITY
#  define HASHMAP_DEFAULT_CAPACITY 20
#endif

#define hashmap_create(opts) \
        hashmap_create_impl((struct hashmap_create_opts){ \
          .capacity = HASHMAP_DEFAULT_CAPACITY,           \
           opts                                           \
        })

It allows to set

	m->capacity = opts.capacity;

without any additional logic.

UPD: but, on the other hand, compilers may argue about

warning: initializer overrides prior initialization of this subobject [-Winitializer-overrides]  // clang
warning: initialized field overwritten [-Woverride-init] // gcc

or something like that, as soon as you'll try to override .capacity value. clang-20 does, but gcc-14 - doesn't.. at least with default compilation flags (but with -Wall -Wextra it does too).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant