1 /* Blerg is (C) 2011 The Dominion of Awesome, and is distributed under a
2 * BSD-style license. Please see the COPYING file for details.
13 #include <stringbucket.h>
15 #define STRINGBUCKET_STRINGSIZE 64
17 const char * strnchr(const char *s, int c, int n) {
28 struct stringbucket * stringbucket_open(const char *filename) {
30 struct stringbucket *obj = malloc(sizeof(struct stringbucket));
33 perror("stringbucket allocate");
37 obj->fd = open(filename, O_RDWR | O_APPEND | O_CREAT, 0600);
38 flock(obj->fd, LOCK_SH);
40 flock(obj->fd, LOCK_UN);
41 obj->size = st.st_size;
42 obj->list = mmap(NULL, obj->size, PROT_READ | PROT_WRITE, MAP_SHARED, obj->fd, 0);
43 if (obj->list == NULL) {
44 perror("stringbucket mmap");
53 void stringbucket_close(struct stringbucket *sb) {
54 munmap(sb->list, sb->size);
59 int stringbucket_find(struct stringbucket *sb, const char *string) {
60 char * end = sb->list + sb->size;
61 int string_len = strlen(string);
63 char * ptr = sb->list;
65 char * next = (char *) strnchr(ptr, '\n', end - ptr);
69 if (len > STRINGBUCKET_STRINGSIZE)
70 len = STRINGBUCKET_STRINGSIZE;
71 if (memcmp(ptr, string, (len < string_len ? string_len : len)) == 0) {
72 return (ptr - sb->list);
80 int stringbucket_add(struct stringbucket *sb, const char *string) {
81 if (stringbucket_find(sb, string) != -1) return 0;
82 flock(sb->fd, LOCK_EX);
83 write(sb->fd, string, strlen(string));
84 write(sb->fd, "\n", 1);
85 flock(sb->fd, LOCK_UN);
89 int stringbucket_delete(struct stringbucket *sb, const char *string) {
90 int pos = stringbucket_find(sb, string);
91 if (pos == -1) return 0;
93 /* We doin' it DOS style! */
98 void stringbucket_iterate(struct stringbucket *sb, void (*iter)(char *, void *), void *stuff) {
99 char string[STRINGBUCKET_STRINGSIZE + 1];
100 char * ptr = sb->list;
101 char * end = sb->list + sb->size;
104 char * next = (char *) strnchr(ptr, '\n', end - ptr);
111 int len = next - ptr;
112 memcpy(string, ptr, len);