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