I’m trying to find an efficient deterministic way of allocating a 32-bit handle in such a way that it will operate indefinitely. A simple incrementing counter will not work because it will eventually loop around. Extending to 64-bits isn’t possible because the values will be used in a network protocol which is expecting a 32-bit value.
It’s for a real-time system so it has to be deterministic and quick. Though it’ll end up in an SQLite database I can’t just brute force test each key after loop around for example…
I think what I need is some sort of range tree that knows about all previously allocated handles (populating this on start up is fine). This seems to be a common(ish) sort of problem but it’s not one that’s solved by boost or the STL.
Any pointers?
Edit: Some additional clarification. I’m looking to have something of the order of 200k active handles in the system at any one time. Handles are deleted on a random basis.
You can’t allocate more than 2^32. But you can reallocate used handles if they are released and the problem is to keep track of the free handles.
A tree is a good way to store the free handles. Each node has a lowest and a highest handle, the left subtree contains the handles that are lesser than the lowest and the right subtree contains the handles that are greater than the highest.
An example is:
If a handle is released, it is stored in the tree. For example, if 10 is released, the tree looks like:
If handle 5 is released, you can chose to optimize the tree because 4 can be added to the 5-10 node as wel:
To:
The allocation of a handle, searches for a leaf node with 1 handle and removes it from the tree. If there are no leaves with 1 handle, just use a leaf and decrement the side that is not connected to the parent:
In the above example we allocate 1 and not 2 because if 3 is released, you can combine it with 4 and you want to keep the number of nodes as low as possible.
Below is a pseudocode algorithm. Some parts are left for the reader: