aboutsummaryrefslogtreecommitdiff
path: root/src/util/string.h
blob: 6c48adeb3d70b0368f4f62b5a7a13d4ebcd03081 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#ifndef UTIL_STRING_HEADER
#define UTIL_STRING_HEADER

#include "../irrlichttypes.h"
#include "../strfnd.h" // For trim()
#include "pointer.h"
#include <string>
#include <cstring>
#include <vector>
#include <sstream>

struct FlagDesc {
	const char *name;
	u32 flag;
};

static inline std::string padStringRight(std::string s, size_t len)
{
	if(len > s.size())
		s.insert(s.end(), len - s.size(), ' ');
	return s;
}

// ends: NULL- or ""-terminated array of strings
// Returns "" if no end could be removed.
static inline std::string removeStringEnd(const std::string &s, const char *ends[])
{
	const char **p = ends;
	for(; (*p) && (*p)[0] != '\0'; p++){
		std::string end = *p;
		if(s.size() < end.size())
			continue;
		if(s.substr(s.size()-end.size(), end.size()) == end)
			return s.substr(0, s.size() - end.size());
	}
	return "";
}

// Tests if two strings are equal, optionally case insensitive
inline bool str_equal(const std::wstring& s1, const std::wstring& s2,
		bool case_insensitive = false)
{
	if(case_insensitive)
	{
		if(s1.size() != s2.size())
			return false;
		for(size_t i = 0; i < s1.size(); ++i)
			if(tolower(s1[i]) != tolower(s2[i]))
				return false;
		return true;
	}
	else
	{
		return s1 == s2;
	}
}

// Tests if the second string is a prefix of the first, optionally case insensitive
inline bool str_starts_with(const std::wstring& str, const std::wstring& prefix,
		bool case_insensitive = false)
{
	if(str.size() < prefix.size())
		return false;
	if(case_insensitive)
	{
		for(size_t i = 0; i < prefix.size(); ++i)
			if(tolower(str[i]) != tolower(prefix[i]))
				return false;
	}
	else
	{
		for(size_t i = 0; i < prefix.size(); ++i)
			if(str[i] != prefix[i])
				return false;
	}
	return true;
}

inline std::wstring narrow_to_wide(const std::string& mbs)
{
	size_t wcl = mbs.size();
	Buffer<wchar_t> wcs(wcl+1);
	size_t l = mbstowcs(*wcs, mbs.c_str(), wcl);
	if(l == (size_t)(-1))
		return L"<invalid multibyte string>";
	wcs[l] = 0;
	return *wcs;
}

inline std::string wide_to_narrow(const std::wstring& wcs)
{
	size_t mbl = wcs.size()*4;
	SharedBuffer<char> mbs(mbl+1);
	size_t l = wcstombs(*mbs, wcs.c_str(), mbl);
	if(l == (size_t)(-1))
		mbs[0] = 0;
	else
		mbs[l] = 0;
	return *mbs;
}

// Split a string using the given delimiter. Returns a vector containing
// the component parts.
inline std::vector<std::wstring> str_split(const std::wstring &str, wchar_t delimiter)
{
	std::vector<std::wstring> parts;
	std::wstringstream sstr(str);
	std::wstring part;
	while(std::getline(sstr, part, delimiter))
		parts.push_back(part);
	return parts;
}

inline std::string lowercase(const std::string &s)
{
	std::string s2;
	for(size_t i=0; i<s.size(); i++)
	{
		char c = s[i];
		if(c >= 'A' && c <= 'Z')
			c -= 'A' - 'a';
		s2 += c;
	}
	return s2;
}

inline bool is_yes(const std::string &s)
{
	std::string s2 = lowercase(trim(s));
	if(s2 == "y" || s2 == "yes" || s2 == "true" || s2 == "1")
		return true;
	return false;
}

inline s32 mystoi(const std::string &s, s32 min, s32 max)
{
	s32 i = atoi(s.c_str());
	if(i < min)
		i = min;
	if(i > max)
		i = max;
	return i;
}


// MSVC2010 includes it's own versions of these
//#if !defined(_MSC_VER) || _MSC_VER < 1600

inline s32 mystoi(const std::string &s)
{
	return atoi(s.c_str());
}

inline s32 mystoi(const std::wstring &s)
{
	return atoi(wide_to_narrow(s).c_str());
}

inline float mystof(const std::string &s)
{
	// This crap causes a segfault in certain cases on MinGW
	/*float f;
	std::istringstream ss(s);
	ss>>f;
	return f;*/
	// This works in that case
	return atof(s.c_str());
}

//#endif

#define stoi mystoi
#define stof mystof

inline std::string itos(s32 i)
{
	std::ostringstream o;
	o<<i;
	return o.str();
}

inline std::string ftos(float f)
{
	std::ostringstream o;
	o<<f;
	return o.str();
}

inline void str_replace(std::string & str, std::string const & pattern,
		std::string const & replacement)
{
	std::string::size_type start = str.find(pattern, 0);
	while(start != str.npos)
	{
		str.replace(start, pattern.size(), replacement);
		start = str.find(pattern, start+replacement.size());
	}
}

inline void str_replace_char(std::string & str, char from, char to)
{
	for(unsigned int i=0; i<str.size(); i++)
	{
		if(str[i] == from)
			str[i] = to;
	}
}

/*
	Checks if a string contains only supplied characters
*/
inline bool string_allowed(const std::string &s, const std::string &allowed_chars)
{
	for(u32 i=0; i<s.size(); i++)
	{
		bool confirmed = false;
		for(u32 j=0; j<allowed_chars.size(); j++)
		{
			if(s[i] == allowed_chars[j])
			{
				confirmed = true;
				break;
			}
		}
		if(confirmed == false)
			return false;
	}
	return true;
}

/*
	Checks if a string contains no blacklisted characters (opposite
	function of string_allowed())
*/
inline bool string_allowed_blacklist(const std::string & s, const std::string & blacklisted_chars)
{
	for(unsigned int i = 0; i < s.length(); i++)
	{
		bool invalid = false;
		for(unsigned int j = 0; j < blacklisted_chars.length(); j++)
		{
			if(s[i] == blacklisted_chars[j])
			{
				invalid = true;
				break;
			}
		}
		if(invalid)
			return false;
	}
	return true;
}

/*
	Forcefully wraps string into rows using \n
	(no word wrap, used for showing paths in gui)
*/
inline std::string wrap_rows(const std::string &from, u32 rowlen)
{
	std::string to;
	for(u32 i=0; i<from.size(); i++)
	{
		if(i != 0 && i%rowlen == 0)
			to += '\n';
		to += from[i];
	}
	return to;
}

/*
	Removes all \\ from a string that had been escaped (FormSpec strings)
*/
inline std::string unescape_string(std::string &s)
{
	std::string res;
	
	for (size_t i = 0; i <= s.length(); i++) {
		if (s[i] == '\\')
			i++;
		res += s[i];
	}
	
	return res;
}

std::string translatePassword(std::string playername, std::wstring password);
size_t curl_write_data(char *ptr, size_t size, size_t nmemb, void *userdata);
u32 readFlagString(std::string str, FlagDesc *flagdesc);
std::string writeFlagString(u32 flags, FlagDesc *flagdesc);
char *mystrtok_r(char *s, const char *sep, char **lasts);

#endif

hl opt">(L, index, "x"); CHECK_POS_COORD("x"); pos.X = lua_tonumber(L, -1); CHECK_FLOAT_RANGE(pos.X, "x") lua_pop(L, 1); lua_getfield(L, index, "y"); CHECK_POS_COORD("y"); pos.Y = lua_tonumber(L, -1); CHECK_FLOAT_RANGE(pos.Y, "y") lua_pop(L, 1); lua_getfield(L, index, "z"); CHECK_POS_COORD("z"); pos.Z = lua_tonumber(L, -1); CHECK_FLOAT_RANGE(pos.Z, "z") lua_pop(L, 1); return pos; } v3d read_v3d(lua_State *L, int index) { v3d pos; CHECK_POS_TAB(index); lua_getfield(L, index, "x"); pos.X = lua_tonumber(L, -1); lua_pop(L, 1); lua_getfield(L, index, "y"); pos.Y = lua_tonumber(L, -1); lua_pop(L, 1); lua_getfield(L, index, "z"); pos.Z = lua_tonumber(L, -1); lua_pop(L, 1); return pos; } v3d check_v3d(lua_State *L, int index) { v3d pos; CHECK_POS_TAB(index); lua_getfield(L, index, "x"); CHECK_POS_COORD("x"); pos.X = lua_tonumber(L, -1); CHECK_FLOAT_RANGE(pos.X, "x") lua_pop(L, 1); lua_getfield(L, index, "y"); CHECK_POS_COORD("y"); pos.Y = lua_tonumber(L, -1); CHECK_FLOAT_RANGE(pos.Y, "y") lua_pop(L, 1); lua_getfield(L, index, "z"); CHECK_POS_COORD("z"); pos.Z = lua_tonumber(L, -1); CHECK_FLOAT_RANGE(pos.Z, "z") lua_pop(L, 1); return pos; } void push_ARGB8(lua_State *L, video::SColor color) { lua_createtable(L, 0, 4); lua_pushinteger(L, color.getAlpha()); lua_setfield(L, -2, "a"); lua_pushinteger(L, color.getRed()); lua_setfield(L, -2, "r"); lua_pushinteger(L, color.getGreen()); lua_setfield(L, -2, "g"); lua_pushinteger(L, color.getBlue()); lua_setfield(L, -2, "b"); } void pushFloatPos(lua_State *L, v3f p) { p /= BS; push_v3f(L, p); } v3f checkFloatPos(lua_State *L, int index) { return check_v3f(L, index) * BS; } void push_v3s16(lua_State *L, v3s16 p) { lua_createtable(L, 0, 3); lua_pushinteger(L, p.X); lua_setfield(L, -2, "x"); lua_pushinteger(L, p.Y); lua_setfield(L, -2, "y"); lua_pushinteger(L, p.Z); lua_setfield(L, -2, "z"); } v3s16 read_v3s16(lua_State *L, int index) { // Correct rounding at <0 v3d pf = read_v3d(L, index); return doubleToInt(pf, 1.0); } v3s16 check_v3s16(lua_State *L, int index) { // Correct rounding at <0 v3d pf = check_v3d(L, index); return doubleToInt(pf, 1.0); } bool read_color(lua_State *L, int index, video::SColor *color) { if (lua_istable(L, index)) { *color = read_ARGB8(L, index); } else if (lua_isnumber(L, index)) { color->set(lua_tonumber(L, index)); } else if (lua_isstring(L, index)) { video::SColor parsed_color; if (!parseColorString(lua_tostring(L, index), parsed_color, true)) return false; *color = parsed_color; } else { return false; } return true; } video::SColor read_ARGB8(lua_State *L, int index) { video::SColor color(0); CHECK_TYPE(index, "ARGB color", LUA_TTABLE); lua_getfield(L, index, "a"); color.setAlpha(lua_isnumber(L, -1) ? lua_tonumber(L, -1) : 0xFF); lua_pop(L, 1); lua_getfield(L, index, "r"); color.setRed(lua_tonumber(L, -1)); lua_pop(L, 1); lua_getfield(L, index, "g"); color.setGreen(lua_tonumber(L, -1)); lua_pop(L, 1); lua_getfield(L, index, "b"); color.setBlue(lua_tonumber(L, -1)); lua_pop(L, 1); return color; } bool is_color_table(lua_State *L, int index) { // Check whole table in case of missing ColorSpec keys: // This check does not remove the checked value from the stack. // Only update the value if we know we have a valid ColorSpec key pair. if (!lua_istable(L, index)) return false; bool is_color_table = false; lua_getfield(L, index, "r"); if (!is_color_table) is_color_table = lua_isnumber(L, -1); lua_getfield(L, index, "g"); if (!is_color_table) is_color_table = lua_isnumber(L, -1); lua_getfield(L, index, "b"); if (!is_color_table) is_color_table = lua_isnumber(L, -1); lua_pop(L, 3); // b, g, r values return is_color_table; } aabb3f read_aabb3f(lua_State *L, int index, f32 scale) { aabb3f box; if(lua_istable(L, index)){ lua_rawgeti(L, index, 1); box.MinEdge.X = lua_tonumber(L, -1) * scale; lua_pop(L, 1); lua_rawgeti(L, index, 2); box.MinEdge.Y = lua_tonumber(L, -1) * scale; lua_pop(L, 1); lua_rawgeti(L, index, 3); box.MinEdge.Z = lua_tonumber(L, -1) * scale; lua_pop(L, 1); lua_rawgeti(L, index, 4); box.MaxEdge.X = lua_tonumber(L, -1) * scale; lua_pop(L, 1); lua_rawgeti(L, index, 5); box.MaxEdge.Y = lua_tonumber(L, -1) * scale; lua_pop(L, 1); lua_rawgeti(L, index, 6); box.MaxEdge.Z = lua_tonumber(L, -1) * scale; lua_pop(L, 1); } box.repair(); return box; } void push_aabb3f(lua_State *L, aabb3f box) { lua_createtable(L, 6, 0); lua_pushnumber(L, box.MinEdge.X); lua_rawseti(L, -2, 1); lua_pushnumber(L, box.MinEdge.Y); lua_rawseti(L, -2, 2); lua_pushnumber(L, box.MinEdge.Z); lua_rawseti(L, -2, 3); lua_pushnumber(L, box.MaxEdge.X); lua_rawseti(L, -2, 4); lua_pushnumber(L, box.MaxEdge.Y); lua_rawseti(L, -2, 5); lua_pushnumber(L, box.MaxEdge.Z); lua_rawseti(L, -2, 6); } std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale) { std::vector<aabb3f> boxes; if(lua_istable(L, index)){ int n = lua_objlen(L, index); // Check if it's a single box or a list of boxes bool possibly_single_box = (n == 6); for(int i = 1; i <= n && possibly_single_box; i++){ lua_rawgeti(L, index, i); if(!lua_isnumber(L, -1)) possibly_single_box = false; lua_pop(L, 1); } if(possibly_single_box){ // Read a single box boxes.push_back(read_aabb3f(L, index, scale)); } else { // Read a list of boxes for(int i = 1; i <= n; i++){ lua_rawgeti(L, index, i); boxes.push_back(read_aabb3f(L, -1, scale)); lua_pop(L, 1); } } } return boxes; } size_t read_stringlist(lua_State *L, int index, std::vector<std::string> *result) { if (index < 0) index = lua_gettop(L) + 1 + index; size_t num_strings = 0; if (lua_istable(L, index)) { lua_pushnil(L); while (lua_next(L, index)) { if (lua_isstring(L, -1)) { result->push_back(lua_tostring(L, -1)); num_strings++; } lua_pop(L, 1); } } else if (lua_isstring(L, index)) { result->push_back(lua_tostring(L, index)); num_strings++; } return num_strings; } /* Table field getters */ #if defined(__MINGW32__) && !defined(__MINGW64__) /* MinGW 32-bit somehow crashes in the std::set destructor when this * variable is thread-local, so just don't do that. */ static std::set<u64> warned_msgs; #endif bool check_field_or_nil(lua_State *L, int index, int type, const char *fieldname) { #if !defined(__MINGW32__) || defined(__MINGW64__) thread_local std::set<u64> warned_msgs; #endif int t = lua_type(L, index); if (t == LUA_TNIL) return false; if (t == type) return true; // Check coercion types if (type == LUA_TNUMBER) { if (lua_isnumber(L, index)) return true; } else if (type == LUA_TSTRING) { if (lua_isstring(L, index)) return true; } // Types mismatch. Log unique line. std::string backtrace = std::string("Invalid field ") + fieldname + " (expected " + lua_typename(L, type) + " got " + lua_typename(L, t) + ").\n" + script_get_backtrace(L); u64 hash = murmur_hash_64_ua(backtrace.data(), backtrace.length(), 0xBADBABE); if (warned_msgs.find(hash) == warned_msgs.end()) { errorstream << backtrace << std::endl; warned_msgs.insert(hash); } return false; } bool getstringfield(lua_State *L, int table, const char *fieldname, std::string &result) { lua_getfield(L, table, fieldname); bool got = false; if (check_field_or_nil(L, -1, LUA_TSTRING, fieldname)) { size_t len = 0; const char *ptr = lua_tolstring(L, -1, &len); if (ptr) { result.assign(ptr, len); got = true; } } lua_pop(L, 1); return got; } bool getfloatfield(lua_State *L, int table, const char *fieldname, float &result) { lua_getfield(L, table, fieldname); bool got = false; if (check_field_or_nil(L, -1, LUA_TNUMBER, fieldname)) { result = lua_tonumber(L, -1); got = true; } lua_pop(L, 1); return got; } bool getboolfield(lua_State *L, int table, const char *fieldname, bool &result) { lua_getfield(L, table, fieldname); bool got = false; if (check_field_or_nil(L, -1, LUA_TBOOLEAN, fieldname)){ result = lua_toboolean(L, -1); got = true; } lua_pop(L, 1); return got; } size_t getstringlistfield(lua_State *L, int table, const char *fieldname, std::vector<std::string> *result) { lua_getfield(L, table, fieldname); size_t num_strings_read = read_stringlist(L, -1, result); lua_pop(L, 1); return num_strings_read; } std::string getstringfield_default(lua_State *L, int table, const char *fieldname, const std::string &default_) { std::string result = default_; getstringfield(L, table, fieldname, result); return result; } int getintfield_default(lua_State *L, int table, const char *fieldname, int default_) { int result = default_; getintfield(L, table, fieldname, result); return result; } float getfloatfield_default(lua_State *L, int table, const char *fieldname, float default_) { float result = default_; getfloatfield(L, table, fieldname, result); return result; } bool getboolfield_default(lua_State *L, int table, const char *fieldname, bool default_) { bool result = default_; getboolfield(L, table, fieldname, result); return result; } v3s16 getv3s16field_default(lua_State *L, int table, const char *fieldname, v3s16 default_) { getv3intfield(L, table, fieldname, default_); return default_; } void setstringfield(lua_State *L, int table, const char *fieldname, const std::string &value) { lua_pushlstring(L, value.c_str(), value.length()); if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } void setintfield(lua_State *L, int table, const char *fieldname, int value) { lua_pushinteger(L, value); if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } void setfloatfield(lua_State *L, int table, const char *fieldname, float value) { lua_pushnumber(L, value); if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } void setboolfield(lua_State *L, int table, const char *fieldname, bool value) { lua_pushboolean(L, value); if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } //// //// Array table slices //// size_t write_array_slice_float( lua_State *L, int table_index, float *data, v3u16 data_size, v3u16 slice_offset, v3u16 slice_size) { v3u16 pmin, pmax(data_size); if (slice_offset.X > 0) { slice_offset.X--; pmin.X = slice_offset.X; pmax.X = MYMIN(slice_offset.X + slice_size.X, data_size.X); } if (slice_offset.Y > 0) { slice_offset.Y--; pmin.Y = slice_offset.Y; pmax.Y = MYMIN(slice_offset.Y + slice_size.Y, data_size.Y); } if (slice_offset.Z > 0) { slice_offset.Z--; pmin.Z = slice_offset.Z; pmax.Z = MYMIN(slice_offset.Z + slice_size.Z, data_size.Z); } const u32 ystride = data_size.X; const u32 zstride = data_size.X * data_size.Y; u32 elem_index = 1; for (u32 z = pmin.Z; z != pmax.Z; z++) for (u32 y = pmin.Y; y != pmax.Y; y++) for (u32 x = pmin.X; x != pmax.X; x++) { u32 i = z * zstride + y * ystride + x; lua_pushnumber(L, data[i]); lua_rawseti(L, table_index, elem_index); elem_index++; } return elem_index - 1; }