Updating ChangeLog for 4.22.10
[centerim.git] / firetalk / safestring.c
blob7f852defdbb1c711676646f713b72be92ebd943c
1 /*
2 safestring.c - FireTalk replacement string functions
3 Copyright (C) 2000 Ian Gulliver
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of version 2 of the GNU General Public License as
7 published by the Free Software Foundation.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "safestring.h"
20 #include <string.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <ctype.h>
26 void *safe_malloc(const size_t size) {
27 char *output;
28 output = malloc(size);
29 if (output == NULL) {
30 perror("malloc");
31 exit(EXIT_FAILURE);
33 return output;
36 void *safe_realloc(void *old, const size_t new) {
37 char *output;
38 output = realloc(old,new);
39 if (output == NULL) {
40 perror("realloc");
41 exit(EXIT_FAILURE);
43 return output;
46 char *safe_strdup(const char * const input) {
47 char *output;
48 size_t s;
49 if (input == NULL)
50 return NULL;
51 s = strlen(input) + 1;
52 output = safe_malloc(s);
53 safe_strncpy(output,input,s);
54 return(output);
57 void safe_strncpy(char * const to, const char * const from, const size_t size) {
58 strncpy(to,from,size);
59 to[size - 1]= '\0';
60 return;
63 void safe_strncat(char * const to, const char * const from, const size_t size) {
64 size_t l;
65 l = strlen(to);
66 safe_strncpy(&to[l],from,size - l);
67 return;
70 void safe_snprintf(char *out, const size_t size, char * const format, ...) {
71 va_list ap;
72 char numbuf[10]; /* stores shorts for printing */
73 size_t f,o = 0,fl,tl,ml;
74 char *tempchr;
75 int b = 0;
77 fl = strlen(format);
78 ml = size - 1;
80 va_start(ap,format);
81 for (f = 0; f < fl && o < ml && b == 0; f++) {
82 if (format[f] == '%') {
83 switch(format[++f]) {
84 case 's':
85 tempchr = va_arg(ap,char *);
86 tl = strlen(tempchr);
87 if (tl + o >= ml)
88 b = 1;
89 else {
90 memcpy(&out[o],tempchr,tl);
91 out += tl;
93 break;
94 case 'd':
95 sprintf(numbuf,"%d",va_arg(ap,int));
96 tl = strlen(numbuf);
97 if (tl + o >= ml)
98 b = 1;
99 else {
100 memcpy(&out[o],numbuf,tl);
101 out += tl;
103 break;
104 case '%':
105 out[o++] = '%';
106 break;
108 } else
109 out[o++] = format[f];
111 out[o] = '\0';
112 return;
115 int safe_strncasecmp(const char *s1, const char *s2, size_t n) {
116 size_t s;
117 for (s = 0; s < n; s++) {
118 if (tolower((unsigned char) s1[s]) != tolower((unsigned char) s2[s]))
119 return 1;
120 if (s1[s] == '\0')
121 return 0;
123 return 0;