kettek2/wiki/games/newsboy/Newsboy_0x00/engine/Index.c

139 lines
2.9 KiB
C

#include "Index.h"
#include <stdlib.h>
#include <string.h>
int initIndex(struct Index *index, int size) {
if (index == NULL) {
return 1;
}
if (size <= 0) {
index->size = 0;
index->bias = 0;
index->ids = NULL;
return 2;
}
index->size = size;
index->bias = size / 2;
index->ids = malloc(sizeof(char)*size);
memset(index->ids, 0, sizeof(char)*size);
return 0;
}
//
int clearIndex(struct Index *index) {
index->bias = 0;
index->size = 0;
free(index->ids);
index->ids = NULL;
return 0;
}
/* grow adds given size to index's current size, e.g., "index + 2" */
int growIndex(struct Index *index, int size) {
if (index == NULL) {
return 1;
}
if (size <= 0) {
return 2;
}
if ((index->ids = realloc(index->ids, index->size+size)) == NULL) {
return 3;
}
int i;
for(i = index->size;i < index->size+size;i++) {
index->ids[i] = 0;
}
if (index->bias == 0) {
index->bias = size/2;
} else {
index->bias = (index->bias + ((index->size+size)/2)) / 2; //FIXME
}
index->size += size;
return 0;
}
int remIndex(struct Index *index, int id) {
if (index == NULL) {
return 1;
}
if (id < 0 || id >= index->size) {
return 2;
}
index->bias += (id < index->size/2 ? -1 : 1);
index->ids[id] = 0;
return 0;
}
int addIndex(struct Index *index, int id) {
if (index == NULL) {
return 1;
}
if (id < 0 || id >= index->size) {
return 2;
}
index->bias += (id < index->size/2 ? 1 : -1);
index->ids[id] = 1;
return 0;
}
int toggleIndex(struct Index *index, int id) {
if (index == NULL) {
return 1;
}
if (id < 0 || id >= index->size) {
return 2;
}
int state = index->ids[id];
if (state == 0) {
index->bias -= (id < index->size/2 ? -1 : 1);
index->ids[id] = 1;
} else {
index->bias += (id < index->size/2 ? -1 : 1);
index->ids[id] = 0;
}
return 0;
}
int getIndex(struct Index *index, int id) {
if (index == NULL) {
return -1;
}
if (id < 0 || id >= index->size) {
return -2;
}
return index->ids[id];
}
int acquireIndex(struct Index *index) {
if (index == NULL) {
return -1;
}
if (index->size == 0) {
return -2;
}
// TODO: replace this with some magick that returns 0 or 1 from bias from center and searches towards that
// TODO: don't start from left or right totally, but start with an offset that complements the bias
/*int start, end, inc; // search start, end, and increment value respectively
if (index->bias > index->size/2) {
start = 0;
end = index->size-1;
inc = -1;
} else {
start = index->size-1;
end = 0;
inc = 1;
}
//printf("bias: %d, start: %d\n", index->bias, start);
int i;
for (i = start;i != end;i += inc) {
if (index->ids[i] == 0) {
return i;
}
}*/
int i;
for(i = 0; i < index->size; i++) {
if (index->ids[i] == 0) {
return i;
}
}
return -2;
}