]> git.draconx.ca Git - upkg.git/blob - test/common.c
engine: Add a unit test for the PCX run-length encoder.
[upkg.git] / test / common.c
1 /*
2  * Helper functions for test programs.
3  * Copyright © 2012 Nick Bowler
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 #include <stdlib.h>
19 #include <ctype.h>
20
21 #include "common.h"
22
23 /*
24  * Decode a hexadecimal string into a sequence of bytes.  If there are an
25  * odd number of nibbles, treat the first character as the least significant
26  * nibble of the first byte.  The result is written to the buffer specified by
27  * buf.  At most n bytes are written to the buffer.
28  *
29  * Returns the number of bytes that would be written provided that n was large
30  * enough, or (size_t)-1 if the input is not valid.
31  */
32 size_t test_decode_hex(const char *hex, unsigned char *buf, size_t n)
33 {
34         size_t len, count = 0;
35         char tmp[] = "00";
36
37         for (len = 0; hex[len]; len++) {
38                 if (!isxdigit(hex[len]))
39                         return -1;
40         }
41
42         if (!len)
43                 return 0;
44
45         switch (len % 2) {
46                 while (len > 0) {
47                         case 0: tmp[0] = *hex++; len--;
48                         case 1: tmp[1] = *hex++; len--;
49
50                         if (count < n)
51                                 buf[count] = strtoul(tmp, NULL, 16);
52                         count++;
53                 }
54         }
55
56         return count;
57 }