nostrdb

an unfairly fast embedded nostr database backed by lmdb
git clone git://jb55.com/nostrdb
Log | Files | Refs | Submodules | README | LICENSE

hex.h (1297B)


      1 
      2 #ifndef HEX_H
      3 #define HEX_H
      4 
      5 #include <stdlib.h>
      6 
      7 static const char hex_table[256] = {
      8     ['0'] = 0, ['1'] = 1, ['2'] = 2, ['3'] = 3,
      9     ['4'] = 4, ['5'] = 5, ['6'] = 6, ['7'] = 7,
     10     ['8'] = 8, ['9'] = 9, ['a'] = 10, ['b'] = 11,
     11     ['c'] = 12, ['d'] = 13, ['e'] = 14, ['f'] = 15,
     12     ['A'] = 10, ['B'] = 11, ['C'] = 12, ['D'] = 13,
     13     ['E'] = 14, ['F'] = 15
     14 };
     15 
     16 static inline int char_to_hex(unsigned char *val, unsigned char c)
     17 {
     18 	if (hex_table[c] || c == '0') {
     19 		*val = hex_table[c];
     20 		return 1;
     21 	}
     22 	return 0;
     23 }
     24 
     25 static inline int hex_decode(const char *str, size_t slen, void *buf, size_t bufsize)
     26 {
     27 	unsigned char v1, v2;
     28 	unsigned char *p = buf;
     29 
     30 	while (slen > 1) {
     31 		if (!char_to_hex(&v1, str[0]) || !char_to_hex(&v2, str[1]))
     32 			return 0;
     33 		if (!bufsize)
     34 			return 0;
     35 		*(p++) = (v1 << 4) | v2;
     36 		str += 2;
     37 		slen -= 2;
     38 		bufsize--;
     39 	}
     40 	return slen == 0 && bufsize == 0;
     41 }
     42 
     43 
     44 static inline char hexchar(unsigned int val)
     45 {
     46 	if (val < 10)
     47 		return '0' + val;
     48 	if (val < 16)
     49 		return 'a' + val - 10;
     50 	abort();
     51 }
     52 
     53 static int hex_encode(const void *buf, size_t bufsize, char *dest)
     54 {
     55 	size_t i;
     56 
     57 	for (i = 0; i < bufsize; i++) {
     58 		unsigned int c = ((const unsigned char *)buf)[i];
     59 		*(dest++) = hexchar(c >> 4);
     60 		*(dest++) = hexchar(c & 0xF);
     61 	}
     62 	*dest = '\0';
     63 
     64 	return 1;
     65 }
     66 
     67 
     68 #endif