Tcl_Hash(3tcl)

πŸ“¦
version 9.0.4 Β· 2 versions
, in debian trixie, ubuntu questing, ubuntu resolute, ubuntu stonking

🌈 Tcl_Hash(3tcl) β€” Tcl Library Procedures, but make it bestie-coded 🌈

okay so welcome to Tcl_Hash(3tcl), straight out of the Tcl Library Procedures. this is the manual for the procedures that manage hash tables, and bestie, it's a whole vibe. no cap. πŸ’…


πŸ’– NAME πŸ’–

meet the squad: Tcl_InitHashTable, Tcl_InitCustomHashTable, Tcl_InitObjHashTable, Tcl_DeleteHashTable, Tcl_CreateHashEntry, Tcl_DeleteHashEntry, Tcl_FindHashEntry, Tcl_GetHashValue, Tcl_SetHashValue, Tcl_GetHashKey, Tcl_FirstHashEntry, Tcl_NextHashEntry, and Tcl_HashStats β€” these are the procedures to manage hash tables. periodt. 🫢


✨ SYNOPSIS ✨

like, here's the include and the calls, exactly as they are:

#include <tcl.h>

Tcl_InitHashTable(tablePtr, keyType)

Tcl_InitCustomHashTable(tablePtr, keyType, typePtr)

Tcl_InitObjHashTable(tablePtr)

Tcl_DeleteHashTable(tablePtr)

Tcl_HashEntry *
Tcl_CreateHashEntry(tablePtr, key, newPtr)

Tcl_DeleteHashEntry(entryPtr)

Tcl_HashEntry *
Tcl_FindHashEntry(tablePtr, key)

void *
Tcl_GetHashValue(entryPtr)

Tcl_SetHashValue(entryPtr, value)

void *
Tcl_GetHashKey(tablePtr, entryPtr)

Tcl_HashEntry *
Tcl_FirstHashEntry(tablePtr, searchPtr)

Tcl_HashEntry *
Tcl_NextHashEntry(searchPtr)

char *
Tcl_HashStats(tablePtr)

πŸŽ€ ARGUMENTS πŸŽ€

okay so here's who's who and what they mean:

  • Tcl_HashTable *tablePtr (in) β€” address of hash table structure. for all procedures but Tcl_InitHashTable, this must have been initialized by a previous call to Tcl_InitHashTable. yes, read that twice. πŸ’…
  • int keyType (in) β€” kind of keys to use for the new hash table. must be either TCL_STRING_KEYS, TCL_ONE_WORD_KEYS, TCL_CUSTOM_TYPE_KEYS, TCL_CUSTOM_PTR_KEYS, or an integer value greater than 1. pick your fighter. ✨
  • Tcl_HashKeyType *typePtr (in) β€” address of structure which defines the behavior of the hash table.
  • const void *key (in) β€” key to use for probe into table. exact form depends on keyType used to create table.
  • int *newPtr (out) β€” the word at *newPtr is set to 1 if a new entry was created and 0 if there was already an entry for key.
  • Tcl_HashEntry *entryPtr (in) β€” pointer to hash table entry.
  • void *value (in) β€” new value to assign to hash table entry.
  • Tcl_HashSearch *searchPtr (in) β€” pointer to record to use to keep track of progress in enumerating all the entries in a hash table.

πŸ’– DESCRIPTION πŸ’–

okay bestie, buckle up, because a hash table is literally the moment. ✨

A hash table is made of zero or more entries, and every single entry is a key plus a value. You hand over the key for an entry, and the hashing routines go find that entry so fast, which means you get the value too. Slay.

Rules of the game, no cap:

  • There can be at most one entry in a hash table with any particular key.
  • But many entries can totally share the same value. It's giving "same energy, different keys." πŸ’…
  • Keys come in four forms: strings, one-word values, integer arrays, or custom keys defined by a Tcl_HashKeyType structure (peep THE TCL_HASHKEYTYPE STRUCTURE section below πŸ‘€).
  • All of the keys in a given table have the same form, and you pick that form when the table gets initialized. No mixing, bestie, that's the vibe.

The value of a hash table entry can be anything that fits in the same space as a char * pointer. Values are managed entirely by clients, not by the hash module itself β€” the module is not your mom, it is not cleaning up after you. Typically each entry's value is a pointer to a data structure that client code is managing. 🫢

Hash tables grow gracefully as the number of entries increases, so there are always less than three entries per hash bucket, on average. That's how lookups stay fast no matter how many entries you've got in the table. Growth without the drama, iconic. 🌱


The core gives you three functions for initializing hash tables: Tcl_InitHashTable, Tcl_InitObjHashTable, and Tcl_InitCustomHashTable. Let's meet them. πŸŽ€

Tcl_InitHashTable initializes a structure that describes a new hash table. The space for that structure is provided by the caller, not by the hash module β€” you bring the venue, it brings the party. 🏠 The value of keyType says what kinds of keys will be used for all entries in the table. All of the key types described later are allowed, with the exception of TCL_CUSTOM_TYPE_KEYS and TCL_CUSTOM_PTR_KEYS. Those two are not invited to this one, sorry.

Tcl_InitObjHashTable is a wrapper around Tcl_InitCustomHashTable and initializes a hash table whose keys are Tcl_Obj *. Cute little shortcut, we love a convenience function. ✨

Tcl_InitCustomHashTable initializes a structure that describes a new hash table. Again, the space for the structure is provided by the caller, not by the hash module. The value of keyType says what kinds of keys will be used for all entries in the table. keyType must have one of these values:

  • TCL_STRING_KEYS β€” keys are null-terminated strings. They get passed to hashing routines using the address of the first character of the string.
  • TCL_ONE_WORD_KEYS β€” keys are single-word values. They get passed to hashing routines and stored in hash table entries as char * values. The pointer value is the key; it doesn't need to (and usually doesn't) actually point to a string. It's just a word doing its thing. πŸ’…
  • TCL_CUSTOM_TYPE_KEYS β€” keys are of arbitrary type and are stored in the entry. Hashing and comparison are determined by typePtr. The Tcl_HashKeyType structure is described in THE TCL_HASHKEYTYPE STRUCTURE below.
  • TCL_CUSTOM_PTR_KEYS β€” keys are pointers to an arbitrary type and are stored in the entry. Hashing and comparison are determined by typePtr. Same deal, the Tcl_HashKeyType structure is described in THE TCL_HASHKEYTYPE STRUCTURE below.
  • other β€” if keyType isn't one of the above, then it must be an integer value greater than 1. In that case the keys are arrays of int values, where keyType gives the number of ints in each key. This is how you use structures as keys. All keys must have the same size. Array keys get passed into hashing functions using the address of the first int in the array. Math girlies rise πŸ™ˆ

Tcl_DeleteHashTable deletes all of the entries in a hash table and frees up the memory associated with the table's bucket array and entries. But β€” and this is the important part β€” it does not free the actual table structure (the one pointed to by tablePtr), because that memory is assumed to be managed by the client. It also does not free or otherwise manipulate the values of the hash table entries. So if those entry values point to dynamically-allocated memory, it is the client's responsibility to free those structures before deleting the table. Clean up your own room, bestie, the table is not gonna do it for you. 🧹

Tcl_CreateHashEntry locates the entry corresponding to a particular key, and creates a new entry in the table if there wasn't already one with that key. Details:

  • If an entry already existed with the given key, then *newPtr is set to zero.
  • If a new entry was created, then *newPtr is set to a non-zero value and the value of the new entry is set to zero.
  • The return value from Tcl_CreateHashEntry is a pointer to the entry, which you can use to retrieve and modify the entry's value, or to delete the entry from the table. Very versatile, very main character. πŸ‘‘

Tcl_DeleteHashEntry will remove an existing entry from a table. The memory associated with the entry itself gets freed, but the client is responsible for any cleanup associated with the entry's value β€” like freeing a structure that it points to. Again: your value, your problem. πŸ’…

Tcl_FindHashEntry is similar to Tcl_CreateHashEntry except that it does not create a new entry if the key doesn't exist; instead, it returns NULL as its result. It's the low-commitment version. πŸ™ˆ

Tcl_GetHashValue and Tcl_SetHashValue are used to read and write an entry's value, respectively. Simple. Clean. Slay.

Tcl_GetHashKey returns the key for a given hash table entry, either as:

  • a pointer to a string,
  • a one-word (char *) key, or
  • a pointer to the first word of an array of integers,

…depending on the keyType used to create the hash table. In all cases, Tcl_GetHashKey returns a result with type char *. When the key is a string or an array, the result of Tcl_GetHashKey points to information in the table entry, and that information stays valid until the entry is deleted or its table is deleted. So don't go holding onto it forever, okay? ⏳


Tcl_FirstHashEntry and Tcl_NextHashEntry are your duo for scanning all the entries in a hash table. A structure of type Tcl_HashSearch, provided by the client, keeps track of your progress through the table. Like a little bookmark but for buckets. πŸ“–

  • Tcl_FirstHashEntry initializes the search record and returns the first entry in the table (or NULL if the table is empty).
  • Each subsequent call to Tcl_NextHashEntry returns the next entry in the table, or NULL if the end of the table has been reached.
  • One call to Tcl_FirstHashEntry followed by calls to Tcl_NextHashEntry will return each of the entries in the table exactly once, in an arbitrary order. Don't expect alphabetical, don't expect insertion order, just vibe with it. 🌈
careful bestie: it is inadvisable to modify the structure of the table β€” like creating or deleting entries β€” while the search is in progress. The one exception is deleting the entry returned by Tcl_FirstHashEntry or Tcl_NextHashEntry. That one's fine. Everything else, absolutely not. 😭

Tcl_HashStats returns a dynamically-allocated string with overall information about a hash table, like the number of entries it contains, the number of buckets in its hash array, and the utilization of the buckets. It is the caller's responsibility to free the result string by passing it to Tcl_Free. Yes, you. Free it. 🫢


The header file tcl.h defines the actual data structures used to implement hash tables. This is necessary so that clients can allocate Tcl_HashTable structures and so that macros can be used to read and write the values of entries. However β€” and this is the rule, periodt β€” users of the hashing routines should never refer directly to any of the fields of any of the hash-related data structures. Use the procedures and macros defined here. Hands off the internals, bestie, that's not your business. πŸ’…


🧬 THE TCL_HASHKEYTYPE STRUCTURE 🧬

okay so listen, bestie β€” if you're an extension writer (iconic of you, honestly πŸ‘‘), you can literally make your own hash key types. the way you do it is: define four procedures, init a Tcl_HashKeyType structure to describe the type, and then call Tcl_InitCustomHashTable. that's the whole vibe. here's what the structure looks like, and yes, it's giving ✨

typedef struct {
    int version;
    int flags;
    Tcl_HashKeyProc *hashKeyProc;
    Tcl_CompareHashKeysProc *compareKeysProc;
    Tcl_AllocHashEntryProc *allocEntryProc;
    Tcl_FreeHashEntryProc *freeEntryProc;
} Tcl_HashKeyType;

the version member is the version of the table, fr fr. if this structure gets extended in the future, then the version is how you tell the different structures apart. you should set it to TCL_HASH_KEY_TYPE_VERSION. periodt. πŸ’…

the flags member is either 0 or one or more of the following values OR'ed together (yes, OR them, we love a bitwise moment 🌈):

  • TCL_HASH_KEY_RANDOMIZE_HASH β€” okay so there are some things out here, pointers for example, that just do not hash well because they don't use the lower bits. rude of them. if this flag is set, the hash table will attempt to rectify this by randomizing the bits and then using the upper N bits as the index into the table. slay, problem solved ✨
  • TCL_HASH_KEY_SYSTEM_HASH β€” this flag forces Tcl to use the memory allocation procedures provided by the operating system when allocating and freeing memory used to store the hash table data structures, and not any of Tcl's own customized memory allocation routines. this is important if the hash table is to be used in the implementation of a custom set of allocation routines, or something that a custom set of allocation routines might depend on β€” because otherwise you get a circular dependency and bestie, that's a whole mess 😭

the hashKeyProc member contains the address of a function that gets called to calculate a hash value for the key:

typedef TCL_HASH_TYPE Tcl_HashKeyProc(
        Tcl_HashTable *tablePtr,
        void *keyPtr);

if this is NULL then keyPtr is used and TCL_HASH_KEY_RANDOMIZE_HASH is assumed. iykyk πŸ’œ


the compareKeysProc member contains the address of a function that gets called to compare two keys:

typedef int Tcl_CompareHashKeysProc(
        void *keyPtr,
        Tcl_HashEntry *hPtr);

if this is NULL then the keyPtr pointers are compared. if the keys do not match then the function returns 0, otherwise it returns 1. no in-between, we don't do ambiguity here πŸŽ€


the allocEntryProc member contains the address of a function that gets called to allocate space for an entry and initialize the key and clientData:

typedef Tcl_HashEntry *Tcl_AllocHashEntryProc(
        Tcl_HashTable *tablePtr,
        void *keyPtr);

if this is NULL then Tcl_Alloc is used to allocate enough space for a Tcl_HashEntry, the key pointer is assigned to key.oneWordValue and the clientData is set to NULL. String keys and array keys use this function to allocate enough space for the entry and the key in one block, rather than doing it in two blocks. this saves space for a pointer to the key from the entry and another memory allocation β€” efficiency queen πŸ‘‘. Tcl_Obj* keys use this function to allocate enough space for an entry and increment the reference count on the value.


the freeEntryProc member contains the address of a function that gets called to free space for an entry:

typedef void Tcl_FreeHashEntryProc(
        Tcl_HashEntry *hPtr);

if this is NULL then Tcl_Free is used to free the space for the entry. Tcl_Obj* keys use this function to decrement the reference count on the value. balance restored 🧚


πŸ’– REFERENCE COUNT MANAGEMENT πŸ’–

this is the part where you actually have to pay attention, bestie, because refcounts are not a joke πŸ™ˆ

when a hash table is created with Tcl_InitCustomHashTable, the Tcl_CreateHashEntry function will increment the reference count of its key argument when it creates a key (but not if there is an existing matching key). the reference count of the key will be decremented when the corresponding hash entry is deleted, whether that's with Tcl_DeleteHashEntry or with Tcl_DeleteHashTable. and Tcl_GetHashKey will return the key without further modifying its reference count β€” it's just vibing, not touching anything 🌸

custom hash tables that use a Tcl_Obj* as key will generally need to do something similar in their allocEntryProc. so like, don't forget that part, or the refcounts get all out of whack and that's giving πŸ’€


πŸ‘€ SEE ALSO πŸ‘€


πŸ”‘ KEYWORDS πŸ”‘

hash table, key, lookup, search, value


and that's the whole page, bestie!! 🫢 this was Tcl_Hash(3tcl), straight from the Tcl source, so go forth and hash responsibly. mwah πŸ’‹ ✨

πŸ“¦ where this page comes from