strfbits.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*====================================================================*
  2. *
  3. * size_t strfbits (char buffer [], size_t length, char const * operands [], char const * operator, unsigned flagword);
  4. *
  5. * format.h
  6. *
  7. * format buffer with an enumerated list of the bits in a flagword;
  8. * each flagword bit position corresponds to a string in operands[]
  9. * and operator is the string separating formatted operands;
  10. *
  11. * enumeration continues until all bits are enumerated or operands
  12. * are exhausted or the buffer fills;
  13. *
  14. * for example, the following formats buffer with the literal string
  15. * "one, three, five, six" since those bits are set;
  16. *
  17. * char buffer[100];
  18. * char const operator = ", ";
  19. * char const *operands[] =
  20. * {
  21. * "zero",
  22. * "one",
  23. * "two",
  24. * "three",
  25. * "four",
  26. * "five",
  27. * "six",
  28. * "seven",
  29. * "eight",
  30. * "nine",
  31. * "ten",
  32. * (char *)(0)
  33. * };
  34. * flag_t flags = 0x006C;
  35. *
  36. * strfbits (buffer, sizeof(buffer), operands, operator, flags);
  37. *
  38. * we decrement length before starting to reserve room for the NUL
  39. * terminator; not room ... no write; we then add length to buffer
  40. * before to compute the terminator address then subtract it after
  41. * to compute the buffer start; this minimizes indexing and offset
  42. * calculations within the loop;
  43. *
  44. * Motley Tools by Charles Maier;
  45. * Copyright (c) 2001-2006 by Charles Maier Associates;
  46. * Licensed under the Internet Software Consortium License;
  47. *
  48. *--------------------------------------------------------------------*/
  49. #ifndef STRFBITS_SOURCE
  50. #define STRFBITS_SOURCE
  51. #include <unistd.h>
  52. #include "../tools/memory.h"
  53. #include "../tools/flags.h"
  54. size_t strfbits (char buffer [], size_t length, char const * operands [], char const * operator, unsigned flagword)
  55. {
  56. char * string = (char *)(buffer);
  57. char const *separator = "";
  58. if (length--)
  59. {
  60. buffer += length;
  61. while ((*operands) && (flagword))
  62. {
  63. if (flagword & 1)
  64. {
  65. char const *symbol;
  66. for (symbol = separator; (*symbol) && (string < buffer); symbol++)
  67. {
  68. *string++ = *symbol;
  69. }
  70. for (symbol = *operands; (*symbol) && (string < buffer); symbol++)
  71. {
  72. *string++ = *symbol;
  73. }
  74. separator = operator;
  75. }
  76. flagword >>= 1;
  77. operands++;
  78. }
  79. *string = (char) (0);
  80. buffer -= length;
  81. }
  82. return (string - (char *)(buffer));
  83. }
  84. #endif