#include <ctype.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include "buffer.h"
#include "util.h"
static void vfail(const char *fmt, va_list args) __attribute__((__noreturn__));
static void vfail(const char *fmt, va_list args)
{
vfprintf(stderr, fmt, args);
fflush(stdin);
fflush(stderr);
fflush(stdout);
sync();
fsync(STDIN_FILENO);
fsync(STDERR_FILENO);
fsync(STDOUT_FILENO);
abort();
while (1);
}
void __fail(const char *file, unsigned int line,
const char *func __attribute__((unused)),
const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
fprintf(stderr, "\n%s:%u ", file, line);
vfail(fmt, args);
}
#ifndef HAVE_VARIADIC_MACROS
void fail(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfail(fmt, args);
}
#endif
void failure(const char *message)
{
fprintf(stderr,message);
exit(1);
}
char *rstrcat(region r, const char *s1, const char *s2)
{
char *result = rarrayalloc(r, strlen(s1)+strlen(s2)+1, char);
result[0] = '\0';
strcat(result, s1);
strcat(result, s2);
return result;
}
char *rstrscat(region r, ...)
{
char *result;
int len = 0;
const char *s;
va_list args;
va_start(args, r);
while ((s = va_arg(args, const char *)))
len += strlen(s);
result = rarrayalloc(r, len+1, char);
result[0] = '\0';
va_start(args, r);
while ((s = va_arg(args, const char *)))
strcat(result, s);
return result;
}
#if 0
const char *inttostr(region r, int i)
{
char *result;
int width;
if (i == 0)
width = 1;
else
width = (int) (floor(log10(abs((double) i))) + 1);
if (i<0) width++;
printf("i=%d, width=%d\n", i, width);
assert(width >0);
result = rarrayalloc(r, width + 1, char);
if (snprintf(result, width + 1, "%d", i) == -1) {
printf("i=%d, width=%d\n", i, width);
fail ("inttostr width wrong\n");
}
return result;
}
#endif
char *rsprintf(region r, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
return rvsprintf(r, fmt, args);
}
char *rvsprintf(region r, const char *fmt, va_list args)
{
growbuf buf = growbuf_new(r, 100);
gvprintf(buf, fmt, args);
return growbuf_contents(buf);
}
#define PTR_ASCII_SIZE ((int) (3 + sizeof(void *)*2))
char *ptr_to_ascii(void *ptr) {
static char addr[PTR_ASCII_SIZE];
int nchars;
nchars = snprintf(addr, PTR_ASCII_SIZE, "%p", ptr);
if (nchars == -1 || nchars >= PTR_ASCII_SIZE)
fail("Unable to convert ptr to ascii (need %d bytes, have %d)\n",
nchars, PTR_ASCII_SIZE);
return addr;
}
long ptr_hash(void *ptr)
{
return (long) ptr;
}
bool ptr_eq(void *ptr1, void *ptr2)
{
return ptr1 == ptr2;
}
bool str_eq(const char *s1, const char *s2)
{
return (strcmp(s1, s2) == 0);
}
int ptr_cmp(const void *ptr1, const void *ptr2)
{
return (char *) ptr1 - (char *) ptr2;
}