-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshellmemory.c
81 lines (74 loc) · 1.6 KB
/
shellmemory.c
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
#include "shellmemory.h"
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct
{
char *key;
char *value;
} mem_t;
#define MEM_LENGTH 100
mem_t memory[MEM_LENGTH];
void shell_memory_initialize()
{
for (size_t i = 0; i < MEM_LENGTH; ++i)
{
memory[i].key = NULL;
memory[i].value = NULL;
}
}
void shell_memory_destroy()
{
for (size_t i = 0; i < MEM_LENGTH; ++i)
{
if (memory[i].key != NULL)
free(memory[i].key);
if (memory[i].value != NULL)
free(memory[i].value);
}
}
const char *shell_memory_get(const char *key)
{
for (size_t i = 0; i < MEM_LENGTH; ++i)
{
if (memory[i].key == NULL)
continue;
if (strcmp(memory[i].key, key) == 0)
return memory[i].value;
}
return NULL;
}
int shell_memory_set(const char *key, const char *value)
{
for (size_t i = 0; i < MEM_LENGTH; ++i)
{
if (memory[i].key == NULL)
continue;
if (strcmp(memory[i].key, key) == 0)
{
free(memory[i].value);
memory[i].value = strdup(value);
return 0;
}
}
size_t possible_slot = MEM_LENGTH;
for (size_t i = 0; i < MEM_LENGTH; ++i)
{
if (memory[i].key == NULL && memory[i].value == NULL)
{
possible_slot = i;
break;
}
}
if (possible_slot == MEM_LENGTH)
{
return -1;
}
else
{
memory[possible_slot].key = strdup(key);
memory[possible_slot].value = strdup(value);
return 0;
}
}