argv_new.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * argv_new.c
  3. */
  4. #include "private.h"
  5. #include "lub/string.h"
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <assert.h>
  9. /*--------------------------------------------------------- */
  10. static void lub_argv_init(lub_argv_t * this, const char *line, size_t offset)
  11. {
  12. size_t len;
  13. const char *word;
  14. lub_arg_t *arg;
  15. size_t quoted;
  16. this->argv = NULL;
  17. this->argc = 0;
  18. if (!line)
  19. return;
  20. /* first of all count the words in the line */
  21. this->argc = lub_string_wordcount(line);
  22. if (0 == this->argc)
  23. return;
  24. /* allocate space to hold the vector */
  25. arg = this->argv = malloc(sizeof(lub_arg_t) * this->argc);
  26. assert(arg);
  27. /* then fill out the array with the words */
  28. for (word = lub_string_nextword(line, &len, &offset, &quoted);
  29. *word || quoted;
  30. word = lub_string_nextword(word + len, &len, &offset, &quoted)) {
  31. (*arg).arg = lub_string_ndecode(word, len);
  32. (*arg).offset = offset;
  33. (*arg).quoted = quoted ? BOOL_TRUE : BOOL_FALSE;
  34. offset += len;
  35. if (quoted) {
  36. len += quoted - 1; /* account for terminating quotation mark */
  37. offset += quoted; /* account for quotation marks */
  38. }
  39. arg++;
  40. }
  41. }
  42. /*--------------------------------------------------------- */
  43. lub_argv_t *lub_argv_new(const char *line, size_t offset)
  44. {
  45. lub_argv_t *this;
  46. this = malloc(sizeof(lub_argv_t));
  47. if (this)
  48. lub_argv_init(this, line, offset);
  49. return this;
  50. }
  51. /*--------------------------------------------------------- */
  52. void lub_argv_add(lub_argv_t * this, const char *text)
  53. {
  54. lub_arg_t * arg;
  55. if (!text)
  56. return;
  57. /* allocate space to hold the vector */
  58. arg = realloc(this->argv, sizeof(lub_arg_t) * (this->argc + 1));
  59. assert(arg);
  60. this->argv = arg;
  61. (this->argv[this->argc++]).arg = strdup(text);
  62. }
  63. /*--------------------------------------------------------- */
  64. static void lub_argv_fini(lub_argv_t * this)
  65. {
  66. unsigned i;
  67. for (i = 0; i < this->argc; i++)
  68. free(this->argv[i].arg);
  69. free(this->argv);
  70. this->argv = NULL;
  71. }
  72. /*--------------------------------------------------------- */
  73. void lub_argv_delete(lub_argv_t * this)
  74. {
  75. lub_argv_fini(this);
  76. free(this);
  77. }
  78. /*--------------------------------------------------------- */