Utility.cpp 2.8 KB

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