X-Git-Url: http://git.draconx.ca/gitweb/upkg.git/blobdiff_plain/94cc6656cd266c2f0d8eb5bc1201fa091744c46c..ca9488ce89bd4895db0341db393ec03696b4ebd3:/test/common.c?ds=sidebyside diff --git a/test/common.c b/test/common.c new file mode 100644 index 0000000..c998624 --- /dev/null +++ b/test/common.c @@ -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 . + */ +#include +#include + +#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; +}