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.
12 #include <stringbucket.h>
14 #define STRINGBUCKET_STRINGSIZE 64
16 const char * strnchr(const char *s, int c, int n) {
27 struct stringbucket * stringbucket_open(const char *filename) {
29 struct stringbucket *obj = malloc(sizeof(struct stringbucket));
32 perror("stringbucket allocate");
36 obj->fd = open(filename, O_RDWR | O_APPEND | O_CREAT, 0600);
37 flock(obj->fd, LOCK_SH);
39 flock(obj->fd, LOCK_UN);
40 obj->size = st.st_size;
41 obj->list = mmap(NULL, obj->size, PROT_READ | PROT_WRITE, MAP_SHARED, obj->fd, 0);
42 if (obj->list == NULL) {
43 perror("stringbucket mmap");
52 void stringbucket_close(struct stringbucket *sb) {
53 munmap(sb->list, sb->size);
58 int stringbucket_find(struct stringbucket *sb, const char *string) {
59 char * end = sb->list + sb->size;
60 int string_len = strlen(string);
62 char * ptr = sb->list;
64 char * next = (char *) strnchr(ptr, '\n', end - ptr);
68 if (len > STRINGBUCKET_STRINGSIZE)
69 len = STRINGBUCKET_STRINGSIZE;
70 if (memcmp(ptr, string, (len < string_len ? string_len : len)) == 0) {
71 return (ptr - sb->list);
79 int stringbucket_add(struct stringbucket *sb, const char *string) {
80 if (stringbucket_find(sb, string) != -1) return 0;
81 flock(sb->fd, LOCK_EX);
82 write(sb->fd, string, strlen(string));
83 write(sb->fd, "\n", 1);
84 flock(sb->fd, LOCK_UN);
88 int stringbucket_delete(struct stringbucket *sb, const char *string) {
89 int pos = stringbucket_find(sb, string);
90 if (pos == -1) return 0;
92 /* We doin' it DOS style! */
96 void stringbucket_iterate(struct stringbucket *sb, void (*iter)(char *, void *), void *stuff) {
97 char string[STRINGBUCKET_STRINGSIZE + 1];
98 char * ptr = sb->list;
99 char * end = sb->list + sb->size;
102 char * next = (char *) strnchr(ptr, '\n', end - ptr);
109 int len = next - ptr;
110 memcpy(string, ptr, len);