common.cpp (2532B)
1 #include "c4/yml/common.hpp" 2 3 #ifndef RYML_NO_DEFAULT_CALLBACKS 4 # include <stdlib.h> 5 # include <stdio.h> 6 #endif // RYML_NO_DEFAULT_CALLBACKS 7 8 namespace c4 { 9 namespace yml { 10 11 C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast") 12 13 namespace { 14 Callbacks s_default_callbacks; 15 } // anon namespace 16 17 #ifndef RYML_NO_DEFAULT_CALLBACKS 18 void report_error_impl(const char* msg, size_t length, Location loc, FILE *f) 19 { 20 if(!f) 21 f = stderr; 22 if(loc) 23 { 24 if(!loc.name.empty()) 25 { 26 fwrite(loc.name.str, 1, loc.name.len, f); 27 fputc(':', f); 28 } 29 fprintf(f, "%zu:", loc.line); 30 if(loc.col) 31 fprintf(f, "%zu:", loc.col); 32 if(loc.offset) 33 fprintf(f, " (%zuB):", loc.offset); 34 } 35 fprintf(f, "%.*s\n", (int)length, msg); 36 fflush(f); 37 } 38 39 void error_impl(const char* msg, size_t length, Location loc, void * /*user_data*/) 40 { 41 report_error_impl(msg, length, loc, nullptr); 42 ::abort(); 43 } 44 45 void* allocate_impl(size_t length, void * /*hint*/, void * /*user_data*/) 46 { 47 void *mem = ::malloc(length); 48 if(mem == nullptr) 49 { 50 const char msg[] = "could not allocate memory"; 51 error_impl(msg, sizeof(msg)-1, {}, nullptr); 52 } 53 return mem; 54 } 55 56 void free_impl(void *mem, size_t /*length*/, void * /*user_data*/) 57 { 58 ::free(mem); 59 } 60 #endif // RYML_NO_DEFAULT_CALLBACKS 61 62 63 64 Callbacks::Callbacks() 65 : 66 m_user_data(nullptr), 67 #ifndef RYML_NO_DEFAULT_CALLBACKS 68 m_allocate(allocate_impl), 69 m_free(free_impl), 70 m_error(error_impl) 71 #else 72 m_allocate(nullptr), 73 m_free(nullptr), 74 m_error(nullptr) 75 #endif 76 { 77 } 78 79 Callbacks::Callbacks(void *user_data, pfn_allocate alloc_, pfn_free free_, pfn_error error_) 80 : 81 m_user_data(user_data), 82 #ifndef RYML_NO_DEFAULT_CALLBACKS 83 m_allocate(alloc_ ? alloc_ : allocate_impl), 84 m_free(free_ ? free_ : free_impl), 85 m_error(error_ ? error_ : error_impl) 86 #else 87 m_allocate(alloc_), 88 m_free(free_), 89 m_error(error_) 90 #endif 91 { 92 C4_CHECK(m_allocate); 93 C4_CHECK(m_free); 94 C4_CHECK(m_error); 95 } 96 97 98 void set_callbacks(Callbacks const& c) 99 { 100 s_default_callbacks = c; 101 } 102 103 Callbacks const& get_callbacks() 104 { 105 return s_default_callbacks; 106 } 107 108 void reset_callbacks() 109 { 110 set_callbacks(Callbacks()); 111 } 112 113 void error(const char *msg, size_t msg_len, Location loc) 114 { 115 s_default_callbacks.m_error(msg, msg_len, loc, s_default_callbacks.m_user_data); 116 } 117 118 C4_SUPPRESS_WARNING_GCC_CLANG_POP 119 120 } // namespace yml 121 } // namespace c4