C Collections

chashmap · Section 3

chmap_get_ptr

chmap_get_ptr - get pointer to value by key (type-inferred)

C Collections (libccollections, -lccollections)

#include <ccollections/chashmap.h>
 
value_ptr = chmap_get_ptr(hm_name, key);

Type-inferred wrapper for chashmap_get_elem_ref() that returns a pointer to
the value, or NULL when the map does not hold the key. Unlike chmap_get(),
a missing key does not stop the program.
 
The lookup key is converted through the DECLARED key type of the map,
the same way chmap_insert(3) converts it, so a key stored through that
conversion is only found again by a lookup that makes the same
conversion. A literal and a computed expression both work.

hm_name  Hash map to search
key      Key to look up

A pointer to the value if the key is found, or NULL if it is not

Returns NULL when the map does not hold the key (it does not stop the
program)
Returns NULL when key is a NULL character pointer, since that is not
a string
Stops the program when the size of the value does not match the size
of the type
Returns a pointer to the value, so you can change the value in place
The pointer is correctly aligned for the type of the value, with both
internal backends
A later insert, delete or resize invalidates the pointer
For a char* value type, the target of the pointer is const
(char *const *). You can read the stored string and edit its bytes in
place within the stored length, but replacing the pointer itself is a
compile error. The map owns the string bytes and keeps its own accessor
in step with them, so after a replaced pointer the accessor's length
would describe the earlier string. To replace a string value call
chmap_insert(3), which frees the old bytes and copies the new ones into
storage that the map owns
For a float or double key, chmap_construct(3) gives the key equality
contract (bitwise, except that -0.0 becomes 0.0)
For a long double key, chmap_construct(3) gives the key equality contract
(by value, unlike every other key type)

chmap_construct(map, int, int);
int key = 42, val = 100;
chmap_insert(map, key, val);
int* ptr = chmap_get_ptr(map, key);
if (ptr) {
  *ptr = 200; // Change the value in place
}
 
chmap_construct(names, int, char *);
chmap_insert(names, key, "hello");
char *const *sptr = chmap_get_ptr(names, key);
if (sptr) {
  printf("%s\n", *sptr);  // Read the stored string
  (*sptr)[0] = 'j';         // Edit its bytes in place: "jello"
  chmap_insert(names, key, "a longer replacement");  // Replace it
}
chmap_destroy(map);
chmap_destroy(names);

chmap_get(3), chashmap_get_elem_ref(3), chmap_insert(3), chmap_construct(3)