Path: blob/master/dep/rapidyaml/src/c4/yml/common.cpp
4262 views
#include "c4/yml/common.hpp"12#ifndef RYML_NO_DEFAULT_CALLBACKS3# include <stdlib.h>4# include <stdio.h>5#endif // RYML_NO_DEFAULT_CALLBACKS67namespace c4 {8namespace yml {910C4_SUPPRESS_WARNING_GCC_CLANG_WITH_PUSH("-Wold-style-cast")1112namespace {13Callbacks s_default_callbacks;14} // anon namespace1516#ifndef RYML_NO_DEFAULT_CALLBACKS17void report_error_impl(const char* msg, size_t length, Location loc, FILE *f)18{19if(!f)20f = stderr;21if(loc)22{23if(!loc.name.empty())24{25fwrite(loc.name.str, 1, loc.name.len, f);26fputc(':', f);27}28fprintf(f, "%zu:", loc.line);29if(loc.col)30fprintf(f, "%zu:", loc.col);31if(loc.offset)32fprintf(f, " (%zuB):", loc.offset);33}34fprintf(f, "%.*s\n", (int)length, msg);35fflush(f);36}3738void error_impl(const char* msg, size_t length, Location loc, void * /*user_data*/)39{40report_error_impl(msg, length, loc, nullptr);41::abort();42}4344void* allocate_impl(size_t length, void * /*hint*/, void * /*user_data*/)45{46void *mem = ::malloc(length);47if(mem == nullptr)48{49const char msg[] = "could not allocate memory";50error_impl(msg, sizeof(msg)-1, {}, nullptr);51}52return mem;53}5455void free_impl(void *mem, size_t /*length*/, void * /*user_data*/)56{57::free(mem);58}59#endif // RYML_NO_DEFAULT_CALLBACKS60616263Callbacks::Callbacks()64:65m_user_data(nullptr),66#ifndef RYML_NO_DEFAULT_CALLBACKS67m_allocate(allocate_impl),68m_free(free_impl),69m_error(error_impl)70#else71m_allocate(nullptr),72m_free(nullptr),73m_error(nullptr)74#endif75{76}7778Callbacks::Callbacks(void *user_data, pfn_allocate alloc_, pfn_free free_, pfn_error error_)79:80m_user_data(user_data),81#ifndef RYML_NO_DEFAULT_CALLBACKS82m_allocate(alloc_ ? alloc_ : allocate_impl),83m_free(free_ ? free_ : free_impl),84m_error(error_ ? error_ : error_impl)85#else86m_allocate(alloc_),87m_free(free_),88m_error(error_)89#endif90{91C4_CHECK(m_allocate);92C4_CHECK(m_free);93C4_CHECK(m_error);94}959697void set_callbacks(Callbacks const& c)98{99s_default_callbacks = c;100}101102Callbacks const& get_callbacks()103{104return s_default_callbacks;105}106107void reset_callbacks()108{109set_callbacks(Callbacks());110}111112void error(const char *msg, size_t msg_len, Location loc)113{114s_default_callbacks.m_error(msg, msg_len, loc, s_default_callbacks.m_user_data);115}116117C4_SUPPRESS_WARNING_GCC_CLANG_POP118119} // namespace yml120} // namespace c4121122123