Own fork of MbedSmartRestMain

Dependencies:   C027_Support C12832 LM75B MMA7660 MbedSmartRest mbed-rtos mbed

Fork of MbedSmartRestMain by Cumulocity Official

util/dict.h

Committer:
xinlei
Date:
2015-04-27
Revision:
95:5dfdc8568e9f
Child:
98:e369fc75c000

File content as of revision 95:5dfdc8568e9f:

#ifndef DICH_H
#define DICH_H
#include <string.h>
#define MAX_KEY_LEN 50
#define MAX_VALUE_LEN 50
#define MAX_ITEM_SIZE 5

class Dict
{
public:
        struct Item {
                char key[MAX_KEY_LEN];
                char value[MAX_VALUE_LEN];
        };

        Dict(): count(0) {}

        const Item* at(const size_t i) const {
                if (i < count) return &items[i];
                else return NULL;
        }

        const Item* get(const char *k) const {
                size_t i = find(k);
                if (i < count)
                        return &items[i];
                else
                        return NULL;
        }

        const Item* set(const char *k, const char *v) {
                size_t i = find(k);
                if (i < count) {
                        strncpy(items[i].value, v, MAX_VALUE_LEN);
                        return &items[i];
                } else if (count < MAX_ITEM_SIZE){
                        ++count;
                        strncpy(items[i].key, k, MAX_KEY_LEN);
                        strncpy(items[i].value, v, MAX_VALUE_LEN);
                        return &items[i];
                } else
                        return NULL;
        }

        size_t maxSize() const { return MAX_ITEM_SIZE; }
        size_t maxKeyLen() const { return MAX_KEY_LEN; }
        size_t maxValueLen() const { return MAX_VALUE_LEN; }
        size_t size() const { return count; }
        bool empty() const { return count==0; }
        bool full() const { return count == MAX_ITEM_SIZE; }
        virtual ~Dict() {}
protected:
        size_t find(const char* k) const {
                for (size_t i = 0; i < count; ++i) {
                        if (strncmp(items[i].key, k, MAX_KEY_LEN) == 0)
                                return i;
                }
                return count;
        }
private:
        Item items[MAX_ITEM_SIZE];
        size_t count;
};

#endif /* DICH_H */