Advanced Distributed Systems module at HSLU
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

64 lines
1.3 KiB

/*
* dict.c
*
* Created on: 30 Sep 2022
* Author: simon
*/
#include "dict.h"
#include <stdlib.h>
#include <string.h>
dict_t** dictAlloc(void){
return malloc(sizeof(dict_t));
}
void dictDealoc(dict_t** dict){
free(dict);
}
void* getItem(dict_t* dict, char* key){
dict_t *ptr;
for(ptr =dict; ptr !=NULL; ptr=ptr->next){
if(strcmp(ptr->key, key) == 0){
return ptr->value;
}
}
return NULL;
}
void delItem(dict_t** dict, char* key){
dict_t *ptr, *prev;
for(ptr=*dict, prev=NULL; ptr!=NULL; prev=ptr, ptr=ptr->next){
if(strcmp(ptr->key, key) == 0){ // key match?
if(ptr->next != NULL){ // not at end of dict?
if(prev == NULL){
*dict = ptr->next; // item is first one in dict
}else{
prev->next = ptr->next; // not first and last -> set to next
}
}else if(prev != NULL){
prev->next = NULL; // at end, delete last item
}else{
*dict=NULL; // first and last -> only one item in dict
}
free(ptr->key);
free(ptr);
return;
}
}
}
void addItem(dict_t** dict, char* key, void* value){
if(((dict_t*)dict)->key !=NULL){
delItem(dict, key); // if item already exists delete it!
}
dict_t *d = (dict_t*)malloc(sizeof(struct dict_t_struct)); // new dict
d->key = (char*)malloc(strlen(key)+1);
// set values
strcpy(d->key, key);
d->value = value;
d->next = *dict;
// item at first pos
*dict=d;
}