expstring.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @file expstring.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. #ifndef BADVPN_MISC_EXPSTRING_H
  23. #define BADVPN_MISC_EXPSTRING_H
  24. #include <stddef.h>
  25. #include <misc/debug.h>
  26. #include <misc/exparray.h>
  27. typedef struct {
  28. struct ExpArray arr;
  29. size_t n;
  30. } ExpString;
  31. static int ExpString_Init (ExpString *c);
  32. static void ExpString_Free (ExpString *c);
  33. static int ExpString_Append (ExpString *c, const char *str);
  34. static char * ExpString_Get (ExpString *c);
  35. int ExpString_Init (ExpString *c)
  36. {
  37. if (!ExpArray_init(&c->arr, 1, 16)) {
  38. return 0;
  39. }
  40. c->n = 0;
  41. ((char *)c->arr.v)[c->n] = '\0';
  42. return 1;
  43. }
  44. void ExpString_Free (ExpString *c)
  45. {
  46. free(c->arr.v);
  47. }
  48. int ExpString_Append (ExpString *c, const char *str)
  49. {
  50. ASSERT(str)
  51. size_t l = strlen(str);
  52. if (!ExpArray_resize(&c->arr, c->n + l + 1)) {
  53. return 0;
  54. }
  55. memcpy((char *)c->arr.v + c->n, str, l);
  56. c->n += l;
  57. ((char *)c->arr.v)[c->n] = '\0';
  58. return 1;
  59. }
  60. char * ExpString_Get (ExpString *c)
  61. {
  62. return (char *)c->arr.v;
  63. }
  64. #endif