Consistency
[llpp.git] / cutils.c
blob1754158db4d085489d039dc69583125a8800f094
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);
68 /* handles u == 0 */
70 s[len] = 0;
73 char *ystrdup (const char *s)
75 size_t len = strlen (s);
76 if (len > 0) {
77 char *r = malloc (len+1);
78 if (!r) errx (1, "malloc %zu", len+1);
79 memcpy (r, s, len+1);
80 return r;
82 return NULL;