IRCMessage.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. EQ2Emulator is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include <assert.h>
  17. #include <stdarg.h>
  18. #include <stdio.h>
  19. #include "../../common/types.h"
  20. #include "IRCMessage.h"
  21. IRCMessage::IRCMessage(const char *message, ...) {
  22. int n, size = 512;
  23. va_list ap;
  24. len = 0;
  25. serialized = false;
  26. while (true) {
  27. //allocate our buffer
  28. this->message = new char[size];
  29. //print the format into the buffer
  30. va_start(ap, message);
  31. n = vsnprintf(this->message, size, message, ap);
  32. va_end(ap);
  33. //did we write what we needed to?
  34. if (n > -1 && n < size)
  35. break;
  36. #ifdef _WIN32
  37. size *= 2; //double the buffer
  38. #else
  39. if (n > -1)
  40. size = n + 1; //we know exactly how many bytes to write
  41. else
  42. size *= 2; //double the buffer
  43. #endif
  44. safe_delete_array(this->message);
  45. }
  46. }
  47. IRCMessage::~IRCMessage() {
  48. if (message != NULL)
  49. safe_delete_array(message);
  50. }
  51. const char * IRCMessage::Serialize() {
  52. char *buf;
  53. if (message == NULL || serialized)
  54. return message;
  55. //allocate enough room for the /r/n, and of course the null
  56. len = strlen(message) + 3;
  57. buf = new char[len];
  58. snprintf(buf, len, "%s\r\n", message);
  59. //now copy back into our true buffer
  60. safe_delete_array(message);
  61. message = new char[len];
  62. strncpy(message, buf, len);
  63. //and finally free our temporary buffer
  64. safe_delete_array(buf);
  65. //we don't want to do this process again if for some reason Serialize() is called again
  66. serialized = true;
  67. //we don't want to include the trailing null in the length
  68. len--;
  69. return message;
  70. }