chiark / gitweb /
Fix builtins.
[userv.git] / lib.c
1 /*
2  * userv - lib.c
3  * useful utility routines, used in daemon, but not very dependent on it
4  *
5  * Copyright (C)1996-1997 Ian Jackson
6  *
7  * This is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with userv; if not, write to the Free Software
19  * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */
21
22 #include <errno.h>
23 #include <syslog.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <string.h>
28
29 #include "config.h"
30 #include "lib.h"
31
32 char *xstrcat3save(const char *a, const char *b, const char *c) {
33   char *r;
34
35   r= xmalloc(strlen(a)+strlen(b)+strlen(c)+1);
36   strcpy(r,a);
37   strcat(r,b);
38   strcat(r,c);
39   return r;
40 }
41
42 char *xstrsave(const char *s) {
43   char *r;
44
45   r= xmalloc(strlen(s)+1);
46   strcpy(r,s);
47   return r;
48 }
49
50 char *xstrsubsave(const char *begin, int len) {
51   char *r;
52   
53   r= xmalloc(len+1);
54   memcpy(r,begin,len);
55   r[len]= 0;
56   return r;
57 }
58
59 void *xmalloc(size_t s) {
60   void *p;
61   p= malloc(s?s:1); if (!p) syscallerror("malloc");
62   return p;
63 }
64
65 void *xrealloc(void *p, size_t s) {
66   p= realloc(p,s); if (!p) syscallerror("realloc");
67   return p;
68 }
69
70 void makeroom(char **buffer, int *size, int needed) {
71   if (*size >= needed) return;
72   *buffer= xrealloc(*buffer,needed);
73   *size= needed;
74 }
75
76 void vsnyprintf(char *buffer, size_t size, const char *fmt, va_list al) {
77   vsnprintf(buffer,size,fmt,al);
78   buffer[size-1]= 0;
79 }
80
81 void snyprintf(char *buffer, size_t size, const char *fmt, ...) {
82   va_list al;
83   va_start(al,fmt);
84   vsnyprintf(buffer,size,fmt,al);
85   va_end(al);
86 }
87
88 void strnycpy(char *dest, const char *src, size_t size) {
89   strncpy(dest,src,size-1);
90   dest[size-1]= 0;
91 }
92
93 void strnytcat(char *dest, const char *src, size_t size) {
94   size_t l;
95   l= strlen(dest);
96   strnycpy(dest+l,src,size-l);
97 }
98
99 void vsnytprintfcat(char *buffer, size_t size, const char *fmt, va_list al) {
100   size_t l;
101   l= strlen(buffer);
102   vsnyprintf(buffer+l,size-l,fmt,al);
103 }
104
105 void snytprintfcat(char *buffer, size_t size, const char *fmt, ...) {
106   va_list al;
107   va_start(al,fmt);
108   vsnytprintfcat(buffer,size,fmt,al);
109   va_end(al);
110 }