argv_new.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. char *tmp = lub_string_dupn(word, len);
  31. (*arg).arg = lub_string_decode(tmp);
  32. lub_string_free(tmp);
  33. (*arg).offset = offset;
  34. (*arg).quoted = quoted;
  35. offset += len;
  36. if (quoted) {
  37. len += 1; /* account for terminating quotation mark */
  38. offset += 2; /* account for quotation marks */
  39. }
  40. arg++;
  41. }
  42. }
  43. /*--------------------------------------------------------- */
  44. lub_argv_t *lub_argv_new(const char *line, size_t offset)
  45. {
  46. lub_argv_t *this;
  47. this = malloc(sizeof(lub_argv_t));
  48. if (this)
  49. lub_argv_init(this, line, offset);
  50. return this;
  51. }
  52. /*--------------------------------------------------------- */
  53. void lub_argv_add(lub_argv_t * this, const char *text)
  54. {
  55. lub_arg_t * arg;
  56. if (!text)
  57. return;
  58. /* allocate space to hold the vector */
  59. arg = realloc(this->argv, sizeof(lub_arg_t) * (this->argc + 1));
  60. assert(arg);
  61. this->argv = arg;
  62. (this->argv[this->argc++]).arg = lub_string_dup(text);
  63. }
  64. /*--------------------------------------------------------- */