]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/lib/string.qh
Add string logic table
[xonotic/xonotic-data.pk3dir.git] / qcsrc / lib / string.qh
1 #pragma once
2
3 #include "nil.qh"
4 #include "sort.qh"
5 #include "oo.qh"
6
7 // string logic
8 //
9 // true: is truthy
10 // == "": is equal to ""
11 // is "": has the same string index as the string constant ""
12 // strunzone: can be strunzoned
13 //
14 // |              | true | == "" | is "" | strunzone |
15 // | :----------: | :--: | :---: | :---: | :-------: |
16 // | nil          |      | yes   |       |           |
17 // | strcat(nil)  | yes  | yes   |       |           |
18 // | strzone(nil) | yes  | yes   |       | yes       |
19 // | ""           | yes  | yes   | yes   |           |
20 // | strcat("")   | yes  | yes   |       |           |
21 // | strzone("")  | yes  | yes   |       | yes       |
22 // | "s"          | yes  |       |       |           |
23 // | strcat("s")  | yes  |       |       |           |
24 // | strzone("s") | yes  |       |       | yes       |
25
26 #ifdef CSQC
27         float stringwidth_colors(string s, vector theSize)
28         {
29                 return stringwidth_builtin(s, true, theSize);
30         }
31
32         float stringwidth_nocolors(string s, vector theSize)
33         {
34                 return stringwidth_builtin(s, false, theSize);
35         }
36 #endif
37 #ifdef MENUQC
38         float stringwidth_colors(string s, vector theSize)
39         {
40                 return stringwidth(s, true, theSize);
41         }
42
43         float stringwidth_nocolors(string s, vector theSize)
44         {
45                 return stringwidth(s, false, theSize);
46         }
47 #endif
48
49 #define strcpy(this, s) MACRO_BEGIN \
50         if (this) { \
51                 strunzone(this); \
52         } \
53         this = strzone(s); \
54 MACRO_END
55
56 ERASEABLE
57 string seconds_tostring(float sec)
58 {
59         float minutes = floor(sec / 60);
60         sec -= minutes * 60;
61         return sprintf("%d:%02d", minutes, sec);
62 }
63
64 ERASEABLE
65 string format_time(float seconds)
66 {
67         seconds = floor(seconds + 0.5);
68         float days = floor(seconds / 864000);
69         seconds -= days * 864000;
70         float hours = floor(seconds / 36000);
71         seconds -= hours * 36000;
72         float minutes = floor(seconds / 600);
73         seconds -= minutes * 600;
74         if (days > 0) return sprintf(_("%d days, %02d:%02d:%02d"), days, hours, minutes, seconds);
75         else return sprintf(_("%02d:%02d:%02d"), hours, minutes, seconds);
76 }
77
78 ERASEABLE
79 string mmsss(float tenths)
80 {
81         tenths = floor(tenths + 0.5);
82         float minutes = floor(tenths / 600);
83         tenths -= minutes * 600;
84         string s = ftos(1000 + tenths);
85         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 1));
86 }
87
88 ERASEABLE
89 string mmssss(float hundredths)
90 {
91         hundredths = floor(hundredths + 0.5);
92         float minutes = floor(hundredths / 6000);
93         hundredths -= minutes * 6000;
94         string s = ftos(10000 + hundredths);
95         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 2));
96 }
97
98 int ColorTranslateMode;
99
100 ERASEABLE
101 string ColorTranslateRGB(string s)
102 {
103         return (ColorTranslateMode & 1) ? strdecolorize(s) : s;
104 }
105
106 #ifdef GAMEQC
107 // color code replace, place inside of sprintf and parse the string... defaults described as constants
108 // foreground/normal colors
109 string autocvar_hud_colorset_foreground_1 = "2"; // F1 - Green  // primary priority (important names, etc)
110 string autocvar_hud_colorset_foreground_2 = "3"; // F2 - Yellow // secondary priority (items, locations, numbers, etc)
111 string autocvar_hud_colorset_foreground_3 = "4"; // F3 - Blue   // tertiary priority or relatively inconsequential text
112 string autocvar_hud_colorset_foreground_4 = "1"; // F4 - Red    // notice/attention grabbing texting
113 // "kill" colors
114 string autocvar_hud_colorset_kill_1 = "1";       // K1 - Red    // "bad" or "dangerous" text (death messages against you, kill notifications, etc)
115 string autocvar_hud_colorset_kill_2 = "3";       // K2 - Yellow // similar to above, but less important... OR, a highlight out of above message type
116 string autocvar_hud_colorset_kill_3 = "4";       // K3 - Blue   // "good" or "beneficial" text (you fragging someone, etc)
117 // background color
118 string autocvar_hud_colorset_background = "7";   // BG - White // neutral/unimportant text
119
120 /** color code replace, place inside of sprintf and parse the string */
121 string CCR(string input)
122 {
123         // See the autocvar declarations in util.qh for default values
124
125         // foreground/normal colors
126         input = strreplace("^F1", strcat("^", autocvar_hud_colorset_foreground_1), input);
127         input = strreplace("^F2", strcat("^", autocvar_hud_colorset_foreground_2), input);
128         input = strreplace("^F3", strcat("^", autocvar_hud_colorset_foreground_3), input);
129         input = strreplace("^F4", strcat("^", autocvar_hud_colorset_foreground_4), input);
130
131         // "kill" colors
132         input = strreplace("^K1", strcat("^", autocvar_hud_colorset_kill_1), input);
133         input = strreplace("^K2", strcat("^", autocvar_hud_colorset_kill_2), input);
134         input = strreplace("^K3", strcat("^", autocvar_hud_colorset_kill_3), input);
135
136         // background colors
137         input = strreplace("^BG", strcat("^", autocvar_hud_colorset_background), input);
138         input = strreplace("^N", "^7", input);  // "none"-- reset to white...
139         return input;
140 }
141 #endif
142
143 #define startsWith(haystack, needle) (strstrofs(haystack, needle, 0) == 0)
144
145 ERASEABLE
146 bool startsWithNocase(string haystack, string needle)
147 {
148         return strcasecmp(substring(haystack, 0, strlen(needle)), needle) == 0;
149 }
150
151 noref string _endsWith_suffix;
152 #define endsWith(this, suffix) (_endsWith_suffix = suffix, substring(this, -strlen(_endsWith_suffix), -1) == _endsWith_suffix)
153
154 /** unzone the string, and return it as tempstring. Safe to be called on string_null */
155 ERASEABLE
156 string fstrunzone(string s)
157 {
158         if (!s) return s;
159         string sc = strcat(s, "");
160         strunzone(s);
161         return sc;
162 }
163
164 /** returns first word */
165 ERASEABLE
166 string car(string s)
167 {
168         int o = strstrofs(s, " ", 0);
169         if (o < 0) return s;
170         return substring(s, 0, o);
171 }
172
173 /** returns all but first word */
174 ERASEABLE
175 string cdr(string s)
176 {
177         int o = strstrofs(s, " ", 0);
178         if (o < 0) return string_null;
179         return substring(s, o + 1, strlen(s) - (o + 1));
180 }
181
182 ERASEABLE
183 string cons(string a, string b)
184 {
185         if (a == "") return b;
186         if (b == "") return a;
187         return strcat(a, " ", b);
188 }
189
190 ERASEABLE
191 string cons_mid(string a, string mid, string b)
192 {
193         if (a == "") return b;
194         if (b == "") return a;
195         return strcat(a, mid, b);
196 }
197
198 ERASEABLE
199 string substring_range(string s, float b, float e)
200 {
201         return substring(s, b, e - b);
202 }
203
204 ERASEABLE
205 string swapwords(string str, float i, float j)
206 {
207         float n;
208         string s1, s2, s3, s4, s5;
209         float si, ei, sj, ej, s0, en;
210         n = tokenizebyseparator(str, " ");  // must match g_maplist processing in ShuffleMaplist and "shuffle"
211         si = argv_start_index(i);
212         sj = argv_start_index(j);
213         ei = argv_end_index(i);
214         ej = argv_end_index(j);
215         s0 = argv_start_index(0);
216         en = argv_end_index(n - 1);
217         s1 = substring_range(str, s0, si);
218         s2 = substring_range(str, si, ei);
219         s3 = substring_range(str, ei, sj);
220         s4 = substring_range(str, sj, ej);
221         s5 = substring_range(str, ej, en);
222         return strcat(s1, s4, s3, s2, s5);
223 }
224
225 string _shufflewords_str;
226 ERASEABLE
227 void _shufflewords_swapfunc(float i, float j, entity pass)
228 {
229         _shufflewords_str = swapwords(_shufflewords_str, i, j);
230 }
231
232 ERASEABLE
233 string shufflewords(string str)
234 {
235         _shufflewords_str = str;
236         int n = tokenizebyseparator(str, " ");
237         shuffle(n, _shufflewords_swapfunc, NULL);
238         str = _shufflewords_str;
239         _shufflewords_str = string_null;
240         return str;
241 }
242
243 ERASEABLE
244 string unescape(string in)
245 {
246         in = strzone(in);  // but it doesn't seem to be necessary in my tests at least
247
248         int len = strlen(in);
249         string str = "";
250         for (int i = 0; i < len; ++i)
251         {
252                 string s = substring(in, i, 1);
253                 if (s == "\\")
254                 {
255                         s = substring(in, i + 1, 1);
256                         if (s == "n") str = strcat(str, "\n");
257                         else if (s == "\\") str = strcat(str, "\\");
258                         else str = strcat(str, substring(in, i, 2));
259                         ++i;
260                         continue;
261                 }
262                 str = strcat(str, s);
263         }
264         strunzone(in);
265         return str;
266 }
267
268 ERASEABLE
269 string strwords(string s, int w)
270 {
271         int endpos = 0;
272         for ( ; w && endpos >= 0; --w)
273                 endpos = strstrofs(s, " ", endpos + 1);
274         if (endpos < 0) return s;
275         return substring(s, 0, endpos);
276 }
277
278 #define strhasword(s, w) (strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0)
279
280 ERASEABLE
281 int u8_strsize(string s)
282 {
283         int l = 0;
284         for (int i = 0, c; (c = str2chr(s, i)) > 0; ++i, ++l)
285         {
286                 l += (c >= 0x80);
287                 l += (c >= 0x800);
288                 l += (c >= 0x10000);
289         }
290         return l;
291 }
292
293 //List of Unicode spaces: https://www.cs.tut.fi/~jkorpela/chars/spaces.html
294 ERASEABLE
295 bool isInvisibleString(string s)
296 {
297         s = strdecolorize(s);
298         bool utf8 = cvar("utf8_enable");
299         for (int i = 0, n = strlen(s); i < n; ++i)
300         {
301                 int c = str2chr(s, i);
302                 switch (c)
303                 {
304                         case 0:
305                         case 32:           // space
306                                 break;
307                         case 192:          // charmap space
308                                 if (!utf8) break;
309                                 return false;
310                         case 0xE000 + 192: // utf8 charmap space
311                         case 0x00A0: // NO-BREAK SPACE
312                         //case 0x1680: // OGHAM SPACE MARK
313                         case 0x180E: // MONGOLIAN VOWEL SEPARATOR
314                         case 0x2000: // EN QUAD
315                         case 0x2001: // EM QUAD
316                         case 0x2002: // EN SPACE
317                         case 0x2003: // EM SPACE
318                         case 0x2004: // THREE-PER-EM SPACE
319                         case 0x2005: // FOUR-PER-EM SPACE
320                         case 0x2006: // SIX-PER-EM SPACE
321                         case 0x2007: // FIGURE SPACE
322                         case 0x2008: // PUNCTUATION SPACE
323                         case 0x2009: // THIN SPACE
324                         case 0x200A: // HAIR SPACE
325                         case 0x200B: // ZERO WIDTH SPACE
326                         case 0x202F: // NARROW NO-BREAK SPACE
327                         case 0x205F: // MEDIUM MATHEMATICAL SPACE
328                         case 0x3000: // IDEOGRAPHIC SPACE
329                         case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE
330                                 if (utf8) break;
331                         default:
332                                 return false;
333                 }
334         }
335         return true;
336 }
337
338 // Multiline text file buffers
339
340 ERASEABLE
341 int buf_load(string pFilename)
342 {
343         int buf = buf_create();
344         if (buf < 0) return -1;
345         int fh = fopen(pFilename, FILE_READ);
346         if (fh < 0)
347         {
348                 buf_del(buf);
349                 return -1;
350         }
351         string l;
352         for (int i = 0; (l = fgets(fh)); ++i)
353                 bufstr_set(buf, i, l);
354         fclose(fh);
355         return buf;
356 }
357
358 ERASEABLE
359 void buf_save(float buf, string pFilename)
360 {
361         int fh = fopen(pFilename, FILE_WRITE);
362         if (fh < 0) error(strcat("Can't write buf to ", pFilename));
363         int n = buf_getsize(buf);
364         for (int i = 0; i < n; ++i)
365                 fputs(fh, strcat(bufstr_get(buf, i), "\n"));
366         fclose(fh);
367 }
368
369 /**
370  * converts a number to a string with the indicated number of decimals
371  */
372 ERASEABLE
373 string ftos_decimals(float number, int decimals)
374 {
375         // inhibit stupid negative zero
376         if (number == 0) number = 0;
377         return sprintf("%.*f", decimals, number);
378 }
379
380 /**
381  * converts a number to a string with the minimum number of decimals
382  */
383 ERASEABLE
384 string ftos_mindecimals(float number)
385 {
386         // inhibit stupid negative zero
387         if (number == 0) number = 0;
388         return sprintf("%.7g", number);
389 }
390
391 ERASEABLE
392 int vercmp_recursive(string v1, string v2)
393 {
394         int dot1 = strstrofs(v1, ".", 0);
395         int dot2 = strstrofs(v2, ".", 0);
396         string s1 = (dot1 == -1) ? v1 : substring(v1, 0, dot1);
397         string s2 = (dot2 == -1) ? v2 : substring(v2, 0, dot2);
398
399         float r;
400         r = stof(s1) - stof(s2);
401         if (r != 0) return r;
402
403         r = strcasecmp(s1, s2);
404         if (r != 0) return r;
405
406         if (dot1 == -1) return (dot2 == -1) ? 0 : -1;
407         else return (dot2 == -1) ? 1 : vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
408 }
409
410 ERASEABLE
411 int vercmp(string v1, string v2)
412 {
413         if (strcasecmp(v1, v2) == 0) return 0;  // early out check
414
415         // "git" beats all
416         if (v1 == "git") return 1;
417         if (v2 == "git") return -1;
418
419         return vercmp_recursive(v1, v2);
420 }
421
422 const string HEXDIGITS_MINSET = "0123456789ABCDEFabcdef";
423 const string HEXDIGITS = "0123456789ABCDEF0123456789abcdef";
424 #define HEXDIGIT_TO_DEC_RAW(d) (strstrofs(HEXDIGITS, (d), 0))
425 #define HEXDIGIT_TO_DEC(d) ((HEXDIGIT_TO_DEC_RAW(d) | 0x10) - 0x10)
426 #define DEC_TO_HEXDIGIT(d) (substring(HEXDIGITS_MINSET, (d), 1))
427 #define IS_HEXDIGIT(d) (strstrofs(HEXDIGITS_MINSET, (d), 0) >= 0)
428
429 const string DIGITS = "0123456789";
430 #define IS_DIGIT(d) (strstrofs(DIGITS, (d), 0) >= 0)