NetworkMessage.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* Copyright The kNet Project.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License. */
  11. /** @file NetworkMessage.cpp
  12. @brief Represents a serializable network message. */
  13. #include <string.h>
  14. #include "kNet/DebugMemoryLeakCheck.h"
  15. #include "kNet/NetworkMessage.h"
  16. namespace kNet
  17. {
  18. NetworkMessage::NetworkMessage()
  19. :data(0),
  20. priority(0),
  21. id(0),
  22. contentID(0),
  23. reliable(true),
  24. inOrder(true),
  25. obsolete(false),
  26. receivedPacketID(0),
  27. messageNumber(0),
  28. reliableMessageNumber(0),
  29. sendCount(0),
  30. fragmentIndex(0),
  31. dataCapacity(0),
  32. dataSize(0),
  33. transfer(0)
  34. {
  35. }
  36. NetworkMessage::NetworkMessage(const NetworkMessage &rhs)
  37. {
  38. *this = rhs;
  39. }
  40. NetworkMessage &NetworkMessage::operator=(const NetworkMessage &rhs)
  41. {
  42. if (this == &rhs)
  43. return *this;
  44. Resize(rhs.Size());
  45. memcpy(data, rhs.data, rhs.Size());
  46. priority = rhs.priority;
  47. id = rhs.id;
  48. contentID = rhs.contentID;
  49. reliable = rhs.reliable;
  50. inOrder = rhs.inOrder;
  51. obsolete = rhs.obsolete;
  52. // We could also copy the remaining fields messageNumber, reliableMessageNumber, sendCount and fragmentIndex,
  53. // but those don't have a specified meaning at the moment the message is being crafted, so don't.
  54. // Once the message has been queued for sending, deep copies of it will not be performed.
  55. return *this;
  56. }
  57. NetworkMessage::~NetworkMessage()
  58. {
  59. delete[] data;
  60. }
  61. void NetworkMessage::Resize(size_t newBytes, bool discard)
  62. {
  63. // Remember how much data is actually being used.
  64. dataSize = newBytes;
  65. if (newBytes <= dataCapacity)
  66. return; // No need to reallocate, we can fit the requested amount of bytes.
  67. char *newData = new char[newBytes];
  68. if (!discard)
  69. memcpy(newData, data, dataCapacity);
  70. delete[] data;
  71. data = newData;
  72. dataCapacity = newBytes;
  73. }
  74. } // ~kNet