argv_new.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. bool_t quoted;
  16. if (!line) {
  17. this->argv = NULL;
  18. this->argc = 0;
  19. return;
  20. }
  21. /* first of all count the words in the line */
  22. this->argc = lub_argv_wordcount(line);
  23. /* allocate space to hold the vector */
  24. arg = this->argv = malloc(sizeof(lub_arg_t) * this->argc);
  25. assert(arg);
  26. /* then fill out the array with the words */
  27. for (word = lub_argv_nextword(line, &len, &offset, &quoted);
  28. *word;
  29. word = lub_argv_nextword(word + len, &len, &offset, &quoted)) {
  30. (*arg).arg = lub_string_ndecode(word, len);
  31. (*arg).offset = offset;
  32. (*arg).quoted = quoted;
  33. offset += len;
  34. if (quoted) {
  35. len += 1; /* account for terminating quotation mark */
  36. offset += 2; /* account for quotation marks */
  37. }
  38. arg++;
  39. }
  40. }
  41. /*--------------------------------------------------------- */
  42. lub_argv_t *lub_argv_new(const char *line, size_t offset)
  43. {
  44. lub_argv_t *this;
  45. this = malloc(sizeof(lub_argv_t));
  46. if (this)
  47. lub_argv_init(this, line, offset);
  48. return this;
  49. }
  50. /*--------------------------------------------------------- */
  51. void lub_argv_add(lub_argv_t * this, const char *text)
  52. {
  53. lub_arg_t * arg;
  54. if (!text)
  55. return;
  56. /* allocate space to hold the vector */
  57. arg = realloc(this->argv, sizeof(lub_arg_t) * (this->argc + 1));
  58. assert(arg);
  59. this->argv = arg;
  60. (this->argv[this->argc++]).arg = strdup(text);
  61. }
  62. /*--------------------------------------------------------- */
  63. static void lub_argv_fini(lub_argv_t * this)
  64. {
  65. unsigned i;
  66. for (i = 0; i < this->argc; i++)
  67. free(this->argv[i].arg);
  68. free(this->argv);
  69. this->argv = NULL;
  70. }
  71. /*--------------------------------------------------------- */
  72. void lub_argv_delete(lub_argv_t * this)
  73. {
  74. lub_argv_fini(this);
  75. free(this);
  76. }
  77. /*--------------------------------------------------------- */