testutil.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * cifra - embedded cryptography library
  3. * Written in 2014 by Joseph Birr-Pixton <jpixton@gmail.com>
  4. *
  5. * To the extent possible under law, the author(s) have dedicated all
  6. * copyright and related and neighboring rights to this software to the
  7. * public domain worldwide. This software is distributed without any
  8. * warranty.
  9. *
  10. * You should have received a copy of the CC0 Public Domain Dedication
  11. * along with this software. If not, see
  12. * <http://creativecommons.org/publicdomain/zero/1.0/>.
  13. */
  14. #ifndef TESTUTIL_H
  15. #define TESTUTIL_H
  16. #include <assert.h>
  17. #include <string.h>
  18. #include <stdio.h>
  19. static inline uint8_t unhex_chr(char a)
  20. {
  21. if (a >= '0' && a <= '9')
  22. return a - '0';
  23. else if (a >= 'a' && a <= 'f')
  24. return a - 'a' + 10;
  25. else if (a >= 'A' && a <= 'F')
  26. return a - 'A' + 10;
  27. return 0;
  28. }
  29. static inline size_t unhex(uint8_t *buf, size_t len, const char *str)
  30. {
  31. size_t used = 0;
  32. assert(strlen(str) % 2 == 0);
  33. assert(strlen(str) / 2 <= len);
  34. while (*str)
  35. {
  36. assert(len);
  37. *buf = unhex_chr(str[0]) << 4 | unhex_chr(str[1]);
  38. buf++;
  39. used++;
  40. str += 2;
  41. len--;
  42. }
  43. return used;
  44. }
  45. static inline void dump(const char *label, const uint8_t *buf, size_t len)
  46. {
  47. printf("%s: ", label);
  48. for (size_t i = 0; i < len; i++)
  49. printf("%02x", buf[i]);
  50. printf("\n");
  51. }
  52. #endif