dataspec.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*====================================================================*
  2. *
  3. * size_t dataspec (char const * string, void * memory, size_t extent);
  4. *
  5. * memory.h
  6. *
  7. * encode a memory region with a variable-length hexadecimal string;
  8. * return the number of bytes encoded or terminate the program on
  9. * error;
  10. *
  11. * the number of octets in string must equal the memory extent or
  12. * an error will occur; octets may be seperated by semi-colons;
  13. * empty octets are illegal;
  14. *
  15. * Motley Tools by Charles Maier;
  16. * Copyright (c) 2001-2006 by Charles Maier Associates;
  17. * Licensed under the Internet Software Consortium License;
  18. *
  19. *--------------------------------------------------------------------*/
  20. #ifndef DATASPEC_SOURCE
  21. #define DATASPEC_SOURCE
  22. #include <ctype.h>
  23. #include <errno.h>
  24. #include "../tools/memory.h"
  25. #include "../tools/number.h"
  26. #include "../tools/error.h"
  27. size_t dataspec (char const * string, void * memory, size_t extent)
  28. {
  29. char const * number = string;
  30. byte * origin = (byte *)(memory);
  31. byte * offset = (byte *)(memory);
  32. if (!number)
  33. {
  34. error (1, EFAULT, "dataspec");
  35. }
  36. #ifdef WIN32
  37. while (isspace (*number))
  38. {
  39. number++;
  40. }
  41. #endif
  42. while ((*number) && (extent))
  43. {
  44. unsigned digit = 0;
  45. #ifdef WIN32
  46. if (isspace (*number))
  47. {
  48. break;
  49. }
  50. #endif
  51. if ((offset > origin) && (*number == HEX_EXTENDER))
  52. {
  53. number++;
  54. }
  55. if ((digit = todigit (*number++)) >= RADIX_HEX)
  56. {
  57. error (1, EINVAL, "You said '%s' but I want a hex digit", string);
  58. }
  59. *offset = digit << 4;
  60. if (!*number)
  61. {
  62. error (1, EINVAL, "You said '%s' but I want another hex digit", string);
  63. }
  64. if ((digit = todigit (*number++)) >= 0x10)
  65. {
  66. error (1, EINVAL, "You said '%s' but I want valid hex data", string);
  67. }
  68. *offset |= digit;
  69. offset++;
  70. extent--;
  71. }
  72. #ifdef WIN32
  73. while (isspace (*number))
  74. {
  75. number++;
  76. }
  77. #endif
  78. if (*number && !extent)
  79. {
  80. error (1, EINVAL, "'%s' exceeds %d bytes", string, (unsigned)(offset - origin - extent));
  81. }
  82. if (*number)
  83. {
  84. error (1, EINVAL, "String '%s' contains trash", string);
  85. }
  86. return (offset - origin);
  87. }
  88. #endif