Stream.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. Stream::Stream(size_t capacity) : data(capacity), error(false), writeIndex(0), readIndex(0) {
  7. }
  8. bool Stream::hasData() const {
  9. return readIndex < writeIndex;
  10. }
  11. bool Stream::hasError() const {
  12. return error;
  13. }
  14. void Stream::clearError() {
  15. error = false;
  16. }
  17. void Stream::write(const void* writeData, size_t length) {
  18. if(data.write(writeIndex, writeData, length)) {
  19. writeIndex += length;
  20. } else {
  21. error = true;
  22. }
  23. }
  24. void Stream::write(const char* writeData) {
  25. write(writeData, strlen(writeData));
  26. }
  27. void Stream::writeUnsignedChar(u8 uc) {
  28. write(&uc, sizeof (u8));
  29. }
  30. void Stream::writeUnsignedShort(u16 us) {
  31. us = htons(us);
  32. write(&us, sizeof (u16));
  33. }
  34. void Stream::writeUnsignedInt(u32 ui) {
  35. ui = htonl(ui);
  36. write(&ui, sizeof (u32));
  37. }
  38. void Stream::read(void* buffer, size_t length) {
  39. if(readIndex + length <= writeIndex && data.read(readIndex, buffer, length)) {
  40. readIndex += length;
  41. } else {
  42. error = true;
  43. }
  44. }
  45. u8 Stream::readUnsignedChar() {
  46. u8 uc;
  47. read(&uc, sizeof (u8));
  48. return uc;
  49. }
  50. u16 Stream::readUnsignedShort() {
  51. u16 us;
  52. read(&us, sizeof (u16));
  53. us = ntohs(us);
  54. return us;
  55. }
  56. u32 Stream::readUnsignedInt() {
  57. u32 ui;
  58. read(&ui, sizeof (u32));
  59. ui = ntohl(ui);
  60. return ui;
  61. }
  62. bool Stream::readSocket(int socket) {
  63. readIndex = 0;
  64. return data.readSocket(socket, writeIndex);
  65. }
  66. void Stream::sendToSocket(int socket) const {
  67. data.sendToSocket(socket, writeIndex);
  68. }