ByteArray.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * This is the source code of tgnet library v. 1.1
  3. * It is licensed under GNU GPL v. 2 or later.
  4. * You should have received a copy of the license in this archive (see LICENSE).
  5. *
  6. * Copyright Nikolai Kudashov, 2015-2018.
  7. */
  8. #include <stdlib.h>
  9. #include <memory.h>
  10. #include "ByteArray.h"
  11. #include "FileLog.h"
  12. ByteArray::ByteArray() {
  13. bytes = nullptr;
  14. length = 0;
  15. }
  16. ByteArray::ByteArray(uint32_t len) {
  17. bytes = new uint8_t[len];
  18. if (bytes == nullptr) {
  19. if (LOGS_ENABLED) DEBUG_E("unable to allocate byte buffer %u", len);
  20. exit(1);
  21. }
  22. length = len;
  23. }
  24. ByteArray::ByteArray(ByteArray *byteArray) {
  25. bytes = new uint8_t[byteArray->length];
  26. if (bytes == nullptr) {
  27. if (LOGS_ENABLED) DEBUG_E("unable to allocate byte buffer %u", byteArray->length);
  28. exit(1);
  29. }
  30. length = byteArray->length;
  31. memcpy(bytes, byteArray->bytes, length);
  32. }
  33. ByteArray::ByteArray(uint8_t *buffer, uint32_t len) {
  34. bytes = new uint8_t[len];
  35. if (bytes == nullptr) {
  36. if (LOGS_ENABLED) DEBUG_E("unable to allocate byte buffer %u", len);
  37. exit(1);
  38. }
  39. length = len;
  40. memcpy(bytes, buffer, length);
  41. }
  42. ByteArray::~ByteArray() {
  43. if (bytes != nullptr) {
  44. delete[] bytes;
  45. bytes = nullptr;
  46. }
  47. }
  48. void ByteArray::alloc(uint32_t len) {
  49. if (bytes != nullptr) {
  50. delete[] bytes;
  51. bytes = nullptr;
  52. }
  53. bytes = new uint8_t[len];
  54. if (bytes == nullptr) {
  55. if (LOGS_ENABLED) DEBUG_E("unable to allocate byte buffer %u", len);
  56. exit(1);
  57. }
  58. length = len;
  59. }
  60. bool ByteArray::isEqualTo(ByteArray *byteArray) {
  61. return byteArray->length == length && !memcmp(byteArray->bytes, bytes, length);
  62. }