rearrange some things
[voxelands-alt.git] / src / lib / string.c
blobaca928bb0250689a44734670115158a72092da58
1 /************************************************************************
2 * string.c
3 * voxelands - 3d voxel world sandbox game
4 * Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 * See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>
18 ************************************************************************/
20 #include "common.h"
22 #include <stdlib.h>
23 #include <string.h>
24 #include <ctype.h>
26 /* remove whitespace from beginning and end of a string */
27 char* trim(char* str)
29 int l;
31 while (*str && isspace(*str)) {
32 str++;
35 l = strlen(str);
36 while (--l > -1 && (!str[l] || isspace(str[l]))) {
37 str[l] = 0;
40 return str;
43 /* allocate memory and copy a string */
44 char* strdup(const char* str)
46 char* r;
47 int l;
49 if (!str)
50 return NULL;
52 l = strlen(str);
53 l++;
55 r = malloc(l);
56 if (!r)
57 return NULL;
59 if (!memcpy(r,str,l)) {
60 free(r);
61 return NULL;
64 return r;
67 /* append str to dest, only if there's room for all of it */
68 int strappend(char* dest, int size, char* str)
70 int l;
72 l = strlen(dest);
73 l += strlen(str);
75 if (l >= size)
76 return 0;
78 strcat(dest,str);
80 return l;
83 /* makes a string safe for use as a file or directory name */
84 int str_sanitise(char* dest, int size, char* str)
86 int o = 0;
87 int i = 0;
88 int lws = 0;
90 for (; o<size; i++) {
91 if (!str[i]) {
92 dest[o] = 0;
93 return o;
95 if (isalnum(str[i])) {
96 lws = 0;
97 dest[o++] = str[i];
98 }else if (!lws) {
99 dest[o++] = '_';
100 lws = 1;
104 return -1;
107 /* parse a string into a bool true/false 1/0 */
108 int parse_bool(char* str)
110 if (str) {
111 if (!strcmp(str,"true"))
112 return 1;
113 if (!strcmp(str,"yes"))
114 return 1;
115 if (!strcmp(str,"on"))
116 return 1;
117 if (!strcmp(str,"enabled"))
118 return 1;
119 if (!strcmp(str,"active"))
120 return 1;
121 if (strtol(str,NULL,10))
122 return 1;
125 return 0;