Use Ffi module explicitly
[llpp.git] / cutils.c
blob76bd3804fb7e6a8a3fe6a568633aa082aec5b055
1 #include <stdio.h>
2 #include <errno.h>
3 #include <stdarg.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <inttypes.h>
8 #include <sys/time.h>
10 #include "cutils.h"
12 void NORETURN_ATTR GCC_FMT_ATTR (2, 3) err (int exitcode, const char *fmt, ...)
14 va_list ap;
15 int savederrno;
17 savederrno = errno;
18 va_start (ap, fmt);
19 vfprintf (stderr, fmt, ap);
20 va_end (ap);
21 fprintf (stderr, ": %s\n", strerror (savederrno));
22 fflush (stderr);
23 _exit (exitcode);
26 void NORETURN_ATTR GCC_FMT_ATTR (2, 3) errx (int exitcode, const char *fmt, ...)
28 va_list ap;
30 va_start (ap, fmt);
31 vfprintf (stderr, fmt, ap);
32 va_end (ap);
33 fputc ('\n', stderr);
34 fflush (stderr);
35 _exit (exitcode);
38 void *parse_pointer (const char *cap, const char *s)
40 int ret;
41 void *ptr;
43 ret = sscanf (s, "%" SCNxPTR, (uintptr_t *) &ptr);
44 if (ret != 1) {
45 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
47 return ptr;
50 double now (void)
52 struct timeval tv;
53 gettimeofday (&tv, NULL);
54 return tv.tv_sec + tv.tv_usec*1e-6;
57 /* slightly tweaked fmt_ulong by D.J. Bernstein */
58 void fmt_linkn (char *s, unsigned int u)
60 unsigned int len; unsigned int q;
61 unsigned int zma = 'z' - 'a' + 1;
62 len = 1; q = u;
63 while (q > zma - 1) { ++len; q /= zma; }
64 if (s) {
65 s += len;
66 do { *--s = (char)('a' + (u % zma) - (u < zma && len > 1));
67 u /= zma; } while(u); /* handles u == 0 */
69 s[len] = 0;
72 char *ystrdup (const char *s)
74 size_t len = strlen (s);
75 if (len > 0) {
76 char *r = malloc (len+1);
77 if (!r) errx (1, "malloc %zu", len+1);
78 memcpy (r, s, len+1);
79 return r;
81 return NULL;