Utility.cpp 2.8 KB

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