본문으로 바로가기

Collections-C 라는 라이브러리가 있음. (https://github.com/srdja/Collections-C)
이 라이브러리는 hash, list등.. 유용한 C용 함수를 제공하는 꽤 괜찮은 라이브러리라 생각됨.

아래는 list를 테스트 해봄.

#include "src/common.c"
#include "src/list.c"
 
static List *list1;
 
typedef struct var_t {
    int id;
    char *name;
} var;
 
int main()
{
    var *v;
 
    list_new(&list1);
 
    v = malloc(sizeof(var));
    v->id = 1;
    v->name = strdup("abc");
    list_add(list1, v);
 
    v = malloc(sizeof(var));
    v->id = 2;
    v->name = strdup("def");
    list_add(list1, v);
 
    int i;
    for(i=0; i< list_size(list1); i++) {
        void *f;
        list_get_at(list1, i, &f);
        printf("%d\n", ((var*)f)->id);
        printf("%s\n", ((var*)f)->name);
    }
     
    for(i=0; i< list_size(list1); i++) {
        void *f;
        list_get_at(list1, i, &f);
        free(((var*)f)->name);
    }
 
    list_destroy(list1);
}
$ ./a.exe
1
abc
2
def

 

double 값을 넣는 두번째 테스트..

#include "src/common.c"
#include "src/list.c"
  
static List *list1;
  
int main()
{
    list_new(&list1);
  
    double v = 1.0;
    list_add(list1, &v);
  
    double v2 = 2.0;
    list_add(list1, &v2);
  
    int i;
    for(i=0; i< list_size(list1); i++) {
        double *f;
        list_get_at(list1, i, (void*)&f);
        printf("%llf\n", *f);
    }
      
    list_destroy(list1);
}


아래는 Hash 를 테스트..

#include "src/common.c"
#include "src/hashset.c"
#include "src/hashtable.c"
#include "src/array.c"
 
HashTable *hash;
 
typedef struct var_t {
    int id;
    char *name;
} var;
 
int main()
{
    var *v;
 
    int stat = hashtable_new(&hash);
 
    v = malloc(sizeof(var));
    v->id = 1;
    v->name = strdup("abc");
    hashtable_add(hash, "key1", v);
     
    v = malloc(sizeof(var));
    v->id = 2;
    v->name = strdup("def");
    hashtable_add(hash, "key2", v);
     
    v = malloc(sizeof(var));
    v->id = 3;
    v->name = strdup("ghi");
    hashtable_add(hash, "key3", v);
 
    // query
    var *v2;
    if (hashtable_get(hash, "key1", (void*) &v2) == CC_OK) {
        printf("id: %d, name: %s\n", ((var*)v2)->id, ((var*)v2)->name);
    }
 
    // remove key
    hashtable_remove(hash, "key1", NULL);
 
    // check removed
    if (hashtable_get(hash, "key1", (void*) &v2) != CC_OK) {
        printf("removed key1\n");
    }
 
    // size check
    size_t size = hashtable_size(hash);
    printf("hash size: %d\n", size);
 
    // free element for memory allocation
    Array *keys;
    hashtable_get_keys(hash, &keys);
    for (int i=0; i<array_size(keys); i++) {
        void *key;
        array_get_at(keys, i, &key);
     
        if (hashtable_get(hash, (char*)key, (void*) &v2) == CC_OK) {
            free(((var*)v2)->name);
            printf("free name of %s\n", (char*)key);
        }
    }
 
    // destroy
    hashtable_destroy(hash);
}
$ ./a.exe
id: 1, name: abc
removed key1
hash size: 2
free name of key3
free name of key2