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);
34 // http://isthe.com/chongo/tech/comp/fnv/#FNV-1a
35 uint32_t simple_hash(const char *name) {
36 unsigned char *s = (unsigned char *)name;
37 uint32_t hval = 0x811c9dc5;
41 // multiply by the 32 bit FNV magic prime mod 2^32
43 hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24);
45 // xor the bottom with the current octet
46 hval ^= (uint32_t)*s++;
49 // fprintf(stderr, "HASH: %u = %s\n", hval, name);
54 // http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
56 uint32_t simple_hash(const char *name) {
57 unsigned char *s = (unsigned char *)name;
70 // fprintf(stderr, "HASH: %u = %s\n", h, name);
76 void strreverse(char* begin, char* end)
80 aux = *end, *end-- = *begin, *begin++ = aux;
83 char *mystrsep(char **ptr, char *s)
86 while ( p && !p[0] && *ptr ) p = strsep(ptr, s);
92 // skip leading spaces
93 while(*s && isspace(*s)) s++;
94 if(!*s || *s == '#') return NULL;
96 // skip tailing spaces
97 int c = strlen(s) - 1;
98 while(c >= 0 && isspace(s[c])) {
102 if(c < 0) return NULL;
107 void *mymmap(const char *filename, unsigned long size, int flags)
113 fd = open(filename, O_RDWR|O_CREAT|O_NOATIME, 0664);
115 if(lseek(fd, size, SEEK_SET) == (long)size) {
116 if(write(fd, "", 1) == 1) {
118 if(ftruncate(fd, size))
119 error("Cannot truncate file '%s' to size %ld. Will use the larger file.", filename, size);
121 mem = mmap(NULL, size, PROT_READ|PROT_WRITE, flags, fd, 0);
123 if(madvise(mem, size, MADV_SEQUENTIAL|MADV_DONTFORK|MADV_WILLNEED) != 0)
124 error("Cannot advise the kernel about the memory usage of file '%s'.", filename);
127 else error("Cannot write to file '%s' at position %ld.", filename, size);
129 else error("Cannot seek file '%s' to size %ld.", filename, size);
133 else error("Cannot create/open file '%s'.", filename);
138 int savememory(const char *filename, void *mem, unsigned long size)
140 char tmpfilename[FILENAME_MAX + 1];
142 snprintf(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long)getpid());
144 int fd = open(tmpfilename, O_RDWR|O_CREAT|O_NOATIME, 0664);
146 error("Cannot create/open file '%s'.", filename);
150 if(write(fd, mem, size) != (long)size) {
151 error("Cannot write to file '%s' %ld bytes.", filename, (long)size);
159 if(rename(tmpfilename, filename)) {
160 error("Cannot rename '%s' to '%s'", tmpfilename, filename);
167 int fd_is_valid(int fd) {
168 return fcntl(fd, F_GETFD) != -1 || errno != EBADF;