Stream.c 2.2 KB

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