added gentoo ebuilds
[libmixp.git] / cmd / util.c
blob507a2266b7f77ea3b2e22ca882628d0502de1a90
1 /* Written by Kris Maglione <fbsdaemon at gmail dot com> */
2 /* Public domain */
3 #include <errno.h>
4 #include <stdarg.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include "util.h"
11 void
12 fatal(const char *fmt, ...) {
13 va_list ap;
14 int err;
16 err = errno;
17 fprintf(stderr, "%s: fatal: ", argv0);
19 va_start(ap, fmt);
20 vfprintf(stderr, fmt, ap);
21 va_end(ap);
23 if(fmt[strlen(fmt)-1] == ':')
24 fprintf(stderr, " %s\n", strerror(err));
25 else
26 fprintf(stderr, "\n");
28 exit(1);
31 /* Can't malloc */
32 void
33 mfatal(char *name, unsigned int size) {
34 const char
35 couldnot[] = ": fatal: Could not ",
36 paren[] = "() ",
37 bytes[] = " bytes\n";
38 char sizestr[8];
39 int i;
41 i = sizeof(sizestr);
42 do {
43 sizestr[--i] = '0' + (size%10);
44 size /= 10;
45 } while(size > 0);
47 write(1, argv0, strlen(argv0)-1);
48 write(1, couldnot, sizeof(couldnot)-1);
49 write(1, name, strlen(name));
50 write(1, paren, sizeof(paren)-1);
51 write(1, sizestr+i, sizeof(sizestr)-i);
52 write(1, bytes, sizeof(bytes)-1);
54 exit(1);
57 void *
58 emalloc(unsigned int size) {
59 void *ret = malloc(size);
60 if(!ret)
61 mfatal("malloc", size);
62 return ret;
65 void *
66 emallocz(unsigned int size) {
67 void *ret = emalloc(size);
68 memset(ret, 0, size);
69 return ret;
72 void *
73 erealloc(void *ptr, unsigned int size) {
74 void *ret = realloc(ptr, size);
75 if(!ret)
76 mfatal("realloc", size);
77 return ret;
80 char *
81 estrdup(const char *str) {
82 void *ret = strdup(str);
83 if(!ret)
84 mfatal("strdup", strlen(str));
85 return ret;
88 unsigned int
89 tokenize(char *res[], unsigned int reslen, char *str, char delim) {
90 char *s;
91 unsigned int i;
93 i = 0;
94 s = str;
95 while(i < reslen && *s) {
96 while(*s == delim)
97 *(s++) = '\0';
98 if(*s)
99 res[i++] = s;
100 while(*s && *s != delim)
101 s++;
103 return i;
107 max(int a, int b) {
108 if(a > b)
109 return a;
110 return b;
114 min(int a, int b) {
115 if(a < b)
116 return a;
117 return b;
120 unsigned int
121 strlcat(char *dst, const char *src, unsigned int size) {
122 const char *s;
123 char *d;
124 int n, len;
126 d = dst;
127 s = src;
128 n = size;
129 while(n-- > 0 && *d != '\0')
130 d++;
131 len = n;
133 while(*s != '\0') {
134 if(n-- > 0)
135 *d++ = *s;
136 s++;
138 if(len > 0)
139 *d = '\0';
140 return size - n - 1;