/
map.h
106 lines (90 loc) · 2.4 KB
/
map.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/***************************************************************************
*
* Copyright (c) 2016 zkdnfcf, Inc. All Rights Reserved
* $Id$
*
**************************************************************************/
/**
* @file hash.h
* @author zk(zkdnfc@163.com)
* @date 2016/05/31 18:26:01
* @version $Revision$
* @brief
*
**/
#ifndef _MAP_H
#define _MAP_H
#include "rbtree.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
struct map {
struct rb_node node;
char *key;
char *val;
};
typedef struct map map_t;
typedef struct rb_root root_t;
typedef struct rb_node rb_node_t;
map_t *get(root_t *root, char *str) {
rb_node_t *node = root->rb_node;
while (node) {
map_t *data = container_of(node, map_t, node);
//compare between the key with the keys in map
int cmp = strcmp(str, data->key);
if (cmp < 0) {
node = node->rb_left;
}else if (cmp > 0) {
node = node->rb_right;
}else {
return data;
}
}
return NULL;
}
int put(root_t *root, char* key, char* val) {
map_t *data = (map_t*)malloc(sizeof(map_t));
data->key = (char*)malloc((strlen(key)+1)*sizeof(char));
strcpy(data->key, key);
data->val = (char*)malloc((strlen(val)+1)*sizeof(char));
strcpy(data->val, val);
rb_node_t **new_node = &(root->rb_node), *parent = NULL;
while (*new_node) {
map_t *this_node = container_of(*new_node, map_t, node);
int result = strcmp(key, this_node->key);
parent = *new_node;
if (result < 0) {
new_node = &((*new_node)->rb_left);
}else if (result > 0) {
new_node = &((*new_node)->rb_right);
}else {
return 0;
}
}
rb_link_node(&data->node, parent, new_node);
rb_insert_color(&data->node, root);
return 1;
}
map_t *map_first(root_t *tree) {
rb_node_t *node = rb_first(tree);
return (rb_entry(node, map_t, node));
}
map_t *map_next(rb_node_t *node) {
rb_node_t *next = rb_next(node);
return rb_entry(next, map_t, node);
}
void map_free(map_t *node){
if (node != NULL) {
if (node->key != NULL) {
free(node->key);
node->key = NULL;
free(node->val);
node->val = NULL;
}
free(node);
node = NULL;
}
}
#endif //_MAP_H
/* vim: set ts=4 sw=4 sts=4 tw=100 */