harec

[hare] Hare compiler, written in C11 for POSIX OSs
Log | Files | Refs | README | LICENSE

util.c (1714B)


      1 #include <stdlib.h>
      2 #include <stdint.h>
      3 #include <string.h>
      4 #include "util.h"
      5 // Remove safety macros:
      6 #undef malloc
      7 #undef calloc
      8 #undef realloc
      9 
     10 const char **sources;
     11 
     12 uint32_t
     13 fnv1a(uint32_t hash, unsigned char c)
     14 {
     15 	return (hash ^ c) * 16777619;
     16 }
     17 
     18 uint32_t
     19 fnv1a_u32(uint32_t hash, uint32_t u32)
     20 {
     21 	hash = fnv1a(hash, (u32) & 0xFF);
     22 	hash = fnv1a(hash, (u32 >> 8) & 0xFF);
     23 	hash = fnv1a(hash, (u32 >> 16) & 0xFF);
     24 	hash = fnv1a(hash, (u32 >> 24) & 0xFF);
     25 	return hash;
     26 }
     27 
     28 uint32_t
     29 fnv1a_u64(uint32_t hash, uint64_t u64)
     30 {
     31 	hash = fnv1a(hash, (u64) & 0xFF);
     32 	hash = fnv1a(hash, (u64 >> 8) & 0xFF);
     33 	hash = fnv1a(hash, (u64 >> 16) & 0xFF);
     34 	hash = fnv1a(hash, (u64 >> 24) & 0xFF);
     35 	hash = fnv1a(hash, (u64 >> 32) & 0xFF);
     36 	hash = fnv1a(hash, (u64 >> 40) & 0xFF);
     37 	hash = fnv1a(hash, (u64 >> 48) & 0xFF);
     38 	hash = fnv1a(hash, (u64 >> 54) & 0xFF);
     39 	return hash;
     40 }
     41 
     42 uint32_t
     43 fnv1a_size(uint32_t hash, size_t sz)
     44 {
     45 	for (size_t i = 0; i < sizeof(sz); i++) {
     46 		hash = fnv1a(hash, sz & 0xFF);
     47 		sz >>= 8;
     48 	}
     49 	return hash;
     50 }
     51 
     52 uint32_t
     53 fnv1a_s(uint32_t hash, const char *str)
     54 {
     55 	unsigned char c;
     56 	while ((c = *str++)) {
     57 		hash = fnv1a(hash, c);
     58 	}
     59 	return hash;
     60 }
     61 
     62 void *
     63 xcalloc(size_t n, size_t s)
     64 {
     65 	void *p = calloc(n, s);
     66 	if (!p && s) {
     67 		abort();
     68 	}
     69 	return p;
     70 }
     71 
     72 void *
     73 xrealloc(void *p, size_t s)
     74 {
     75 	p = realloc(p, s);
     76 	if (!p && s) {
     77 		abort();
     78 	}
     79 	return p;
     80 }
     81 
     82 char *
     83 getpath(const struct pathspec *paths, size_t npaths) {
     84 	for (size_t i = 0; i < npaths; i++) {
     85 		const char *var = "";
     86 		if (paths[i].var) {
     87 			var = getenv(paths[i].var);
     88 		}
     89 		if (var) {
     90 			char *out = calloc(1,
     91 				strlen(var) + strlen(paths[i].path) + 1);
     92 			strcat(strcat(out, var), paths[i].path);
     93 			return out;
     94 		}
     95 	}
     96 	return NULL;
     97 }