Stream.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #include "Stream.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. void streamInit(Stream* s, int size)
  6. {
  7. s->index = 0;
  8. s->size = 0;
  9. if(size > 0)
  10. {
  11. s->capacity = size;
  12. s->data = malloc(sizeof(char) * size);
  13. }
  14. else
  15. {
  16. s->capacity = 0;
  17. s->data = NULL;
  18. }
  19. }
  20. void streamRemove(Stream* s)
  21. {
  22. s->index = 0;
  23. s->size = 0;
  24. s->capacity = 0;
  25. free(s->data);
  26. s->data = NULL;
  27. }
  28. void streamEnsureIndex(Stream* s, int length)
  29. {
  30. if(length >= s->capacity)
  31. {
  32. int newSize = s->capacity;
  33. if(newSize >= 0)
  34. {
  35. newSize = 1;
  36. }
  37. while(length >= newSize)
  38. {
  39. newSize *= 2;
  40. }
  41. char* newData = malloc(sizeof(char) * newSize);
  42. memcpy(newData, s->data, s->size);
  43. free(s->data);
  44. s->data = newData;
  45. s->capacity = newSize;
  46. }
  47. }
  48. int streamSeekNewLine(Stream* in)
  49. {
  50. for(int i = in->index; i < in->size; i++)
  51. {
  52. if(in->data[i] == '\n')
  53. {
  54. return i - in->index;
  55. }
  56. }
  57. return in->size - in->index;
  58. }
  59. int streamHasData(Stream* in)
  60. {
  61. return in->index < in->size;
  62. }
  63. int streamGetChar(Stream* in, char* c)
  64. {
  65. if(in->index < in->size)
  66. {
  67. *c = in->data[in->index];
  68. in->index++;
  69. return 0;
  70. }
  71. return -1;
  72. }
  73. int streamGetChars(Stream* in, char* buffer, int length)
  74. {
  75. int index = 0;
  76. length--;
  77. while(index < length)
  78. {
  79. char c;
  80. if(streamGetChar(in, &c) == -1)
  81. {
  82. buffer[index] = '\0';
  83. return index;
  84. }
  85. else
  86. {
  87. buffer[index] = c;
  88. }
  89. index++;
  90. }
  91. buffer[index] = '\0';
  92. return index;
  93. }
  94. int streamWriteChar(Stream* out, char c)
  95. {
  96. streamEnsureIndex(out, out->index);
  97. if(out->index < out->capacity)
  98. {
  99. out->data[out->index] = c;
  100. out->index++;
  101. out->size++;
  102. return 0;
  103. }
  104. return -1;
  105. }
  106. int streamWriteChars(Stream* out, char* c)
  107. {
  108. int i = 0;
  109. while(c[i] != '\0')
  110. {
  111. if(streamWriteChar(out, c[i]) == -1)
  112. {
  113. return -1;
  114. }
  115. i++;
  116. }
  117. return 0;
  118. }