]> git.lizzy.rs Git - minetest.git/blob - src/util/string.cpp
Fix segfaults caused by the Environment not being initialized yet
[minetest.git] / src / util / string.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "string.h"
21 #include "pointer.h"
22 #include "numeric.h"
23 #include "log.h"
24
25 #include "hex.h"
26 #include "../porting.h"
27
28 #include <sstream>
29 #include <iomanip>
30 #include <map>
31
32 #ifndef _WIN32
33         #include <iconv.h>
34 #else
35         #define _WIN32_WINNT 0x0501
36         #include <windows.h>
37 #endif
38
39 #if defined(_ICONV_H_) && (defined(__FreeBSD__) || defined(__NetBSD__) || \
40         defined(__OpenBSD__) || defined(__DragonFly__))
41         #define BSD_ICONV_USED
42 #endif
43
44 static bool parseHexColorString(const std::string &value, video::SColor &color);
45 static bool parseNamedColorString(const std::string &value, video::SColor &color);
46
47 #ifndef _WIN32
48
49 bool convert(const char *to, const char *from, char *outbuf,
50                 size_t outbuf_size, char *inbuf, size_t inbuf_size)
51 {
52         iconv_t cd = iconv_open(to, from);
53
54 #ifdef BSD_ICONV_USED
55         const char *inbuf_ptr = inbuf;
56 #else
57         char *inbuf_ptr = inbuf;
58 #endif
59
60         char *outbuf_ptr = outbuf;
61
62         size_t *inbuf_left_ptr = &inbuf_size;
63         size_t *outbuf_left_ptr = &outbuf_size;
64
65         size_t old_size = inbuf_size;
66         while (inbuf_size > 0) {
67                 iconv(cd, &inbuf_ptr, inbuf_left_ptr, &outbuf_ptr, outbuf_left_ptr);
68                 if (inbuf_size == old_size) {
69                         iconv_close(cd);
70                         return false;
71                 }
72                 old_size = inbuf_size;
73         }
74
75         iconv_close(cd);
76         return true;
77 }
78
79 std::wstring utf8_to_wide(const std::string &input)
80 {
81         size_t inbuf_size = input.length() + 1;
82         // maximum possible size, every character is sizeof(wchar_t) bytes
83         size_t outbuf_size = (input.length() + 1) * sizeof(wchar_t);
84
85         char *inbuf = new char[inbuf_size];
86         memcpy(inbuf, input.c_str(), inbuf_size);
87         char *outbuf = new char[outbuf_size];
88         memset(outbuf, 0, outbuf_size);
89
90         if (!convert("WCHAR_T", "UTF-8", outbuf, outbuf_size, inbuf, inbuf_size)) {
91                 infostream << "Couldn't convert UTF-8 string 0x" << hex_encode(input)
92                         << " into wstring" << std::endl;
93                 delete[] inbuf;
94                 delete[] outbuf;
95                 return L"<invalid UTF-8 string>";
96         }
97         std::wstring out((wchar_t *)outbuf);
98
99         delete[] inbuf;
100         delete[] outbuf;
101
102         return out;
103 }
104
105 std::string wide_to_utf8(const std::wstring &input)
106 {
107         size_t inbuf_size = (input.length() + 1) * sizeof(wchar_t);
108         // maximum possible size: utf-8 encodes codepoints using 1 up to 6 bytes
109         size_t outbuf_size = (input.length() + 1) * 6;
110
111         char *inbuf = new char[inbuf_size];
112         memcpy(inbuf, input.c_str(), inbuf_size);
113         char *outbuf = new char[outbuf_size];
114         memset(outbuf, 0, outbuf_size);
115
116         if (!convert("UTF-8", "WCHAR_T", outbuf, outbuf_size, inbuf, inbuf_size)) {
117                 infostream << "Couldn't convert wstring 0x" << hex_encode(inbuf, inbuf_size)
118                         << " into UTF-8 string" << std::endl;
119                 delete[] inbuf;
120                 delete[] outbuf;
121                 return "<invalid wstring>";
122         }
123         std::string out(outbuf);
124
125         delete[] inbuf;
126         delete[] outbuf;
127
128         return out;
129 }
130
131 #else // _WIN32
132
133 std::wstring utf8_to_wide(const std::string &input)
134 {
135         size_t outbuf_size = input.size() + 1;
136         wchar_t *outbuf = new wchar_t[outbuf_size];
137         memset(outbuf, 0, outbuf_size * sizeof(wchar_t));
138         MultiByteToWideChar(CP_UTF8, 0, input.c_str(), input.size(),
139                 outbuf, outbuf_size);
140         std::wstring out(outbuf);
141         delete[] outbuf;
142         return out;
143 }
144
145 std::string wide_to_utf8(const std::wstring &input)
146 {
147         size_t outbuf_size = (input.size() + 1) * 6;
148         char *outbuf = new char[outbuf_size];
149         memset(outbuf, 0, outbuf_size);
150         WideCharToMultiByte(CP_UTF8, 0, input.c_str(), input.size(),
151                 outbuf, outbuf_size, NULL, NULL);
152         std::string out(outbuf);
153         delete[] outbuf;
154         return out;
155 }
156
157 #endif // _WIN32
158
159 wchar_t *utf8_to_wide_c(const char *str)
160 {
161         std::wstring ret = utf8_to_wide(std::string(str)).c_str();
162         size_t len = ret.length();
163         wchar_t *ret_c = new wchar_t[len + 1];
164         memset(ret_c, 0, (len + 1) * sizeof(wchar_t));
165         memcpy(ret_c, ret.c_str(), len * sizeof(wchar_t));
166         return ret_c;
167 }
168
169 // You must free the returned string!
170 // The returned string is allocated using new
171 wchar_t *narrow_to_wide_c(const char *str)
172 {
173         wchar_t *nstr = NULL;
174 #if defined(_WIN32)
175         int nResult = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) str, -1, 0, 0);
176         if (nResult == 0) {
177                 errorstream<<"gettext: MultiByteToWideChar returned null"<<std::endl;
178         } else {
179                 nstr = new wchar_t[nResult];
180                 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) str, -1, (WCHAR *) nstr, nResult);
181         }
182 #else
183         size_t len = strlen(str);
184         nstr = new wchar_t[len + 1];
185
186         std::wstring intermediate = narrow_to_wide(str);
187         memset(nstr, 0, (len + 1) * sizeof(wchar_t));
188         memcpy(nstr, intermediate.c_str(), len * sizeof(wchar_t));
189 #endif
190
191         return nstr;
192 }
193
194
195 #ifdef __ANDROID__
196
197 const wchar_t* wide_chars =
198         L" !\"#$%&'()*+,-./0123456789:;<=>?@"
199         L"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`"
200         L"abcdefghijklmnopqrstuvwxyz{|}~";
201
202 int wctomb(char *s, wchar_t wc)
203 {
204         for (unsigned int j = 0; j < (sizeof(wide_chars)/sizeof(wchar_t));j++) {
205                 if (wc == wide_chars[j]) {
206                         *s = (char) (j+32);
207                         return 1;
208                 }
209                 else if (wc == L'\n') {
210                         *s = '\n';
211                         return 1;
212                 }
213         }
214         return -1;
215 }
216
217 int mbtowc(wchar_t *pwc, const char *s, size_t n)
218 {
219         std::wstring intermediate = narrow_to_wide(s);
220
221         if (intermediate.length() > 0) {
222                 *pwc = intermediate[0];
223                 return 1;
224         }
225         else {
226                 return -1;
227         }
228 }
229
230 std::wstring narrow_to_wide(const std::string &mbs) {
231         size_t wcl = mbs.size();
232
233         std::wstring retval = L"";
234
235         for (unsigned int i = 0; i < wcl; i++) {
236                 if (((unsigned char) mbs[i] >31) &&
237                  ((unsigned char) mbs[i] < 127)) {
238
239                         retval += wide_chars[(unsigned char) mbs[i] -32];
240                 }
241                 //handle newline
242                 else if (mbs[i] == '\n') {
243                         retval += L'\n';
244                 }
245         }
246
247         return retval;
248 }
249
250 #else // not Android
251
252 std::wstring narrow_to_wide(const std::string &mbs)
253 {
254         size_t wcl = mbs.size();
255         Buffer<wchar_t> wcs(wcl + 1);
256         size_t len = mbstowcs(*wcs, mbs.c_str(), wcl);
257         if (len == (size_t)(-1))
258                 return L"<invalid multibyte string>";
259         wcs[len] = 0;
260         return *wcs;
261 }
262
263 #endif
264
265 #ifdef __ANDROID__
266
267 std::string wide_to_narrow(const std::wstring &wcs) {
268         size_t mbl = wcs.size()*4;
269
270         std::string retval = "";
271         for (unsigned int i = 0; i < wcs.size(); i++) {
272                 wchar_t char1 = (wchar_t) wcs[i];
273
274                 if (char1 == L'\n') {
275                         retval += '\n';
276                         continue;
277                 }
278
279                 for (unsigned int j = 0; j < wcslen(wide_chars);j++) {
280                         wchar_t char2 = (wchar_t) wide_chars[j];
281
282                         if (char1 == char2) {
283                                 char toadd = (j+32);
284                                 retval += toadd;
285                                 break;
286                         }
287                 }
288         }
289
290         return retval;
291 }
292
293 #else // not Android
294
295 std::string wide_to_narrow(const std::wstring &wcs)
296 {
297         size_t mbl = wcs.size() * 4;
298         SharedBuffer<char> mbs(mbl+1);
299         size_t len = wcstombs(*mbs, wcs.c_str(), mbl);
300         if (len == (size_t)(-1))
301                 return "Character conversion failed!";
302         else
303                 mbs[len] = 0;
304         return *mbs;
305 }
306
307 #endif
308
309 std::string urlencode(std::string str)
310 {
311         // Encodes non-unreserved URI characters by a percent sign
312         // followed by two hex digits. See RFC 3986, section 2.3.
313         static const char url_hex_chars[] = "0123456789ABCDEF";
314         std::ostringstream oss(std::ios::binary);
315         for (u32 i = 0; i < str.size(); i++) {
316                 unsigned char c = str[i];
317                 if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~')
318                         oss << c;
319                 else
320                         oss << "%"
321                                 << url_hex_chars[(c & 0xf0) >> 4]
322                                 << url_hex_chars[c & 0x0f];
323         }
324         return oss.str();
325 }
326
327 std::string urldecode(std::string str)
328 {
329         // Inverse of urlencode
330         std::ostringstream oss(std::ios::binary);
331         for (u32 i = 0; i < str.size(); i++) {
332                 unsigned char highvalue, lowvalue;
333                 if (str[i] == '%' &&
334                                 hex_digit_decode(str[i+1], highvalue) &&
335                                 hex_digit_decode(str[i+2], lowvalue)) {
336                         oss << (char) ((highvalue << 4) | lowvalue);
337                         i += 2;
338                 }
339                 else
340                         oss << str[i];
341         }
342         return oss.str();
343 }
344
345 u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask)
346 {
347         u32 result = 0, mask = 0;
348         char *s = &str[0];
349         char *flagstr, *strpos = NULL;
350
351         while ((flagstr = strtok_r(s, ",", &strpos))) {
352                 s = NULL;
353
354                 while (*flagstr == ' ' || *flagstr == '\t')
355                         flagstr++;
356
357                 bool flagset = true;
358                 if (!strncasecmp(flagstr, "no", 2)) {
359                         flagset = false;
360                         flagstr += 2;
361                 }
362
363                 for (int i = 0; flagdesc[i].name; i++) {
364                         if (!strcasecmp(flagstr, flagdesc[i].name)) {
365                                 mask |= flagdesc[i].flag;
366                                 if (flagset)
367                                         result |= flagdesc[i].flag;
368                                 break;
369                         }
370                 }
371         }
372
373         if (flagmask)
374                 *flagmask = mask;
375
376         return result;
377 }
378
379 std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask)
380 {
381         std::string result;
382
383         for (int i = 0; flagdesc[i].name; i++) {
384                 if (flagmask & flagdesc[i].flag) {
385                         if (!(flags & flagdesc[i].flag))
386                                 result += "no";
387
388                         result += flagdesc[i].name;
389                         result += ", ";
390                 }
391         }
392
393         size_t len = result.length();
394         if (len >= 2)
395                 result.erase(len - 2, 2);
396
397         return result;
398 }
399
400 size_t mystrlcpy(char *dst, const char *src, size_t size)
401 {
402         size_t srclen  = strlen(src) + 1;
403         size_t copylen = MYMIN(srclen, size);
404
405         if (copylen > 0) {
406                 memcpy(dst, src, copylen);
407                 dst[copylen - 1] = '\0';
408         }
409
410         return srclen;
411 }
412
413 char *mystrtok_r(char *s, const char *sep, char **lasts)
414 {
415         char *t;
416
417         if (!s)
418                 s = *lasts;
419
420         while (*s && strchr(sep, *s))
421                 s++;
422
423         if (!*s)
424                 return NULL;
425
426         t = s;
427         while (*t) {
428                 if (strchr(sep, *t)) {
429                         *t++ = '\0';
430                         break;
431                 }
432                 t++;
433         }
434
435         *lasts = t;
436         return s;
437 }
438
439 u64 read_seed(const char *str)
440 {
441         char *endptr;
442         u64 num;
443
444         if (str[0] == '0' && str[1] == 'x')
445                 num = strtoull(str, &endptr, 16);
446         else
447                 num = strtoull(str, &endptr, 10);
448
449         if (*endptr)
450                 num = murmur_hash_64_ua(str, (int)strlen(str), 0x1337);
451
452         return num;
453 }
454
455 bool parseColorString(const std::string &value, video::SColor &color, bool quiet)
456 {
457         bool success;
458
459         if (value[0] == '#')
460                 success = parseHexColorString(value, color);
461         else
462                 success = parseNamedColorString(value, color);
463
464         if (!success && !quiet)
465                 errorstream << "Invalid color: \"" << value << "\"" << std::endl;
466
467         return success;
468 }
469
470 static bool parseHexColorString(const std::string &value, video::SColor &color)
471 {
472         unsigned char components[] = { 0x00, 0x00, 0x00, 0xff }; // R,G,B,A
473
474         if (value[0] != '#')
475                 return false;
476
477         size_t len = value.size();
478         bool short_form;
479
480         if (len == 9 || len == 7) // #RRGGBBAA or #RRGGBB
481                 short_form = false;
482         else if (len == 5 || len == 4) // #RGBA or #RGB
483                 short_form = true;
484         else
485                 return false;
486
487         bool success = true;
488
489         for (size_t pos = 1, cc = 0; pos < len; pos++, cc++) {
490                 assert(cc < sizeof components / sizeof components[0]);
491                 if (short_form) {
492                         unsigned char d;
493                         if (!hex_digit_decode(value[pos], d)) {
494                                 success = false;
495                                 break;
496                         }
497                         components[cc] = (d & 0xf) << 4 | (d & 0xf);
498                 } else {
499                         unsigned char d1, d2;
500                         if (!hex_digit_decode(value[pos], d1) ||
501                                         !hex_digit_decode(value[pos+1], d2)) {
502                                 success = false;
503                                 break;
504                         }
505                         components[cc] = (d1 & 0xf) << 4 | (d2 & 0xf);
506                         pos++;  // skip the second digit -- it's already used
507                 }
508         }
509
510         if (success) {
511                 color.setRed(components[0]);
512                 color.setGreen(components[1]);
513                 color.setBlue(components[2]);
514                 color.setAlpha(components[3]);
515         }
516
517         return success;
518 }
519
520 struct ColorContainer {
521         ColorContainer();
522         std::map<const std::string, u32> colors;
523 };
524
525 ColorContainer::ColorContainer()
526 {
527         colors["aliceblue"]              = 0xf0f8ff;
528         colors["antiquewhite"]           = 0xfaebd7;
529         colors["aqua"]                   = 0x00ffff;
530         colors["aquamarine"]             = 0x7fffd4;
531         colors["azure"]                  = 0xf0ffff;
532         colors["beige"]                  = 0xf5f5dc;
533         colors["bisque"]                 = 0xffe4c4;
534         colors["black"]                  = 00000000;
535         colors["blanchedalmond"]         = 0xffebcd;
536         colors["blue"]                   = 0x0000ff;
537         colors["blueviolet"]             = 0x8a2be2;
538         colors["brown"]                  = 0xa52a2a;
539         colors["burlywood"]              = 0xdeb887;
540         colors["cadetblue"]              = 0x5f9ea0;
541         colors["chartreuse"]             = 0x7fff00;
542         colors["chocolate"]              = 0xd2691e;
543         colors["coral"]                  = 0xff7f50;
544         colors["cornflowerblue"]         = 0x6495ed;
545         colors["cornsilk"]               = 0xfff8dc;
546         colors["crimson"]                = 0xdc143c;
547         colors["cyan"]                   = 0x00ffff;
548         colors["darkblue"]               = 0x00008b;
549         colors["darkcyan"]               = 0x008b8b;
550         colors["darkgoldenrod"]          = 0xb8860b;
551         colors["darkgray"]               = 0xa9a9a9;
552         colors["darkgreen"]              = 0x006400;
553         colors["darkkhaki"]              = 0xbdb76b;
554         colors["darkmagenta"]            = 0x8b008b;
555         colors["darkolivegreen"]         = 0x556b2f;
556         colors["darkorange"]             = 0xff8c00;
557         colors["darkorchid"]             = 0x9932cc;
558         colors["darkred"]                = 0x8b0000;
559         colors["darksalmon"]             = 0xe9967a;
560         colors["darkseagreen"]           = 0x8fbc8f;
561         colors["darkslateblue"]          = 0x483d8b;
562         colors["darkslategray"]          = 0x2f4f4f;
563         colors["darkturquoise"]          = 0x00ced1;
564         colors["darkviolet"]             = 0x9400d3;
565         colors["deeppink"]               = 0xff1493;
566         colors["deepskyblue"]            = 0x00bfff;
567         colors["dimgray"]                = 0x696969;
568         colors["dodgerblue"]             = 0x1e90ff;
569         colors["firebrick"]              = 0xb22222;
570         colors["floralwhite"]            = 0xfffaf0;
571         colors["forestgreen"]            = 0x228b22;
572         colors["fuchsia"]                = 0xff00ff;
573         colors["gainsboro"]              = 0xdcdcdc;
574         colors["ghostwhite"]             = 0xf8f8ff;
575         colors["gold"]                   = 0xffd700;
576         colors["goldenrod"]              = 0xdaa520;
577         colors["gray"]                   = 0x808080;
578         colors["green"]                  = 0x008000;
579         colors["greenyellow"]            = 0xadff2f;
580         colors["honeydew"]               = 0xf0fff0;
581         colors["hotpink"]                = 0xff69b4;
582         colors["indianred "]             = 0xcd5c5c;
583         colors["indigo "]                = 0x4b0082;
584         colors["ivory"]                  = 0xfffff0;
585         colors["khaki"]                  = 0xf0e68c;
586         colors["lavender"]               = 0xe6e6fa;
587         colors["lavenderblush"]          = 0xfff0f5;
588         colors["lawngreen"]              = 0x7cfc00;
589         colors["lemonchiffon"]           = 0xfffacd;
590         colors["lightblue"]              = 0xadd8e6;
591         colors["lightcoral"]             = 0xf08080;
592         colors["lightcyan"]              = 0xe0ffff;
593         colors["lightgoldenrodyellow"]   = 0xfafad2;
594         colors["lightgray"]              = 0xd3d3d3;
595         colors["lightgreen"]             = 0x90ee90;
596         colors["lightpink"]              = 0xffb6c1;
597         colors["lightsalmon"]            = 0xffa07a;
598         colors["lightseagreen"]          = 0x20b2aa;
599         colors["lightskyblue"]           = 0x87cefa;
600         colors["lightslategray"]         = 0x778899;
601         colors["lightsteelblue"]         = 0xb0c4de;
602         colors["lightyellow"]            = 0xffffe0;
603         colors["lime"]                   = 0x00ff00;
604         colors["limegreen"]              = 0x32cd32;
605         colors["linen"]                  = 0xfaf0e6;
606         colors["magenta"]                = 0xff00ff;
607         colors["maroon"]                 = 0x800000;
608         colors["mediumaquamarine"]       = 0x66cdaa;
609         colors["mediumblue"]             = 0x0000cd;
610         colors["mediumorchid"]           = 0xba55d3;
611         colors["mediumpurple"]           = 0x9370db;
612         colors["mediumseagreen"]         = 0x3cb371;
613         colors["mediumslateblue"]        = 0x7b68ee;
614         colors["mediumspringgreen"]      = 0x00fa9a;
615         colors["mediumturquoise"]        = 0x48d1cc;
616         colors["mediumvioletred"]        = 0xc71585;
617         colors["midnightblue"]           = 0x191970;
618         colors["mintcream"]              = 0xf5fffa;
619         colors["mistyrose"]              = 0xffe4e1;
620         colors["moccasin"]               = 0xffe4b5;
621         colors["navajowhite"]            = 0xffdead;
622         colors["navy"]                   = 0x000080;
623         colors["oldlace"]                = 0xfdf5e6;
624         colors["olive"]                  = 0x808000;
625         colors["olivedrab"]              = 0x6b8e23;
626         colors["orange"]                 = 0xffa500;
627         colors["orangered"]              = 0xff4500;
628         colors["orchid"]                 = 0xda70d6;
629         colors["palegoldenrod"]          = 0xeee8aa;
630         colors["palegreen"]              = 0x98fb98;
631         colors["paleturquoise"]          = 0xafeeee;
632         colors["palevioletred"]          = 0xdb7093;
633         colors["papayawhip"]             = 0xffefd5;
634         colors["peachpuff"]              = 0xffdab9;
635         colors["peru"]                   = 0xcd853f;
636         colors["pink"]                   = 0xffc0cb;
637         colors["plum"]                   = 0xdda0dd;
638         colors["powderblue"]             = 0xb0e0e6;
639         colors["purple"]                 = 0x800080;
640         colors["red"]                    = 0xff0000;
641         colors["rosybrown"]              = 0xbc8f8f;
642         colors["royalblue"]              = 0x4169e1;
643         colors["saddlebrown"]            = 0x8b4513;
644         colors["salmon"]                 = 0xfa8072;
645         colors["sandybrown"]             = 0xf4a460;
646         colors["seagreen"]               = 0x2e8b57;
647         colors["seashell"]               = 0xfff5ee;
648         colors["sienna"]                 = 0xa0522d;
649         colors["silver"]                 = 0xc0c0c0;
650         colors["skyblue"]                = 0x87ceeb;
651         colors["slateblue"]              = 0x6a5acd;
652         colors["slategray"]              = 0x708090;
653         colors["snow"]                   = 0xfffafa;
654         colors["springgreen"]            = 0x00ff7f;
655         colors["steelblue"]              = 0x4682b4;
656         colors["tan"]                    = 0xd2b48c;
657         colors["teal"]                   = 0x008080;
658         colors["thistle"]                = 0xd8bfd8;
659         colors["tomato"]                 = 0xff6347;
660         colors["turquoise"]              = 0x40e0d0;
661         colors["violet"]                 = 0xee82ee;
662         colors["wheat"]                  = 0xf5deb3;
663         colors["white"]                  = 0xffffff;
664         colors["whitesmoke"]             = 0xf5f5f5;
665         colors["yellow"]                 = 0xffff00;
666         colors["yellowgreen"]            = 0x9acd32;
667
668 }
669
670 static const ColorContainer named_colors;
671
672 static bool parseNamedColorString(const std::string &value, video::SColor &color)
673 {
674         std::string color_name;
675         std::string alpha_string;
676
677         /* If the string has a # in it, assume this is the start of a specified
678          * alpha value (if it isn't the string is invalid and the error will be
679          * caught later on, either because the color name won't be found or the
680          * alpha value will fail conversion)
681          */
682         size_t alpha_pos = value.find('#');
683         if (alpha_pos != std::string::npos) {
684                 color_name = value.substr(0, alpha_pos);
685                 alpha_string = value.substr(alpha_pos + 1);
686         } else {
687                 color_name = value;
688         }
689
690         color_name = lowercase(value);
691
692         std::map<const std::string, unsigned>::const_iterator it;
693         it = named_colors.colors.find(color_name);
694         if (it == named_colors.colors.end())
695                 return false;
696
697         u32 color_temp = it->second;
698
699         /* An empty string for alpha is ok (none of the color table entries
700          * have an alpha value either). Color strings without an alpha specified
701          * are interpreted as fully opaque
702          *
703          * For named colors the supplied alpha string (representing a hex value)
704          * must be exactly two digits. For example:  colorname#08
705          */
706         if (!alpha_string.empty()) {
707                 if (alpha_string.length() != 2)
708                         return false;
709
710                 unsigned char d1, d2;
711                 if (!hex_digit_decode(alpha_string.at(0), d1)
712                                 || !hex_digit_decode(alpha_string.at(1), d2))
713                         return false;
714                 color_temp |= ((d1 & 0xf) << 4 | (d2 & 0xf)) << 24;
715         } else {
716                 color_temp |= 0xff << 24;  // Fully opaque
717         }
718
719         color = video::SColor(color_temp);
720
721         return true;
722 }
723
724 void str_replace(std::string &str, char from, char to)
725 {
726         std::replace(str.begin(), str.end(), from, to);
727 }