Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuho/289691 to your computer and use it in GitHub Desktop.
Save kazuho/289691 to your computer and use it in GitHub Desktop.
#include <string.h>
#include <stdio.h>
#define SIZE 2
static char key[SIZE][1024];
static char value[SIZE][1024];
static int now = 0;
void put(const char* k, const char* v)
{
int i;
int found = 0;
// 重複チェック
for (i = 0; i < now; i++) {
if (strcmp(key[i], k) == 0) {
found = 1;
break;
}
}
if (found) {
// 重複があったのでつめる
for (i++; i < now; i++) {
strcpy(key[i - 1], key[i]);
strcpy(value[i - 1], value[i]);
}
now--;
} else {
// サイズがいっぱいだったら、一番古いのをすてて、他のを1つ詰める
if (now == SIZE) {
for (i = 1; i < SIZE; i++) {
strcpy(key[i - 1], key[i]);
strcpy(value[i - 1], value[i]);
}
now--;
}
}
// 最新のスロットに値を入れる
strcpy(key[now], k);
strcpy(value[now], v);
now++;
}
const char* get(const char* k)
{
int i, j;
char v[1024];
for(i = 0; i < now && strcmp(key[i], k) != 0; i++)
;
if(i == now)
return NULL;
strcpy(v, value[i]);
for (j = i+1; j < now; j++) {
strcpy(key[j - 1], key[j]);
strcpy(value[j - 1], value[j]);
}
strcpy(key[now - 1], k);
strcpy(value[now - 1], v);
return value[now - 1];
}
static int status = 0;
static void _ok(int line, int t)
{
if (! t) {
status = 1;
}
printf("%s at line %d\n", t ? "ok" : "not ok", line);
}
static void _is(int line, const char* x, const char* y)
{
int t = strcmp(x, y) == 0;
if (! t) {
status = 1;
printf("not ok %s != %s at line %d\n", x, y, line);
} else {
printf("ok at line %d\n", line);
}
}
#define ok(x) _ok(__LINE__, x)
#define is(s, t) _is(__LINE__, s, t)
int main(int argc, char **argv)
{
put("a", "danA");
ok(strcmp(key[0], "a") == 0);
ok(strcmp(value[0], "danA") == 0);
ok(now == 1);
put("b", "danB");
ok(strcmp(key[0], "a") == 0);
ok(strcmp(value[0], "danA") == 0);
ok(strcmp(key[1], "b") == 0);
ok(strcmp(value[1], "danB") == 0);
ok(now == 2);
put("c", "danC");
ok(strcmp(key[0], "b") == 0);
ok(strcmp(value[0], "danB") == 0);
ok(strcmp(key[1], "c") == 0);
ok(strcmp(value[1], "danC") == 0);
ok(now == 2);
ok(get("a") == NULL);
ok(strcmp(key[0], "b") == 0);
ok(strcmp(value[0], "danB") == 0);
ok(strcmp(key[1], "c") == 0);
ok(strcmp(value[1], "danC") == 0);
ok(now == 2);
is(get("b"), "danB");
is(key[0], "c");
is(value[0], "danC");
is(key[1], "b");
is(value[1], "danB");
ok(now == 2);
put("c", "zzzC");
is(key[0], "b");
is(value[0], "danB");
is(key[1], "c");
is(value[1], "zzzC");
return status;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment