1 /*************************************************************************/
2 /*  string_utils.cpp                                                     */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
9 /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
10 /*                                                                       */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the       */
13 /* "Software"), to deal in the Software without restriction, including   */
14 /* without limitation the rights to use, copy, modify, merge, publish,   */
15 /* distribute, sublicense, and/or sell copies of the Software, and to    */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions:                                             */
18 /*                                                                       */
19 /* The above copyright notice and this permission notice shall be        */
20 /* included in all copies or substantial portions of the Software.       */
21 /*                                                                       */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
29 /*************************************************************************/
30 
31 #include "string_utils.h"
32 
33 #include "core/os/file_access.h"
34 
35 #include <stdio.h>
36 #include <stdlib.h>
37 
38 namespace {
39 
sfind(const String & p_text,int p_from)40 int sfind(const String &p_text, int p_from) {
41 	if (p_from < 0)
42 		return -1;
43 
44 	int src_len = 2;
45 	int len = p_text.length();
46 
47 	if (len == 0)
48 		return -1;
49 
50 	const CharType *src = p_text.c_str();
51 
52 	for (int i = p_from; i <= (len - src_len); i++) {
53 		bool found = true;
54 
55 		for (int j = 0; j < src_len; j++) {
56 			int read_pos = i + j;
57 
58 			ERR_FAIL_COND_V(read_pos >= len, -1);
59 
60 			switch (j) {
61 				case 0:
62 					found = src[read_pos] == '%';
63 					break;
64 				case 1: {
65 					CharType c = src[read_pos];
66 					found = src[read_pos] == 's' || (c >= '0' && c <= '4');
67 					break;
68 				}
69 				default:
70 					found = false;
71 			}
72 
73 			if (!found) {
74 				break;
75 			}
76 		}
77 
78 		if (found)
79 			return i;
80 	}
81 
82 	return -1;
83 }
84 } // namespace
85 
sformat(const String & p_text,const Variant & p1,const Variant & p2,const Variant & p3,const Variant & p4,const Variant & p5)86 String sformat(const String &p_text, const Variant &p1, const Variant &p2, const Variant &p3, const Variant &p4, const Variant &p5) {
87 	if (p_text.length() < 2)
88 		return p_text;
89 
90 	Array args;
91 
92 	if (p1.get_type() != Variant::NIL) {
93 		args.push_back(p1);
94 
95 		if (p2.get_type() != Variant::NIL) {
96 			args.push_back(p2);
97 
98 			if (p3.get_type() != Variant::NIL) {
99 				args.push_back(p3);
100 
101 				if (p4.get_type() != Variant::NIL) {
102 					args.push_back(p4);
103 
104 					if (p5.get_type() != Variant::NIL) {
105 						args.push_back(p5);
106 					}
107 				}
108 			}
109 		}
110 	}
111 
112 	String new_string;
113 
114 	int findex = 0;
115 	int search_from = 0;
116 	int result = 0;
117 
118 	while ((result = sfind(p_text, search_from)) >= 0) {
119 		CharType c = p_text[result + 1];
120 
121 		int req_index = (c == 's' ? findex++ : c - '0');
122 
123 		new_string += p_text.substr(search_from, result - search_from);
124 		new_string += args[req_index].operator String();
125 		search_from = result + 2;
126 	}
127 
128 	new_string += p_text.substr(search_from, p_text.length() - search_from);
129 
130 	return new_string;
131 }
132 
133 #ifdef TOOLS_ENABLED
is_csharp_keyword(const String & p_name)134 bool is_csharp_keyword(const String &p_name) {
135 
136 	// Reserved keywords
137 
138 	return p_name == "abstract" || p_name == "as" || p_name == "base" || p_name == "bool" ||
139 		   p_name == "break" || p_name == "byte" || p_name == "case" || p_name == "catch" ||
140 		   p_name == "char" || p_name == "checked" || p_name == "class" || p_name == "const" ||
141 		   p_name == "continue" || p_name == "decimal" || p_name == "default" || p_name == "delegate" ||
142 		   p_name == "do" || p_name == "double" || p_name == "else" || p_name == "enum" ||
143 		   p_name == "event" || p_name == "explicit" || p_name == "extern" || p_name == "false" ||
144 		   p_name == "finally" || p_name == "fixed" || p_name == "float" || p_name == "for" ||
145 		   p_name == "forech" || p_name == "goto" || p_name == "if" || p_name == "implicit" ||
146 		   p_name == "in" || p_name == "int" || p_name == "interface" || p_name == "internal" ||
147 		   p_name == "is" || p_name == "lock" || p_name == "long" || p_name == "namespace" ||
148 		   p_name == "new" || p_name == "null" || p_name == "object" || p_name == "operator" ||
149 		   p_name == "out" || p_name == "override" || p_name == "params" || p_name == "private" ||
150 		   p_name == "protected" || p_name == "public" || p_name == "readonly" || p_name == "ref" ||
151 		   p_name == "return" || p_name == "sbyte" || p_name == "sealed" || p_name == "short" ||
152 		   p_name == "sizeof" || p_name == "stackalloc" || p_name == "static" || p_name == "string" ||
153 		   p_name == "struct" || p_name == "switch" || p_name == "this" || p_name == "throw" ||
154 		   p_name == "true" || p_name == "try" || p_name == "typeof" || p_name == "uint" || p_name == "ulong" ||
155 		   p_name == "unchecked" || p_name == "unsafe" || p_name == "ushort" || p_name == "using" ||
156 		   p_name == "virtual" || p_name == "volatile" || p_name == "void" || p_name == "while";
157 }
158 
escape_csharp_keyword(const String & p_name)159 String escape_csharp_keyword(const String &p_name) {
160 	return is_csharp_keyword(p_name) ? "@" + p_name : p_name;
161 }
162 #endif
163 
read_all_file_utf8(const String & p_path,String & r_content)164 Error read_all_file_utf8(const String &p_path, String &r_content) {
165 	PoolVector<uint8_t> sourcef;
166 	Error err;
167 	FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
168 	ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + p_path + "'.");
169 
170 	int len = f->get_len();
171 	sourcef.resize(len + 1);
172 	PoolVector<uint8_t>::Write w = sourcef.write();
173 	int r = f->get_buffer(w.ptr(), len);
174 	f->close();
175 	memdelete(f);
176 	ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
177 	w[len] = 0;
178 
179 	String source;
180 	if (source.parse_utf8((const char *)w.ptr())) {
181 		ERR_FAIL_V(ERR_INVALID_DATA);
182 	}
183 
184 	r_content = source;
185 	return OK;
186 }
187 
188 // TODO: Move to variadic templates once we upgrade to C++11
189 
str_format(const char * p_format,...)190 String str_format(const char *p_format, ...) {
191 	va_list list;
192 
193 	va_start(list, p_format);
194 	String res = str_format(p_format, list);
195 	va_end(list);
196 
197 	return res;
198 }
199 // va_copy was defined in the C99, but not in C++ standards before C++11.
200 // When you compile C++ without --std=c++<XX> option, compilers still define
201 // va_copy, otherwise you have to use the internal version (__va_copy).
202 #if !defined(va_copy)
203 #if defined(__GNUC__)
204 #define va_copy(d, s) __va_copy((d), (s))
205 #else
206 #define va_copy(d, s) ((d) = (s))
207 #endif
208 #endif
209 
210 #if defined(MINGW_ENABLED) || defined(_MSC_VER) && _MSC_VER < 1900
211 #define gd_vsnprintf(m_buffer, m_count, m_format, m_args_copy) vsnprintf_s(m_buffer, m_count, _TRUNCATE, m_format, m_args_copy)
212 #define gd_vscprintf(m_format, m_args_copy) _vscprintf(m_format, m_args_copy)
213 #else
214 #define gd_vsnprintf(m_buffer, m_count, m_format, m_args_copy) vsnprintf(m_buffer, m_count, m_format, m_args_copy)
215 #define gd_vscprintf(m_format, m_args_copy) vsnprintf(NULL, 0, p_format, m_args_copy)
216 #endif
217 
str_format(const char * p_format,va_list p_list)218 String str_format(const char *p_format, va_list p_list) {
219 	char *buffer = str_format_new(p_format, p_list);
220 
221 	String res(buffer);
222 	memdelete_arr(buffer);
223 
224 	return res;
225 }
226 
str_format_new(const char * p_format,...)227 char *str_format_new(const char *p_format, ...) {
228 	va_list list;
229 
230 	va_start(list, p_format);
231 	char *res = str_format_new(p_format, list);
232 	va_end(list);
233 
234 	return res;
235 }
236 
str_format_new(const char * p_format,va_list p_list)237 char *str_format_new(const char *p_format, va_list p_list) {
238 	va_list list;
239 
240 	va_copy(list, p_list);
241 	int len = gd_vscprintf(p_format, list);
242 	va_end(list);
243 
244 	len += 1; // for the trailing '/0'
245 
246 	char *buffer(memnew_arr(char, len));
247 
248 	va_copy(list, p_list);
249 	gd_vsnprintf(buffer, len, p_format, list);
250 	va_end(list);
251 
252 	return buffer;
253 }
254