|
Post by Pjot on Sept 3, 2017 17:45:09 GMT 1
All, Though BaCon has a native implementation for key-value structures (by using associative arrays) there is a way to do this using hash tables, and in a more sophisticated way. The below example uses uthash, an open-source implementation completely built on C macros. It fits in only one C header file and has very powerful features. Regards Peter ' UThash header file PRAGMA INCLUDE uthash-master/src/uthash.h
' Optionally choose HASH function PRAGMA OPTIONS -DHASH_FUNCTION=HASH_BER
OPTION PARSE FALSE
' Main key-value store RECORD Hash_Table LOCAL key TYPE char* LOCAL value TYPE char* LOCAL hh TYPE UT_hash_handle END RECORD
' Main data tree DECLARE data = NULL TYPE Hash_Table_type*
' Add items SUB Add_Data(char *idx, char *info)
LOCAL entry TYPE Hash_Table_type*
entry = malloc(SIZEOF(Hash_Table_type))
entry->key = strdup(idx) entry->value = strdup(info)
HASH_ADD_STR(data, key, entry)
END SUB
' Search items FUNCTION Find_Data$(char *idx) TYPE char*
LOCAL find = NULL TYPE Hash_Table_type*
HASH_FIND_STR(data, idx, find)
RETURN find->value
END FUNCTION
' Example Add_Data("one", "English") Add_Data("two", "Dutch") Add_Data("three", "Spanish") Add_Data("four", "Italian")
PRINT "Total entries: ", HASH_COUNT(data)
PRINT "Entry: ", Find_Data$("three")
|
|
|
Post by vovchik on Sept 4, 2017 13:55:44 GMT 1
Dear Peter,
Thanks. Just tested and it works - and is easy to use....
With kind regards, vovchik
|
|