# My Digital Signal Controller Library # The objective of MyDSC library is to implement controllers with help digital signal processors, digital signal controllers or mixed signals processors.

Dependents:   mydsc_sampling_example mydsc_sampling_example mydsc-serial-example mydsc-nonblocking-example

src/mydsc_kvp.c

Committer:
ghsalazar
Date:
2020-03-28
Revision:
4:90c3f1288d41
Parent:
3:b780db800303

File content as of revision 4:90c3f1288d41:

#include "mydsc_kvp.h"
#include "mydsc_error.h"

#include <stdlib.h>
#include <string.h>

static char version[] = "0.1";

static char* get_version(void);

int mydsc_kvp_init(mydsc_kvp_t *pkv)
{
  static char key_init[] = "version";
  int nmsg = -1;
 
  if (NULL != pkv) {
    pkv->key = key_init;
    pkv->get_function = &get_version;
    pkv->set_function = NULL;
    pkv->next_kvp = NULL;     
    nmsg = 0;
  }
  return nmsg;
}

char* mydsc_kvp_get_value(mydsc_kvp_t* pkv, char* key)
{
    mydsc_kvp_t* node = pkv;
    
    if (strcmp(node->key,key) == 0)
        if (node->get_function == NULL)
            return NULL;
        else
            return (*node->get_function)();
    else if (node->next_kvp == NULL)
        return NULL;
    else
        return mydsc_kvp_get_value(node->next_kvp, key);
}

int mydsc_kvp_set_value(mydsc_kvp_t* pkv, char* key, char* value)
{
    mydsc_kvp_t* node = pkv;
    
    if (strcmp(node->key,key) == 0)
        if (node->set_function == NULL)
            return MYDSC_KVP_NO_SET;
        else {
            return (*node->set_function)(value);
        }
    else if (node->next_kvp == NULL)
        return MYDSC_KVP_NO_KEY;
    else
        return mydsc_kvp_set_value(node->next_kvp, key, value);
}

int mydsc_kvp_append(mydsc_kvp_t* pkv, char* key,
                    char* (*get_function)(void),
                    int (*set_function)(char*))
{
    mydsc_kvp_t* node = NULL;

    for (node = pkv; NULL != node->next_kvp; node = node->next_kvp);
    
    node->next_kvp = (mydsc_kvp_t*) malloc(sizeof (struct mydsc_kvp_struct));
    if (NULL == node->next_kvp)
        return MYDSC_KVP_NO_KEY;
    else {
        node->next_kvp->key = (char*) malloc(sizeof (char) * (strlen(key)+1));
        if (NULL == node->next_kvp->key) {
            free(node->next_kvp);
            node->next_kvp = NULL;
            return MYDSC_KVP_NO_KEY;
        }
        node = node->next_kvp;
        strcpy(node->key,key);
        node->get_function = get_function;
        node->set_function = set_function;
        node->next_kvp = NULL;
    }
    return MYDSC_SUCCESS;
}

static char* get_version(void)
{
    return version;    
}