Debian Codegraph @

gcc/d/dmd/root/string.d

raw
1 /**
2 * Contains various string related functions.
3 *
4 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
5 * Authors: Walter Bright, https://www.digitalmars.com
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/root/string.d, root/_string.d)
8 * Documentation: https://dlang.org/phobos/dmd_root_string.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/root/string.d
10 */
11 module dmd.root.string;
12
13 import core.stdc.string;
14 import dmd.root.rmem;
15
16 /// Slices a `\0`-terminated C-string, excluding the terminator
17 inout(char)[] toDString (inout(char)* s) pure nothrow @nogc
18 {
19 import core.stdc.string : strlen;
20 return s ? s[0 .. strlen(s)] : null;
21 }
22
23 private struct FTuple(T...)
24 {
25 T expand;
26 }
27
28 /// Returns: a (length, ptr) tuple for passing a D string to `printf`-style functions with the format string `%.*s`
29 auto fTuple(const(char)[] str)
30 {
31 return FTuple!(int, const(char)*)(cast(int) str.length, str.ptr);
32 }
33
34 ///
35 unittest
36 {
37 import core.stdc.stdio: snprintf;
38 char[6] buf = '.';
39 const(char)[] str = "cutoff"[0..4];
40 snprintf(buf.ptr, buf.length, "%.*s", str.fTuple.expand);
41 assert(buf[] == "cuto\0.");
42 }
43
44 /**
45 Compare two slices for equality, in a case-insensitive way
46
47 Comparison is based on `char` and does not do decoding.
48 As a result, it's only really accurate for plain ASCII strings.
49
50 Params:
51 s1 = string to compare
52 s2 = string to compare
53
54 Returns:
55 `true` if `s1 == s2` regardless of case
56 */
57 extern(D) static bool iequals(const(char)[] s1, const(char)[] s2) pure nothrow @nogc
58 {
59 import core.stdc.ctype : toupper;
60
61 if (s1.length != s2.length)
62 return false;
63
64 foreach (idx, c1; s1)
65 {
66 // Since we did a length check, it is safe to bypass bounds checking
67 const c2 = s2.ptr[idx];
68 if (c1 != c2)
69 if (toupper(c1) != toupper(c2))
70 return false;
71 }
72 return true;
73 }
74
75 /**
76 Copy the content of `src` into a C-string ('\0' terminated) then call `dg`
77
78 The intent of this function is to provide an allocation-less
79 way to call a C function using a D slice.
80 The function internally allocates a buffer if needed, but frees it on exit.
81
82 Note:
83 The argument to `dg` is `scope`. To keep the data around after `dg` exits,
84 one has to copy it.
85
86 Params:
87 src = Slice to use to call the C function
88 dg = Delegate to call afterwards
89
90 Returns:
91 The return value of `T`
92 */
93 auto toCStringThen(alias dg)(const(char)[] src) nothrow
94 {
95 import dmd.root.rmem : mem;
96 import dmd.common.smallbuffer : SmallBuffer;
97
98 const len = src.length + 1;
99 char[512] small = void;
100 auto sb = SmallBuffer!char(len, small[]);
101 scope ptr = sb[];
102 ptr[0 .. src.length] = src[];
103 ptr[src.length] = '\0';
104 return dg(ptr);
105 }
106
107 unittest
108 {
109 assert("Hello world".toCStringThen!((v) => v == "Hello world\0"));
110 assert("Hello world\0".toCStringThen!((v) => v == "Hello world\0\0"));
111 assert(null.toCStringThen!((v) => v == "\0"));
112 }
113
114 /*********************************************
115 * Convert a D string to a C string by allocating memory,
116 * copying it, and adding a terminating 0.
117 * Params:
118 * s = string to copy
119 * Result:
120 * 0-terminated copy of s
121 */
122 char[] toCString(scope const(char)[] s) nothrow
123 {
124 const length = s.length;
125 char* p = cast(char*)mem.xmalloc_noscan(length + 1);
126 memcpy(p, s.ptr, length);
127 p[length] = 0;
128 return p[0 .. length];
129 }
130
131 /**
132 * Strips one leading line terminator of the given string.
133 *
134 * The following are what the Unicode standard considers as line terminators:
135 *
136 * | Name | D Escape Sequence | Unicode Code Point |
137 * |---------------------|-------------------|--------------------|
138 * | Line feed | `\n` | `U+000A` |
139 * | Line tabulation | `\v` | `U+000B` |
140 * | Form feed | `\f` | `U+000C` |
141 * | Carriage return | `\r` | `U+000D` |
142 * | Next line | | `U+0085` |
143 * | Line separator | | `U+2028` |
144 * | Paragraph separator | | `U+2029` |
145 *
146 * This function will also strip `\r\n`.
147 */
148 string stripLeadingLineTerminator(string str) pure nothrow @nogc @safe
149 {
150 enum nextLine = "\xC2\x85";
151 enum lineSeparator = "\xE2\x80\xA8";
152 enum paragraphSeparator = "\xE2\x80\xA9";
153
154 static assert(lineSeparator.length == paragraphSeparator.length);
155
156 if (str.length == 0)
157 return str;
158
159 switch (str[0])
160 {
161 case '\r':
162 {
163 if (str.length >= 2 && str[1] == '\n')
164 return str[2 .. $];
165 goto case;
166 }
167 case '\v', '\f', '\n': return str[1 .. $];
168
169 case nextLine[0]:
170 {
171 if (str.length >= 2 && str[0 .. 2] == nextLine)
172 return str[2 .. $];
173
174 return str;
175 }
176
177 case lineSeparator[0]:
178 {
179 if (str.length >= lineSeparator.length)
180 {
181 const prefix = str[0 .. lineSeparator.length];
182
183 if (prefix == lineSeparator || prefix == paragraphSeparator)
184 return str[lineSeparator.length .. $];
185 }
186
187 return str;
188 }
189
190 default: return str;
191 }
192 }
193
194 unittest
195 {
196 assert("".stripLeadingLineTerminator == "");
197 assert("foo".stripLeadingLineTerminator == "foo");
198 assert("\xC2foo".stripLeadingLineTerminator == "\xC2foo");
199 assert("\xE2foo".stripLeadingLineTerminator == "\xE2foo");
200 assert("\nfoo".stripLeadingLineTerminator == "foo");
201 assert("\vfoo".stripLeadingLineTerminator == "foo");
202 assert("\ffoo".stripLeadingLineTerminator == "foo");
203 assert("\rfoo".stripLeadingLineTerminator == "foo");
204 assert("\u0085foo".stripLeadingLineTerminator == "foo");
205 assert("\u2028foo".stripLeadingLineTerminator == "foo");
206 assert("\u2029foo".stripLeadingLineTerminator == "foo");
207 assert("\n\rfoo".stripLeadingLineTerminator == "\rfoo");
208 assert("\r\nfoo".stripLeadingLineTerminator == "foo");
209 }
210
211 /**
212 * A string comparison functions that returns the same result as strcmp
213 *
214 * Note: Strings are compared based on their ASCII values, no UTF-8 decoding.
215 *
216 * Some C functions (e.g. `qsort`) require a `int` result for comparison.
217 * See_Also: Druntime's `core.internal.string`
218 */
219 int dstrcmp()( scope const char[] s1, scope const char[] s2 ) @trusted
220 {
221 immutable len = s1.length <= s2.length ? s1.length : s2.length;
222 if (__ctfe)
223 {
224 foreach (const u; 0 .. len)
225 {
226 if (s1[u] != s2[u])
227 return s1[u] > s2[u] ? 1 : -1;
228 }
229 }
230 else
231 {
232 import core.stdc.string : memcmp;
233
234 const ret = memcmp( s1.ptr, s2.ptr, len );
235 if ( ret )
236 return ret;
237 }
238 return s1.length < s2.length ? -1 : (s1.length > s2.length);
239 }
240
241 //
242 unittest
243 {
244 assert(dstrcmp("Fraise", "Fraise") == 0);
245 assert(dstrcmp("Baguette", "Croissant") < 0);
246 assert(dstrcmp("Croissant", "Baguette") > 0);
247
248 static assert(dstrcmp("Baguette", "Croissant") < 0);
249
250 // UTF-8 decoding for the CT variant
251 assert(dstrcmp("안녕하세요!", "안녕하세요!") == 0);
252 static assert(dstrcmp("안녕하세요!", "안녕하세요!") == 0);
253 }
254
255 /**
256 * Infers the length `N` of a string literal and coerces its type to a static
257 * array with length `N + 1`. Returns the string with a null character appended
258 * to the end.
259 *
260 * Params:
261 * literal = string literal
262 *
263 * Notes:
264 * - LDC produces quite optimal code for short strings:
265 * - https://d.godbolt.org/z/M69Z1g
266 * - https://gist.github.com/PetarKirov/338e4ab9292b6b2b311a3070572a07fb (backup URL)
267 */
268 char[N + 1] toStaticArray(size_t N)(scope const(char)[N] literal)
269 {
270 char[N+1] result = void;
271 result[0..N] = literal[0..N];
272 result[N] = 0;
273 return result;
274 }
275
276 ///
277 @safe pure nothrow @nogc
278 unittest
279 {
280 auto m = "123".toStaticArray;
281 const c = "123".toStaticArray;
282 immutable i = "123".toStaticArray;
283 enum e = "123".toStaticArray;
284
285 assert(m == "123\0");
286 assert(c == "123\0");
287 assert(i == "123\0");
288 static assert(e == "123\0");
289
290 const empty = "".toStaticArray;
291 static assert(empty.length == 1);
292 static assert(empty[0] == '\0');
293 }
294
295 /**
296 * Checks if C string `p` starts with `needle`.
297 * Params:
298 * p = the C string to check
299 * needle = the string to look for
300 * Returns:
301 * `true` if `p` starts with `needle`
302 */
303 @system pure nothrow @nogc
304 bool startsWith(scope const(char)* p, scope const(char)[] needle)
305 in { assert(p && needle.ptr); }
306 do
307 {
308 foreach (const c; needle)
309 {
310 assert(c);
311 if (c != *p)
312 return false;
313 ++p;
314 }
315 return true;
316 }
317
318 ///ditto
319 nothrow @nogc pure @safe
320 bool startsWith(scope const(char)[] str, scope const(char)[] prefix)
321 {
322 if (str.length < prefix.length)
323 return false;
324 return str[0 .. prefix.length] == prefix;
325 }
326
327 ///
328 @system pure nothrow @nogc
329 unittest
330 {
331 const buf = "123".toStaticArray;
332 const ptr = &buf[0];
333 assert(ptr.startsWith(""));
334 assert(ptr.startsWith("1"));
335 assert(ptr.startsWith("12"));
336 assert(ptr.startsWith("123"));
337 assert(!ptr.startsWith("1234"));
338 }
339
340 /**********************************
341 * Take `text` and turn it into an InputRange that emits
342 * slices into `text` for each line.
343 * Params:
344 * text = array of characters
345 * Returns:
346 * InputRange accessing `text` as a sequence of lines
347 * Reference:
348 * `std.string.splitLines()`
349 */
350 auto splitLines(const char[] text)
351 {
352 struct Range
353 {
354 @safe:
355 @nogc:
356 nothrow:
357 pure:
358 private:
359
360 const char[] text;
361 size_t index; // index of start of line
362 size_t eolIndex; // index of end of line before newline characters
363 size_t nextIndex; // index past end of line
364
365 public this(const char[] text)
366 {
367 this.text = text;
368 this.index = 0;
369 this.eolIndex = 0;
370 this.nextIndex = 0;
371 }
372
373 public bool empty() { advance(); return index >= text.length; }
374
375 public void popFront() { advance(); index = nextIndex; }
376
377 public const(char)[] front()
378 {
379 advance();
380 if (index > eolIndex || index >= text.length)
381 return "";
382
383 return text[index .. eolIndex];
384 }
385
386 private void advance()
387 {
388 if (index != nextIndex) // if already advanced
389 return;
390
391 for (size_t i = index; i < text.length; ++i)
392 {
393 switch (text[i])
394 {
395 case '\v', '\f', '\n':
396 eolIndex = i;
397 nextIndex = i + 1;
398 return;
399
400 case '\r':
401 if (i + 1 < text.length && text[i + 1] == '\n') // decode "\r\n"
402 {
403 eolIndex = i;
404 nextIndex = i + 2;
405 return;
406 }
407 eolIndex = i;
408 nextIndex = i + 1;
409 return;
410
411 /* Manually decode:
412 * NEL is C2 85
413 */
414 case 0xC2:
415 if (i + 1 < text.length && text[i + 1] == 0x85)
416 {
417 eolIndex = i;
418 nextIndex = i + 2;
419 return;
420 }
421 break;
422
423 /* Manually decode:
424 * lineSep is E2 80 A8
425 * paraSep is E2 80 A9
426 */
427 case 0xE2:
428 if (i + 2 < text.length &&
429 text[i + 1] == 0x80 &&
430 (text[i + 2] == 0xA8 || text[i + 2] == 0xA9)
431 )
432 {
433 eolIndex = i;
434 nextIndex = i + 3;
435 return;
436 }
437 break;
438
439 default:
440 break;
441 }
442 }
443
444 // No newline found; set indices to the end of the text
445 eolIndex = text.length;
446 nextIndex = text.length;
447 }
448 }
449
450 return Range(text);
451 }
452
453 private struct FindSplit
454 {
455 @nogc nothrow pure @safe:
456 const(char)[][3] elem;
457
458 ref const(char)[] opIndex(size_t i) scope return { return elem[i]; }
459 bool opCast() const scope { return elem[1].length > 0; }
460 }
461
462 /**
463 Find a substring in a string and split the string into before and after parts.
464 Params:
465 str = string to look into
466 needle = substring to find in str (must not be empty)
467 Returns:
468 a `FindSplit` object that casts to `true` iff `needle` was found inside `str`.
469 In that case, `split[1]` is the needle, and `split[0]`/`split[2]` are before/after the needle.
470 */
471 FindSplit findSplit(return scope const(char)[] str, scope const(char)[] needle) @safe
472 {
473 if (needle.length > str.length)
474 return FindSplit([str, null, null]);
475
476 foreach (i; 0 .. str.length - needle.length + 1)
477 {
478 if (str[i .. i+needle.length] == needle[])
479 return FindSplit([ str[0 .. i], str[i .. i+needle.length], str[i+needle.length .. $] ]);
480 }
481 return FindSplit([str, null, null]);
482 }
483
484 unittest
485 {
486 auto s = findSplit("a b c", "c");
487 assert(s[0] == "a b ");
488 assert(s[1] == "c");
489 assert(s[2] == "");
490 auto s1 = findSplit("a b c", "b");
491 assert(s1[0] == "a ");
492 assert(s1[1] == "b");
493 assert(s1[2] == " c");
494 assert(!findSplit("a b c", "d"));
495 assert(!findSplit("", "d"));
496 }
497
498 /**
499 Find a string inbetween two substrings
500 Params:
501 str = string to look into
502 l = substring to find on the left
503 r = substring to find on the right
504 Returns:
505 substring of `str` inbetween `l` and `r`
506 */
507 const(char)[] findBetween(const(char)[] str, const(char)[] l, const(char)[] r) @safe
508 {
509 if (auto s0 = str.findSplit(l))
510 if (auto s1 = s0[2].findSplit(r))
511 return s1[0];
512 return null;
513 }
514
515 unittest
516 {
517 assert(findBetween("a b c", "a ", " c") == "b");
518 assert(findBetween("a b c", "a ", " d") == null);
519 }