You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

72 lines
1.5 KiB

#include <cassert>
#include <cstdlib>
#include <cstdio>
#include "aixlog.hpp"
#include "util.h"
const uint MAX_FILESIZE = 2 * 1024 * 1024; // 2MB
const uint MAX_STRING_LENGTH = 1024;
// TODO: don't use ftell() to get filesize
// https://wiki.sei.cmu.edu/confluence/display/c/FIO19-C.+Do+not+use+fseek%28%29+and+ftell%28%29+to+compute+the+size+of+a+regular+file
char *
utilDumpTextFile(const char* filename)
{
LOG(INFO) << "loading filename, " << filename << "\n";
std::FILE* fp = std::fopen(filename, "rt");
assert(fp);
std::fseek(fp, 0, SEEK_END);
uint length = std::ftell(fp);
std::fseek(fp, 0, SEEK_SET);
assert(length < MAX_FILESIZE);
// TODO: check error codes for fseek and ftell
char* buf = (char *) std::calloc(length, sizeof(char));
assert(buf);
std::fread(buf, sizeof(char), length, fp);
// TODO: check fp w/ ferror() here
return buf;
}
void *
utilLogAlloc(uint item_count, uint type_size, const char* file_name, const int line)
{
assert(item_count > 0); // that was a fun bug
void* mem = std::calloc(item_count, type_size);
if (mem == nullptr) {
LOG(ERROR) << "Memory allocation failed, called from "
<< file_name << ":" << line;
}
assert(mem != nullptr); // might as well stop execution here
return mem;
}
// TODO: search/replace other calls to std::free with this
void
utilSafeFree(void* mem)
{
if (mem != nullptr) {
std::free(mem);
mem = nullptr;
}
}
// TODO: re-use non-const version, macro or cast away const
void utilSafeFree(const void* mem)
{
if (mem != nullptr) {
std::free((void *) mem);
mem = nullptr;
}
}