Utility.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "core/utils/Utility.hpp"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. static Core::ExitHandler exitHandler = nullptr;
  6. static void* exitData = nullptr;
  7. void Core::exitWithHandler(const char* file, int line, int value) {
  8. if(value != 0) {
  9. printf("\33[1;31mExit from %s:%d with value %d\33[39;49m\n", file, line,
  10. value);
  11. }
  12. if(exitHandler != nullptr) {
  13. exitHandler(value, exitData);
  14. }
  15. exit(value);
  16. }
  17. void Core::setExitHandler(ExitHandler eh, void* data) {
  18. exitHandler = eh;
  19. exitData = data;
  20. }
  21. #define CORE_TO_STRING(type, cast, format) \
  22. check_return Core::Error Core::toString(type t, char* buffer, int size) { \
  23. if(size < 0) { \
  24. return Error::NEGATIVE_ARGUMENT; \
  25. } \
  26. return snprintf(buffer, static_cast<unsigned int>(size), format, \
  27. static_cast<cast>(t)) >= size \
  28. ? Error::CAPACITY_REACHED \
  29. : Error::NONE; \
  30. }
  31. CORE_TO_STRING(signed short, signed short, "%hd")
  32. CORE_TO_STRING(unsigned short, unsigned short, "%hu")
  33. CORE_TO_STRING(signed int, signed int, "%d")
  34. CORE_TO_STRING(unsigned int, unsigned int, "%u")
  35. CORE_TO_STRING(signed long, signed long, "%ld")
  36. CORE_TO_STRING(unsigned long, unsigned long, "%lu")
  37. CORE_TO_STRING(signed long long, signed long long, "%lld")
  38. CORE_TO_STRING(unsigned long long, unsigned long long, "%llu")
  39. CORE_TO_STRING(float, double, "%.2f")
  40. CORE_TO_STRING(double, double, "%.2lf")
  41. CORE_TO_STRING(long double, long double, "%.2Lf")
  42. Core::Error Core::putChar(int c) {
  43. return putchar(c) == EOF ? Error::BLOCKED_STDOUT : Error::NONE;
  44. }
  45. void Core::memorySet(void* p, int c, int n) {
  46. if(n <= 0) {
  47. return;
  48. }
  49. memset(p, c, static_cast<unsigned int>(n));
  50. }
  51. void Core::memoryCopy(void* dest, const void* src, int n) {
  52. if(n <= 0) {
  53. return;
  54. }
  55. memcpy(dest, src, static_cast<unsigned int>(n));
  56. }
  57. bool Core::memoryCompare(const void* a, const void* b, int n) {
  58. return n <= 0 ? true : memcmp(a, b, static_cast<unsigned int>(n)) == 0;
  59. }
  60. Core::Error Core::reallocate(char*& p, int n) {
  61. if(n <= 0) {
  62. free(p);
  63. p = nullptr;
  64. return Error::NONE;
  65. }
  66. char* newP = static_cast<char*>(realloc(p, static_cast<unsigned int>(n)));
  67. if(newP == nullptr) {
  68. return Error::OUT_OF_MEMORY;
  69. }
  70. p = newP;
  71. return Error::NONE;
  72. }
  73. void Core::free(void* p) {
  74. ::free(p);
  75. }