ZHASH(3)

✨ NAME ✨

zhash β€” Class for simple generic hash container πŸ’–

(yes bestie, that's the CZMQ Manual, section 3, and we are about to get so into it πŸ¦‹)


πŸŽ€ SYNOPSIS πŸŽ€

okay so first things first, the tea β˜•: this is a stable class, and it may not change except for emergencies. It is provided in stable builds. So like, it's not going anywhere, she's committed πŸ’…

🫢 the callback type

zhash_free_fn β€” the callback function for the zhash_freefn method:

typedef void (zhash_free_fn) (
    void *data);

🌸 the functions

zhash_new β€” create a new, empty hash container. Fresh out the box, zero items, main character energy πŸ‘‘

CZMQ_EXPORT zhash_t *
    zhash_new (void);

zhash_unpack β€” unpacks a binary frame into a brand new hash table. The packed data must follow the format defined by zhash_pack. The resulting hash table is set to autofree. And a lil fun fact: an empty frame unpacks to an empty hash table πŸ«™βœ¨

CZMQ_EXPORT zhash_t *
    zhash_unpack (zframe_t *frame);

zhash_destroy β€” destroy a hash container and all items in it. It takes a pointer-to-pointer, so it can null out your reference for you. Gone, reduced to atoms πŸ’€

CZMQ_EXPORT void
    zhash_destroy (zhash_t **self_p);

zhash_insert β€” insert an item into the hash table with the specified key and item. If the key is already present, it returns -1 and leaves the existing item unchanged. Returns 0 on success πŸ™Œ

CZMQ_EXPORT int
    zhash_insert (zhash_t *self, const char *key, void *item);

zhash_update β€” update an item into the hash table with the specified key and item. If the key is already present, it destroys the old item and inserts the new one. Use the free_fn method to ensure the deallocator is properly called on the item 🧹

CZMQ_EXPORT void
    zhash_update (zhash_t *self, const char *key, void *item);

zhash_delete β€” remove an item specified by key from the hash table. If there was no such item, this function does nothing. No drama, no error, just vibes 🌈

CZMQ_EXPORT void
    zhash_delete (zhash_t *self, const char *key);

zhash_lookup β€” return the item at the specified key, or null if it's not there πŸ”

CZMQ_EXPORT void *
    zhash_lookup (zhash_t *self, const char *key);

zhash_rename β€” reindexes an item from an old key to a new key. If there was no such item, does nothing. Returns 0 if successful, else -1. Glow-up for your key πŸ¦‹

CZMQ_EXPORT int
    zhash_rename (zhash_t *self, const char *old_key, const char *new_key);

zhash_freefn β€” set a free function for the specified hash table item. When the item is destroyed, the free function, if any, is called on that item. Use this when hash items are dynamically allocated, so you don't leak memory like it's 2013 😭 You can pass free or NULL as a free_fn. Returns the item, or NULL if there is no such item.

CZMQ_EXPORT void *
    zhash_freefn (zhash_t *self, const char *key, zhash_free_fn free_fn);

zhash_size β€” return the number of keys/items in the hash table πŸ”’

CZMQ_EXPORT size_t
    zhash_size (zhash_t *self);

zhash_dup β€” make a copy of the hash table; if the supplied table is null, returns null. It does not copy the items themselves. It rebuilds a new table so it may be slow on very large tables. NOTE: it only works with item values that are strings, since there's no other way to know how to duplicate the item value. The caller owns the return value and must destroy it when done πŸ”

CZMQ_EXPORT zhash_t *
    zhash_dup (zhash_t *self);

zhash_keys β€” return the keys for items in the table. The caller owns the return value and must destroy it when done πŸ—οΈ

CZMQ_EXPORT zlist_t *
    zhash_keys (zhash_t *self);

zhash_first β€” simple iterator; returns the first item in the hash table, in no given order, or NULL if the table is empty. This method is simpler to use than the foreach() method, which is deprecated. To access the key for this item, use zhash_cursor(). NOTE: do NOT modify the table while iterating 🚫

CZMQ_EXPORT void *
    zhash_first (zhash_t *self);

zhash_next β€” simple iterator; returns the next item in the hash table, in no given order, or NULL if the last item was already returned. Use this together with zhash_first() to process all items in a hash table. If you need the items in sorted order, use zhash_keys() and then zlist_sort(). To access the key for this item, use zhash_cursor(). NOTE: do NOT modify the table while iterating 🚫

CZMQ_EXPORT void *
    zhash_next (zhash_t *self);

zhash_cursor β€” after a successful first/next method, returns the key for the item that was returned. This is a constant string that you may not modify or deallocate, and which lasts as long as the item in the hash. After an unsuccessful first/next, returns NULL. Hands off, bestie πŸ™ˆ

CZMQ_EXPORT const char *
    zhash_cursor (zhash_t *self);

zhash_comment β€” add a comment to the hash table before saving to disk. You can add as many comment lines as you like. These comment lines are discarded when loading the file. If you use a null format, all comments are deleted πŸ’¬

CZMQ_EXPORT void
    zhash_comment (zhash_t *self, const char *format, ...) CHECK_PRINTF (2);

zhash_pack β€” serialize the hash table to a binary frame that can be sent in a message. The packed format is compatible with the dictionary type defined in http://rfc.zeromq.org/spec:35/FILEMQ, and implemented by zproto:

; A list of name/value pairs
dictionary      = dict-count *( dict-name dict-value )
dict-count      = number-4
dict-value      = longstr
dict-name       = string

; Strings are always length + text contents
longstr         = number-4 *VCHAR
string          = number-1 *VCHAR

; Numbers are unsigned integers in network byte order
number-1        = 1OCTET
number-4        = 4OCTET

Comments are not included in the packed data. Item values MUST be strings. The caller owns the return value and must destroy it when done πŸ“¦

CZMQ_EXPORT zframe_t *
    zhash_pack (zhash_t *self);

zhash_save β€” save the hash table to a text file in name=value format. Hash values must be printable strings; keys may not contain the = character. Returns 0 if OK, else -1 if a file error occurred πŸ’Ύ

CZMQ_EXPORT int
    zhash_save (zhash_t *self, const char *filename);

zhash_load β€” load the hash table from a text file in name=value format; the hash table must already exist. Hash values must be printable strings; keys may not contain the = character. Returns 0 if OK, else -1 if a file was not readable πŸ“‚

CZMQ_EXPORT int
    zhash_load (zhash_t *self, const char *filename);

zhash_refresh β€” when a hash table was loaded from a file by zhash_load, this method will reload the file if it has been modified since, and is "stable", i.e. not still changing. Returns 0 if OK, -1 if there was an error reloading the file πŸ”„

CZMQ_EXPORT int
    zhash_refresh (zhash_t *self);

zhash_autofree β€” set the hash for automatic value destruction. Note that this assumes that values are NULL-terminated strings. Do not use with different types ⚠️

CZMQ_EXPORT void
    zhash_autofree (zhash_t *self);

zhash_test β€” self test of this class πŸ§ͺ

CZMQ_EXPORT void
    zhash_test (bool verbose);
Please add '@interface' section in './../src/zhash.c'. πŸ“

πŸ’œ DESCRIPTION πŸ’œ

zhash is an expandable hash table container. That's it, that's the whole thing β€” she's a simple container 🫢

For heavy-duty applications, we recommend using zhashx. Like, if you're doing Serious Businessβ„’, go see her cousin.

And now for the honest part, no cap: note that it's relatively slow β€” 50K insertions/deletes per second β€” so don't do inserts/updates on the critical path for message I/O. Keep that off the hot path, bestie, she's not built for it 😭

What she can do is 2.5M lookups per second for 16-char keys. Timed on a 1.6GHz CPU. Lookups? Slay. Inserts? Not so much πŸ’…


and that's only part one, we're not even done β€” more incoming ✨

✨ EXAMPLE ✨

okay bestie this is the whole vibe, straight from zhash_test β€” it's giving the tutorial, fr fr πŸ’–

zhash_t *hash = zhash_new ();
assert (hash);
assert (zhash_size (hash) == 0);
assert (zhash_first (hash) == NULL);
assert (zhash_cursor (hash) == NULL);

//  Insert some items
int rc;
rc = zhash_insert (hash, "DEADBEEF", "dead beef");
char *item = (char *) zhash_first (hash);
assert (streq (zhash_cursor (hash), "DEADBEEF"));
assert (streq (item, "dead beef"));
assert (rc == 0);
rc = zhash_insert (hash, "ABADCAFE", "a bad cafe");
assert (rc == 0);
rc = zhash_insert (hash, "C0DEDBAD", "coded bad");
assert (rc == 0);
rc = zhash_insert (hash, "DEADF00D", "dead food");
assert (rc == 0);
assert (zhash_size (hash) == 4);

//  Look for existing items
item = (char *) zhash_lookup (hash, "DEADBEEF");
assert (streq (item, "dead beef"));
item = (char *) zhash_lookup (hash, "ABADCAFE");
assert (streq (item, "a bad cafe"));
item = (char *) zhash_lookup (hash, "C0DEDBAD");
assert (streq (item, "coded bad"));
item = (char *) zhash_lookup (hash, "DEADF00D");
assert (streq (item, "dead food"));

//  Look for non-existent items
item = (char *) zhash_lookup (hash, "foo");
assert (item == NULL);

//  Try to insert duplicate items
rc = zhash_insert (hash, "DEADBEEF", "foo");
assert (rc == -1);
item = (char *) zhash_lookup (hash, "DEADBEEF");
assert (streq (item, "dead beef"));

//  Some rename tests

//  Valid rename, key is now LIVEBEEF
rc = zhash_rename (hash, "DEADBEEF", "LIVEBEEF");
assert (rc == 0);
item = (char *) zhash_lookup (hash, "LIVEBEEF");
assert (streq (item, "dead beef"));

//  Trying to rename an unknown item to a non-existent key
rc = zhash_rename (hash, "WHATBEEF", "NONESUCH");
assert (rc == -1);

//  Trying to rename an unknown item to an existing key
rc = zhash_rename (hash, "WHATBEEF", "LIVEBEEF");
assert (rc == -1);
item = (char *) zhash_lookup (hash, "LIVEBEEF");
assert (streq (item, "dead beef"));

//  Trying to rename an existing item to another existing item
rc = zhash_rename (hash, "LIVEBEEF", "ABADCAFE");
assert (rc == -1);
item = (char *) zhash_lookup (hash, "LIVEBEEF");
assert (streq (item, "dead beef"));
item = (char *) zhash_lookup (hash, "ABADCAFE");
assert (streq (item, "a bad cafe"));

//  Test keys method
zlist_t *keys = zhash_keys (hash);
assert (zlist_size (keys) == 4);
zlist_destroy (&keys);

//  Test dup method
zhash_t *copy = zhash_dup (hash);
assert (zhash_size (copy) == 4);
item = (char *) zhash_lookup (copy, "LIVEBEEF");
assert (item);
assert (streq (item, "dead beef"));
zhash_destroy (&copy);

//  Test pack/unpack methods
zframe_t *frame = zhash_pack (hash);
copy = zhash_unpack (frame);
zframe_destroy (&frame);
assert (zhash_size (copy) == 4);
item = (char *) zhash_lookup (copy, "LIVEBEEF");
assert (item);
assert (streq (item, "dead beef"));
zhash_destroy (&copy);

//  Test save and load
zhash_comment (hash, "This is a test file");
zhash_comment (hash, "Created by %s", "czmq_selftest");
zhash_save (hash, ".cache");
copy = zhash_new ();
assert (copy);
zhash_load (copy, ".cache");
item = (char *) zhash_lookup (copy, "LIVEBEEF");
assert (item);
assert (streq (item, "dead beef"));
zhash_destroy (&copy);
zsys_file_delete (".cache");

//  Delete a item
zhash_delete (hash, "LIVEBEEF");
item = (char *) zhash_lookup (hash, "LIVEBEEF");
assert (item == NULL);
assert (zhash_size (hash) == 3);

//  Check that the queue is robust against random usage
struct {
    char name [100];
    bool exists;
} testset [200];
memset (testset, 0, sizeof (testset));
int testmax = 200, testnbr, iteration;

srandom ((unsigned) time (NULL));
for (iteration = 0; iteration < 25000; iteration++) {
    testnbr = randof (testmax);
    assert (testnbr != testmax);
    assert (testnbr < testmax);
    if (testset [testnbr].exists) {
        item = (char *) zhash_lookup (hash, testset [testnbr].name);
        assert (item);
        zhash_delete (hash, testset [testnbr].name);
        testset [testnbr].exists = false;
    }
    else {
        sprintf (testset [testnbr].name, "%x-%x", rand (), rand ());
        if (zhash_insert (hash, testset [testnbr].name, "") == 0)
            testset [testnbr].exists = true;
    }
}
//  Test 10K lookups
for (iteration = 0; iteration < 10000; iteration++)
    item = (char *) zhash_lookup (hash, "DEADBEEFABADCAFE");

//  Destructor should be safe to call twice
zhash_destroy (&hash);
zhash_destroy (&hash);
assert (hash == NULL);

// Test autofree; automatically copies and frees string values
hash = zhash_new ();
assert (hash);
zhash_autofree (hash);
char value [255];
strcpy (value, "This is a string");
rc = zhash_insert (hash, "key1", value);
assert (rc == 0);
strcpy (value, "Inserting with the same key will fail");
rc = zhash_insert (hash, "key1", value);
assert (rc == -1);
strcpy (value, "Ring a ding ding");
rc = zhash_insert (hash, "key2", value);
assert (rc == 0);
assert (streq ((char *) zhash_lookup (hash, "key1"), "This is a string"));
assert (streq ((char *) zhash_lookup (hash, "key2"), "Ring a ding ding"));
zhash_destroy (&hash);

#if defined (__WINDOWS__)
zsys_shutdown();
#endif

like… look at her go 🫢 the "DEADBEEF" β†’ "LIVEBEEF" glow-up, the .cache save/load round trip, the 25000 iterations of pure chaos, the destructor getting called twice on purpose (she's safe bestie, it's fine), and zhash_autofree copying your string so you can scribble all over value afterward without a care πŸ’… iconic behavior only.


🌸 AUTHORS 🌸

the czmq manual was written by the authors in the AUTHORS file. yes, those authors. legends, honestly πŸ‘‘


πŸ¦‹ RESOURCES πŸ¦‹

  • Main web site:
  • Report bugs to the email <zeromq-dev@lists.zeromq.org[1]>

Copyright (c) the Contributors as noted in the AUTHORS file. This file is part of CZMQ, the high-level C binding for 0MQ: http://czmq.zeromq.org. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. LICENSE included with the czmq distribution.


⭐ NOTES ⭐

  1. <zeromq-dev@lists.zeromq.org> mailto:zeromq-dev@lists.zeromq.org

and that's a wrap on ZHASH(3) bestie πŸ’– go forth and hash responsibly, no cap.

this one's from CZMQ 4.2.1, dated 01/16/2026 β€” so fresh, so clean, mwah πŸ’…βœ¨

πŸ“¦ where this page comes from