cmdline.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /**
  2. * @file cmdline.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * Command line construction functions.
  25. */
  26. #ifndef BADVPN_MISC_CMDLINE_H
  27. #define BADVPN_MISC_CMDLINE_H
  28. #include <stddef.h>
  29. #include <misc/debug.h>
  30. #include <misc/exparray.h>
  31. typedef struct {
  32. struct ExpArray arr;
  33. size_t n;
  34. } CmdLine;
  35. static int CmdLine_Init (CmdLine *c);
  36. static void CmdLine_Free (CmdLine *c);
  37. static int CmdLine_Append (CmdLine *c, const char *str);
  38. static int CmdLine_Finish (CmdLine *c);
  39. static char ** CmdLine_Get (CmdLine *c);
  40. static int _CmdLine_finished (CmdLine *c)
  41. {
  42. return (c->n > 0 && ((char **)c->arr.v)[c->n - 1] == NULL);
  43. }
  44. int CmdLine_Init (CmdLine *c)
  45. {
  46. if (!ExpArray_init(&c->arr, sizeof(char *), 16)) {
  47. return 0;
  48. }
  49. c->n = 0;
  50. return 1;
  51. }
  52. void CmdLine_Free (CmdLine *c)
  53. {
  54. for (size_t i = 0; i < c->n; i++) {
  55. free(((char **)c->arr.v)[i]);
  56. }
  57. free(c->arr.v);
  58. }
  59. int CmdLine_Append (CmdLine *c, const char *str)
  60. {
  61. ASSERT(str)
  62. ASSERT(!_CmdLine_finished(c))
  63. if (!ExpArray_resize(&c->arr, c->n + 1)) {
  64. return 0;
  65. }
  66. if (!(((char **)c->arr.v)[c->n] = strdup(str))) {
  67. return 0;
  68. }
  69. c->n++;
  70. return 1;
  71. }
  72. int CmdLine_Finish (CmdLine *c)
  73. {
  74. ASSERT(!_CmdLine_finished(c))
  75. if (!ExpArray_resize(&c->arr, c->n + 1)) {
  76. return 0;
  77. }
  78. ((char **)c->arr.v)[c->n] = NULL;
  79. c->n++;
  80. return 1;
  81. }
  82. char ** CmdLine_Get (CmdLine *c)
  83. {
  84. ASSERT(_CmdLine_finished(c))
  85. return (char **)c->arr.v;
  86. }
  87. #endif