Stream.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #include <cstring>
  2. #include <netinet/in.h>
  3. #include "common/stream/Stream.h"
  4. Stream::Stream() : error(false), writeIndex(0), readIndex(0)
  5. {
  6. }
  7. Stream::Stream(size_t capacity) : data(capacity), error(false), writeIndex(0), readIndex(0)
  8. {
  9. }
  10. bool Stream::hasData() const
  11. {
  12. return readIndex < writeIndex;
  13. }
  14. bool Stream::hasError() const
  15. {
  16. return error;
  17. }
  18. void Stream::clearError()
  19. {
  20. error = false;
  21. }
  22. void Stream::write(const void* writeData, size_t length)
  23. {
  24. if(data.write(writeIndex, writeData, length))
  25. {
  26. writeIndex += length;
  27. }
  28. else
  29. {
  30. error = true;
  31. }
  32. }
  33. void Stream::write(const char* writeData)
  34. {
  35. write(writeData, strlen(writeData));
  36. }
  37. void Stream::writeUnsignedChar(u8 uc)
  38. {
  39. write(&uc, sizeof(u8));
  40. }
  41. void Stream::writeUnsignedShort(u16 us)
  42. {
  43. us = htons(us);
  44. write(&us, sizeof(u16));
  45. }
  46. void Stream::writeUnsignedInt(u32 ui)
  47. {
  48. ui = htonl(ui);
  49. write(&ui, sizeof(u32));
  50. }
  51. void Stream::read(void* buffer, size_t length)
  52. {
  53. if(readIndex + length <= writeIndex && data.read(readIndex, buffer, length))
  54. {
  55. readIndex += length;
  56. }
  57. else
  58. {
  59. error = true;
  60. }
  61. }
  62. u8 Stream::readUnsignedChar()
  63. {
  64. u8 uc;
  65. read(&uc, sizeof(u8));
  66. return uc;
  67. }
  68. u16 Stream::readUnsignedShort()
  69. {
  70. u16 us;
  71. read(&us, sizeof(u16));
  72. us = ntohs(us);
  73. return us;
  74. }
  75. u32 Stream::readUnsignedInt()
  76. {
  77. u32 ui;
  78. read(&ui, sizeof(u32));
  79. ui = ntohl(ui);
  80. return ui;
  81. }
  82. bool Stream::readSocket(int socket)
  83. {
  84. readIndex = 0;
  85. return data.readSocket(socket, writeIndex);
  86. }
  87. void Stream::sendToSocket(int socket) const
  88. {
  89. data.sendToSocket(socket, writeIndex);
  90. }