Utility.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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/Error.hpp"
  7. #include "core/utils/Logger.hpp"
  8. static Core::ExitHandler exitHandler = nullptr;
  9. static void* exitData = nullptr;
  10. void Core::exitWithHandler(const char* file, int line, int value) {
  11. if(value != 0) {
  12. printf("%sExit from %s:%d with value %d%s\n", Core::Logger::COLOR_RED,
  13. Core::Logger::getFileName(file), line, value,
  14. Core::Logger::COLOR_RESET);
  15. }
  16. if(exitHandler != nullptr) {
  17. exitHandler(value, exitData);
  18. }
  19. exit(value);
  20. }
  21. void Core::setExitHandler(ExitHandler eh, void* data) {
  22. exitHandler = eh;
  23. exitData = data;
  24. }
  25. #define CORE_TO_STRING(type, cast, format) \
  26. CError Core::toString(type t, char* buffer, size_t size) { \
  27. int w = snprintf(buffer, size, format, static_cast<cast>(t)); \
  28. if(w < 0) { \
  29. return ErrorCode::ERROR; \
  30. } \
  31. return static_cast<size_t>(w) >= size ? ErrorCode::CAPACITY_REACHED \
  32. : ErrorCode::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. void Core::print(int c) {
  46. if(putchar(c) < 0) {
  47. CORE_EXIT(static_cast<int>(ErrorCode::BLOCKED_STDOUT));
  48. }
  49. }
  50. void Core::print(const char* s) {
  51. if(fputs(s, stdout) < 0) {
  52. CORE_EXIT(static_cast<int>(ErrorCode::BLOCKED_STDOUT));
  53. }
  54. }
  55. void Core::printLine(const char* s) {
  56. if(puts(s) < 0) {
  57. CORE_EXIT(static_cast<int>(ErrorCode::BLOCKED_STDOUT));
  58. }
  59. }
  60. Core::Error Core::reallocate(char*& p, size_t n) {
  61. if(n <= 0) {
  62. free(p);
  63. p = nullptr;
  64. return ErrorCode::NONE;
  65. }
  66. char* newP = static_cast<char*>(realloc(p, n));
  67. if(newP == nullptr || CORE_REALLOC_FAIL(newP)) {
  68. return ErrorCode::OUT_OF_MEMORY;
  69. }
  70. p = newP;
  71. return ErrorCode::NONE;
  72. }