expstring.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. #include <misc/bsize.h>
  28. typedef struct {
  29. struct ExpArray arr;
  30. size_t n;
  31. } ExpString;
  32. static int ExpString_Init (ExpString *c);
  33. static void ExpString_Free (ExpString *c);
  34. static int ExpString_Append (ExpString *c, const char *str);
  35. static int ExpString_AppendChar (ExpString *c, char ch);
  36. static char * ExpString_Get (ExpString *c);
  37. int ExpString_Init (ExpString *c)
  38. {
  39. if (!ExpArray_init(&c->arr, 1, 16)) {
  40. return 0;
  41. }
  42. c->n = 0;
  43. ((char *)c->arr.v)[c->n] = '\0';
  44. return 1;
  45. }
  46. void ExpString_Free (ExpString *c)
  47. {
  48. free(c->arr.v);
  49. }
  50. int ExpString_Append (ExpString *c, const char *str)
  51. {
  52. ASSERT(str)
  53. size_t l = strlen(str);
  54. bsize_t newsize = bsize_add(bsize_fromsize(c->n), bsize_add(bsize_fromsize(l), bsize_fromint(1)));
  55. if (newsize.is_overflow || !ExpArray_resize(&c->arr, newsize.value)) {
  56. return 0;
  57. }
  58. memcpy((char *)c->arr.v + c->n, str, l);
  59. c->n += l;
  60. ((char *)c->arr.v)[c->n] = '\0';
  61. return 1;
  62. }
  63. int ExpString_AppendChar (ExpString *c, char ch)
  64. {
  65. ASSERT(ch != '\0')
  66. bszie_t newsize = bsize_add(bsize_fromsize(c->n, bsize_fromint(2)));
  67. if (newsize.is_overflow || !ExpArray_resize(&c->arr, newsize.value)) {
  68. return 0;
  69. }
  70. ((char *)c->arr.v)[c->n] = ch;
  71. c->n++;
  72. ((char *)c->arr.v)[c->n] = '\0';
  73. return 1;
  74. }
  75. char * ExpString_Get (ExpString *c)
  76. {
  77. return (char *)c->arr.v;
  78. }
  79. #endif