1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 *
6 * Copyright 1997 - July 2008 CWI, August 2008 - 2019 MonetDB B.V.
7 */
8
9#include "monetdb_config.h"
10#include "sql_mem.h"
11#include "gdk.h"
12#include "sql_string.h"
13#include "mal_exception.h"
14
15/*
16 * some string functions.
17 */
18
19/* implace cast to lower case string */
20char *
21mkLower(char *s)
22{
23 char *r = s;
24
25 while (*s) {
26 *s = (char) tolower(*s);
27 s++;
28 }
29 return r;
30}
31
32static char *
33mkUpper(char *s)
34{
35 char *r = s;
36
37 while (*s) {
38 *s = (char) toupper(*s);
39 s++;
40 }
41 return r;
42}
43
44char *
45toLower(const char *s)
46{
47 char *r = _STRDUP(s);
48
49 return r ? mkLower(r) : NULL;
50}
51
52char *
53toUpper(const char *s)
54{
55 char *r = _STRDUP(s);
56
57 return r ? mkUpper(r) : NULL;
58}
59
60/* concat s1,s2 into a new result string */
61char *
62strconcat(const char *s1, const char *s2)
63{
64 size_t i, j, l1 = strlen(s1);
65 size_t l2 = strlen(s2) + 1;
66 char *new_s = NEW_ARRAY(char, l1 + l2);
67
68 if (new_s) {
69 for (i = 0; i < l1; i++) {
70 new_s[i] = s1[i];
71 }
72 for (j = 0; j < l2; j++, i++) {
73 new_s[i] = s2[j];
74 }
75 }
76 return new_s;
77}
78
79char *
80strip_extra_zeros(char *s)
81{
82 char *res = s;
83
84 for (; *s && isspace((unsigned char) *s); s++)
85 ;
86 res = s;
87 /* find end, and strip extra 0's */
88 for (; *s; s++) ;
89 s--;
90 for (; *s && *s == '0' && s[-1] == '0'; s--)
91 ;
92 s++;
93 *s = 0;
94 return res;
95}
96
97char *
98sql_strdup(char *s)
99{
100 size_t l = strlen(s);
101 char *r = NEW_ARRAY(char, l);
102
103 if (r) {
104 memcpy(r, s + 1, l - 2);
105 r[l - 2] = 0;
106 }
107 return r;
108}
109
110char *
111sql_escape_str(char *s)
112{
113 size_t l = strlen(s);
114 char *res, *r = NEW_ARRAY(char, (l * 2) + 1);
115
116 res = r;
117 if (res) {
118 while (*s) {
119 if (*s == '\'' || *s == '\\') {
120 *r++ = '\\';
121 }
122 *r++ = *s++;
123 }
124 *r = '\0';
125 }
126 return res;
127}
128
129const char *
130sql_escape_ident(const char *s)
131{
132 size_t l = strlen(s);
133 char *res, *r = NEW_ARRAY(char, (l * 2) + 1);
134
135 res = r;
136 if (res) {
137 while (*s) {
138 if (*s == '"' || *s == '\\') {
139 *r++ = '\\';
140 }
141 *r++ = *s++;
142 }
143 *r = '\0';
144 }
145 return res;
146}
147
148char *sql_message( const char *format, ... )
149{
150 char buf[BUFSIZ];
151 va_list ap;
152
153 va_start (ap,format);
154 (void) vsnprintf( buf, BUFSIZ, format, ap);
155 va_end (ap);
156 return GDKstrdup(buf);
157}
158
159char *sa_message( sql_allocator *sa, const char *format, ... )
160{
161 char buf[BUFSIZ];
162 va_list ap;
163
164 va_start (ap,format);
165 (void) vsnprintf( buf, BUFSIZ, format, ap);
166 va_end (ap);
167 return sa_strdup(sa, buf);
168}
169
170