]> git.draconx.ca Git - upkg.git/blobdiff - test/common.c
engine: Add a unit test for the PCX run-length encoder.
[upkg.git] / test / common.c
diff --git a/test/common.c b/test/common.c
new file mode 100644 (file)
index 0000000..c998624
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Helper functions for test programs.
+ * Copyright © 2012 Nick Bowler
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+#include <stdlib.h>
+#include <ctype.h>
+
+#include "common.h"
+
+/*
+ * Decode a hexadecimal string into a sequence of bytes.  If there are an
+ * odd number of nibbles, treat the first character as the least significant
+ * nibble of the first byte.  The result is written to the buffer specified by
+ * buf.  At most n bytes are written to the buffer.
+ *
+ * Returns the number of bytes that would be written provided that n was large
+ * enough, or (size_t)-1 if the input is not valid.
+ */
+size_t test_decode_hex(const char *hex, unsigned char *buf, size_t n)
+{
+       size_t len, count = 0;
+       char tmp[] = "00";
+
+       for (len = 0; hex[len]; len++) {
+               if (!isxdigit(hex[len]))
+                       return -1;
+       }
+
+       if (!len)
+               return 0;
+
+       switch (len % 2) {
+               while (len > 0) {
+                       case 0: tmp[0] = *hex++; len--;
+                       case 1: tmp[1] = *hex++; len--;
+
+                       if (count < n)
+                               buf[count] = strtoul(tmp, NULL, 16);
+                       count++;
+               }
+       }
+
+       return count;
+}