18 // http://stackoverflow.com/questions/7666509/hash-function-for-string
19 uint32_t simple_hash(const char *name)
25 while((i = *s++)) hash = ((hash << 5) + hash) + i;
27 // fprintf(stderr, "HASH: %lu %s\n", hash, name);
33 // http://isthe.com/chongo/tech/comp/fnv/#FNV-1a
34 uint32_t simple_hash(const char *name) {
35 unsigned char *s = (unsigned char *)name;
36 uint32_t hval = 0x811c9dc5;
40 // multiply by the 32 bit FNV magic prime mod 2^32
42 hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24);
44 // xor the bottom with the current octet
45 hval ^= (uint32_t)*s++;
48 // fprintf(stderr, "HASH: %u = %s\n", hval, name);
53 void strreverse(char* begin, char* end)
57 aux = *end, *end-- = *begin, *begin++ = aux;
60 char *mystrsep(char **ptr, char *s)
63 while ( p && !p[0] && *ptr ) p = strsep(ptr, s);
68 // it trims spaces before and after each value
69 // it accepts quoted values in single or double quotes
70 char *qstrsep(char **ptr)
72 if(!*ptr || !**ptr) return NULL;
76 // skip leading spaces
77 while(isspace(*p)) p++;
79 // if the first char is a quote, assume quoted
80 if(*p == '"' || *p == '\'') {
83 while(*p && *p != q) p++;
95 while(*p && !isspace(*p)) p++;
107 // skip leading spaces
108 while(*s && isspace(*s)) s++;
109 if(!*s || *s == '#') return NULL;
111 // skip tailing spaces
112 int c = strlen(s) - 1;
113 while(c >= 0 && isspace(s[c])) {
117 if(c < 0) return NULL;
122 void *mymmap(const char *filename, unsigned long size, int flags)
128 fd = open(filename, O_RDWR|O_CREAT|O_NOATIME, 0664);
130 if(lseek(fd, size, SEEK_SET) == (long)size) {
131 if(write(fd, "", 1) == 1) {
133 if(ftruncate(fd, size))
134 error("Cannot truncate file '%s' to size %ld. Will use the larger file.", filename, size);
136 mem = mmap(NULL, size, PROT_READ|PROT_WRITE, flags, fd, 0);
138 if(madvise(mem, size, MADV_SEQUENTIAL|MADV_DONTFORK|MADV_WILLNEED) != 0)
139 error("Cannot advise the kernel about the memory usage of file '%s'.", filename);
142 else error("Cannot write to file '%s' at position %ld.", filename, size);
144 else error("Cannot seek file '%s' to size %ld.", filename, size);
148 else error("Cannot create/open file '%s'.", filename);
153 int savememory(const char *filename, void *mem, unsigned long size)
155 char tmpfilename[FILENAME_MAX + 1];
157 snprintf(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long)getpid());
159 int fd = open(tmpfilename, O_RDWR|O_CREAT|O_NOATIME, 0664);
161 error("Cannot create/open file '%s'.", filename);
165 if(write(fd, mem, size) != (long)size) {
166 error("Cannot write to file '%s' %ld bytes.", filename, (long)size);
174 if(rename(tmpfilename, filename)) {
175 error("Cannot rename '%s' to '%s'", tmpfilename, filename);
182 int fd_is_valid(int fd) {
183 return fcntl(fd, F_GETFD) != -1 || errno != EBADF;