VgaGames4 - hash man-pages

[.. upper level ..]

Hash functions

Hashes are a sort of arrays with strings as index instead of integers. The key must be a string, the value may be a structure, a string or an integer (or boolean). There are some VgaGames4 functions that use a hash as parameter.


Example


example.c

/* hash example */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <vgagames4.h>

int main(int argc, char **argv) {
  struct VG_Hash *hsh;
  void *vpos;
  const char *key;
  struct { int i1; int i2; } sti, *stip;

  (void)argc; (void)argv;

  /* initialize VgaGames library */
  if (!VG_init("window-example")) { exit(1); }

  /* create hash */
  hsh = vg4->hash->create();

  /* insert an entry with a structure */
  sti.i1 = 10; sti.i2 = 20;
  vg4->hash->set(hsh, "Structure", &sti, sizeof(sti));

  /* insert an entry with a string */
  vg4->hash->setstr(hsh, "String", "Hello dude");

  /* insert an entry with an integer */
  vg4->hash->setint(hsh, "Integer", 17);

  /* list entries and their values */
  printf("List of entries:\n");
  vpos = NULL;
  for (key = vg4->hash->list(hsh, &vpos); vpos != NULL; key = vg4->hash->list(hsh, &vpos)) {
    if (vg4->hash->isnum(hsh, key)) {
      /* value is an integer */
      printf(" - %s: %d\n", key, vg4->hash->getint(hsh, key));
    } else {
      /* value is a pointer, may be a string or something else */
      if (strcmp(key, "String") == 0) {  /* value for this key was inserted as a string */
        printf(" - %s: %s\n", key, (char *)vg4->hash->get(hsh, key, NULL));
      } else if (strcmp(key, "Structure") == 0) {  /* value for this key was inserted as a structure */
        stip = vg4->hash->get(hsh, key, NULL);
        printf(" - %s: i1=%d, i2=%d\n", key, stip->i1, stip->i2);
      }
    }

    /* now remove entry */
    vpos = vg4->hash->remove(hsh, key);
  }

  /* check if hash is empty (must be, as all entries were removed) */
  if (vg4->hash->is_empty(hsh)) {
    printf("Hash is empty\n");
  } else {
    printf("Hash is not empty! Why???\n");
  }

  /* destroy and exit */
  VG_dest();
  exit(0);
}

Output

List of entries:
 - Structure: i1=10, i2=20
 - Integer: 17
 - String: Hello dude
Hash is empty