do the output buffering ourselves; this improves performance a lot
[cwebfiles.git] / hex.c
1 #include "cwebfiles.h"
2
3 // these routines don't respect nullbytes!
4
5 // we use fast hex. start from 'a'. no checks performed (apart from length validity).
6 // out must be half the size of in
7 void unhex(unsigned char *out, char *in, size_t in_len) {
8   in_len = in_len & ~1; // input length mod 2 must be 0 - mask out the last bit
9   char *in_end = in + in_len;
10   while (in != in_end) {
11     unsigned char in1 = *(in++), in2 = *(in++);
12     *(out++) = (in1 - 'a') << 4 | (in2 - 'a');
13   }
14 }
15
16 // out must be twice the size of in
17 void hex(char *out, unsigned char *in, size_t in_len) {
18   unsigned char *in_end = in+in_len;
19   while (in != in_end) {
20     *(out++) = (*in >> 4) + 'a';
21     *(out++) = (*in & 0xf) + 'a';
22     in++;
23   }
24 }
25
26 bool checkhex(char *p, size_t l) {
27   if ((l&1) == 1) return false;
28   char *e = p+l;
29   while (p<e) {
30     if (*p < 'a') return false;
31     if (*p >= 'a'+16) return false;
32     p++;
33   }
34   return true;
35 }