kulp / tenyr
1
#define _XOPEN_SOURCE (700) /* for strdup */
2

3
#include "common.h"
4

5
#include <errno.h>
6
#include <stdarg.h>
7
#include <stdio.h>
8
#include <stdlib.h>
9
#include <string.h>
10

11
// This file must not be linked into plugins, because of the different way
12
// fatal_ and debug_ are handled in main programs vs. plugins. This file should
13
// probably be renamed.
14

15
jmp_buf errbuf;
16

17 1
static void NORETURN main_fatal_(int code, const char *file, int line,
18
    const char *func, const char *fmt, ...)
19
{
20
    va_list vl;
21 1
    va_start(vl,fmt);
22 1
    vfprintf(stderr, fmt, vl);
23 1
    va_end(vl);
24 1
    fprintf(stderr, " (in %s() at %s:%d)", func, file, line);
25

26 1
    if (code & PRINT_ERRNO)
27 1
        fprintf(stderr, ": %s\n", strerror(errno));
28
    else
29 1
        fwrite("\n", 1, 1, stderr);
30

31 1
    longjmp(errbuf, code);
32
}
33

34 1
static void main_debug_(int level, const char *file, int line,
35
    const char *func, const char *fmt, ...)
36
{
37
#ifndef DEBUG
38
#define DEBUG 0
39
#endif
40 1
    if (level > DEBUG)
41 1
        return;
42

43
    va_list vl;
44 1
    va_start(vl,fmt);
45 1
    vfprintf(stderr, fmt, vl);
46 1
    va_end(vl);
47 1
    fprintf(stderr, " (in %s() at %s:%d)\n", func, file, line);
48
}
49

50 1
long long numberise(char *str, int base)
51
{
52 1
    char *p = str;
53
    // there are more efficient ways to strip '_' but this one is pretty clear
54 1
    size_t len = strlen(p);
55 1
    while ((p = strchr(p, '_')))
56 1
        memmove(p, p + 1, len - (size_t)(p - str));
57

58 1
    return strtoll(str, NULL, base);
59
}
60

61 1
char *build_path(const char *base, const char *fmt, ...)
62
{
63 1
    char *dir = strdup(base);
64 1
    char *solidus = strrchr(dir, '/');
65 1
    if (solidus)
66 1
        solidus[1] = '\0';
67

68
    va_list vl;
69 1
    va_start(vl, fmt);
70

71 1
    size_t flen = strlen(fmt) + strlen(dir) + 1;
72 1
    char *ff = malloc(flen);
73 1
    snprintf(ff, flen, "%s%s", solidus ? dir : "", fmt);
74 1
    size_t len = (size_t)vsnprintf(NULL, 0, ff, vl);
75 1
    va_start(vl, fmt); // restart
76 1
    char *buf = malloc(len + 1);
77 1
    vsnprintf(buf, len + 1, ff, vl);
78

79 1
    free(ff);
80 1
    free(dir);
81 1
    va_end(vl);
82

83 1
    return buf;
84
}
85

86
// These are the implementations of the `common` functions, main program version.
87
// TODO these should probably be wrapped up in a structure
88
void (* NORETURN fatal_)(int code, const char *file, int line, const char *func, const char *fmt, ...) = main_fatal_;
89
void (*debug_)(int level, const char *file, int line, const char *func, const char *fmt, ...) = main_debug_;
90

91
/* vi: set ts=4 sw=4 et: */

Read our documentation on viewing source code .

Loading