• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 19020191358

02 Nov 2025 05:04PM UTC coverage: 72.222% (-0.02%) from 72.241%
19020191358

push

github

web-flow
Enhance docs for ukify and direct kernel boots (#39516)

305246 of 422650 relevant lines covered (72.22%)

1085243.28 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.99
/src/basic/string-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdio.h>
4

5
#include "alloc-util.h"
6
#include "escape.h"
7
#include "extract-word.h"
8
#include "glyph-util.h"
9
#include "gunicode.h"
10
#include "locale-util.h"
11
#include "log.h"
12
#include "memory-util.h"
13
#include "memstream-util.h"
14
#include "path-util.h"
15
#include "string-util.h"
16
#include "strv.h"
17
#include "terminal-util.h"
18
#include "utf8.h"
19

20
char* first_word(const char *s, const char *word) {
3,222,891✔
21
        assert(s);
3,222,891✔
22
        assert(word);
3,222,891✔
23

24
        /* Checks if the string starts with the specified word, either followed by NUL or by whitespace.
25
         * Returns a pointer to the NUL or the first character after the whitespace. */
26

27
        if (isempty(word))
3,222,891✔
28
                return (char*) s;
29

30
        const char *p = startswith(s, word);
3,222,890✔
31
        if (!p)
3,222,890✔
32
                return NULL;
33
        if (*p == '\0')
93,522✔
34
                return (char*) p;
35

36
        const char *nw = skip_leading_chars(p, WHITESPACE);
93,521✔
37
        if (p == nw)
93,521✔
38
                return NULL;
1✔
39

40
        return (char*) nw;
41
}
42

43
char* strextendn(char **x, const char *s, size_t l) {
27,903✔
44
        assert(x);
27,903✔
45
        assert(s || l == 0);
27,903✔
46

47
        if (l > 0)
27,903✔
48
                l = strnlen(s, l); /* ignore trailing noise */
27,607✔
49

50
        if (l > 0 || !*x) {
27,903✔
51
                size_t q;
27,762✔
52
                char *m;
27,762✔
53

54
                q = strlen_ptr(*x);
27,762✔
55
                m = realloc(*x, q + l + 1);
27,762✔
56
                if (!m)
27,762✔
57
                        return NULL;
58

59
                *mempcpy_typesafe(m + q, s, l) = 0;
27,762✔
60

61
                *x = m;
27,762✔
62
        }
63

64
        return *x;
27,903✔
65
}
66

67
char* strstrip(char *s) {
5,307,768✔
68
        if (!s)
5,307,768✔
69
                return NULL;
70

71
        /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
72

73
        return delete_trailing_chars(skip_leading_chars(s, WHITESPACE), WHITESPACE);
5,304,537✔
74
}
75

76
char* delete_chars(char *s, const char *bad) {
9✔
77
        char *f, *t;
9✔
78

79
        /* Drops all specified bad characters, regardless where in the string */
80

81
        if (!s)
9✔
82
                return NULL;
83

84
        if (!bad)
9✔
85
                bad = WHITESPACE;
×
86

87
        for (f = s, t = s; *f; f++) {
131✔
88
                if (strchr(bad, *f))
122✔
89
                        continue;
67✔
90

91
                *(t++) = *f;
55✔
92
        }
93

94
        *t = 0;
9✔
95

96
        return s;
9✔
97
}
98

99
char* delete_trailing_chars(char *s, const char *bad) {
6,603,849✔
100
        char *c = s;
6,603,849✔
101

102
        /* Drops all specified bad characters, at the end of the string */
103

104
        if (!s)
6,603,849✔
105
                return NULL;
106

107
        if (!bad)
6,603,849✔
108
                bad = WHITESPACE;
77,319✔
109

110
        for (char *p = s; *p; p++)
248,773,197✔
111
                if (!strchr(bad, *p))
242,169,348✔
112
                        c = p + 1;
232,399,300✔
113

114
        *c = 0;
6,603,849✔
115

116
        return s;
6,603,849✔
117
}
118

119
char* truncate_nl_full(char *s, size_t *ret_len) {
2,277,776✔
120
        size_t n;
2,277,776✔
121

122
        assert(s);
2,277,776✔
123

124
        n = strcspn(s, NEWLINE);
2,277,776✔
125
        s[n] = '\0';
2,277,776✔
126
        if (ret_len)
2,277,776✔
127
                *ret_len = n;
6✔
128
        return s;
2,277,776✔
129
}
130

131
char ascii_tolower(char x) {
47,262,743✔
132

133
        if (x >= 'A' && x <= 'Z')
47,262,743✔
134
                return x - 'A' + 'a';
3,286,325✔
135

136
        return x;
137
}
138

139
char ascii_toupper(char x) {
294,803✔
140

141
        if (x >= 'a' && x <= 'z')
294,803✔
142
                return x - 'a' + 'A';
177,142✔
143

144
        return x;
145
}
146

147
char* ascii_strlower(char *t) {
27,515✔
148
        assert(t);
27,515✔
149

150
        for (char *p = t; *p; p++)
176,922✔
151
                *p = ascii_tolower(*p);
149,407✔
152

153
        return t;
27,515✔
154
}
155

156
char* ascii_strupper(char *t) {
20,607✔
157
        assert(t);
20,607✔
158

159
        for (char *p = t; *p; p++)
315,280✔
160
                *p = ascii_toupper(*p);
294,673✔
161

162
        return t;
20,607✔
163
}
164

165
char* ascii_strlower_n(char *t, size_t n) {
1,687,028✔
166
        if (n <= 0)
1,687,028✔
167
                return t;
168

169
        for (size_t i = 0; i < n; i++)
14,378,638✔
170
                t[i] = ascii_tolower(t[i]);
12,691,937✔
171

172
        return t;
173
}
174

175
int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
2,268,396✔
176

177
        for (; n > 0; a++, b++, n--) {
18,944,151✔
178
                int x, y;
17,206,494✔
179

180
                x = (int) (uint8_t) ascii_tolower(*a);
17,206,494✔
181
                y = (int) (uint8_t) ascii_tolower(*b);
17,206,494✔
182

183
                if (x != y)
17,206,494✔
184
                        return x - y;
530,739✔
185
        }
186

187
        return 0;
188
}
189

190
int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
987,764✔
191
        int r;
987,764✔
192

193
        r = ascii_strcasecmp_n(a, b, MIN(n, m));
987,764✔
194
        if (r != 0)
987,764✔
195
                return r;
196

197
        return CMP(n, m);
878,849✔
198
}
199

200
bool chars_intersect(const char *a, const char *b) {
10,393✔
201
        /* Returns true if any of the chars in a are in b. */
202
        for (const char *p = a; *p; p++)
156,210✔
203
                if (strchr(b, *p))
145,830✔
204
                        return true;
205

206
        return false;
207
}
208

209
bool string_has_cc(const char *p, const char *ok) {
209,714✔
210
        assert(p);
209,714✔
211

212
        /*
213
         * Check if a string contains control characters. If 'ok' is
214
         * non-NULL it may be a string containing additional CCs to be
215
         * considered OK.
216
         */
217

218
        for (const char *t = p; *t; t++) {
1,829,964✔
219
                if (ok && strchr(ok, *t))
1,620,266✔
220
                        continue;
8✔
221

222
                if (char_is_cc(*t))
1,620,258✔
223
                        return true;
224
        }
225

226
        return false;
227
}
228

229
static int write_ellipsis(char *buf, bool unicode) {
4,264✔
230
        const char *s = glyph_full(GLYPH_ELLIPSIS, unicode);
4,264✔
231
        assert(strlen(s) == 3);
4,264✔
232
        memcpy(buf, s, 3);
4,264✔
233
        return 3;
4,264✔
234
}
235

236
static size_t ansi_sequence_length(const char *s, size_t len) {
6,271✔
237
        assert(s);
6,271✔
238

239
        if (len < 2)
6,271✔
240
                return 0;
241

242
        if (s[0] != 0x1B)  /* ASCII 27, aka ESC, aka Ctrl-[ */
6,181✔
243
                return 0;  /* Not the start of a sequence */
244

245
        if (s[1] == 0x5B) { /* [, start of CSI sequence */
895✔
246
                size_t i = 2;
895✔
247

248
                if (i == len)
895✔
249
                        return 0;
250

251
                while (s[i] >= 0x30 && s[i] <= 0x3F) /* Parameter bytes */
9,184✔
252
                        if (++i == len)
8,289✔
253
                                return 0;
254
                while (s[i] >= 0x20 && s[i] <= 0x2F) /* Intermediate bytes */
895✔
255
                        if (++i == len)
×
256
                                return 0;
257
                if (s[i] >= 0x40 && s[i] <= 0x7E) /* Final byte */
895✔
258
                        return i + 1;
895✔
259
                return 0;  /* Bad sequence */
260

261
        } else if (s[1] >= 0x40 && s[1] <= 0x5F) /* other non-CSI Fe sequence */
×
262
                return 2;
×
263

264
        return 0;  /* Bad escape? */
265
}
266

267
static bool string_has_ansi_sequence(const char *s, size_t len) {
7,693✔
268
        const char *t = s;
7,693✔
269

270
        while ((t = memchr(s, 0x1B, len - (t - s))))
7,693✔
271
                if (ansi_sequence_length(t, len - (t - s)) > 0)
151✔
272
                        return true;
273
        return false;
274
}
275

276
static size_t previous_ansi_sequence(const char *s, size_t length, const char **ret_where) {
263✔
277
        /* Locate the previous ANSI sequence and save its start in *ret_where and return length. */
278

279
        for (size_t i = length - 2; i > 0; i--) {  /* -2 because at least two bytes are needed */
3,409✔
280
                size_t slen = ansi_sequence_length(s + (i - 1), length - (i - 1));
3,407✔
281
                if (slen == 0)
3,407✔
282
                        continue;
3,146✔
283

284
                *ret_where = s + (i - 1);
261✔
285
                return slen;
261✔
286
        }
287

288
        *ret_where = NULL;
2✔
289
        return 0;
2✔
290
}
291

292
static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4,167✔
293
        size_t x, need_space, suffix_len;
4,167✔
294
        char *t;
4,167✔
295

296
        assert(s);
4,167✔
297
        assert(percent <= 100);
4,167✔
298
        assert(new_length != SIZE_MAX);
4,167✔
299

300
        if (old_length <= new_length)
4,167✔
301
                return strndup(s, old_length);
1,670✔
302

303
        /* Special case short ellipsations */
304
        switch (new_length) {
2,497✔
305

306
        case 0:
×
307
                return strdup("");
×
308

309
        case 1:
65✔
310
                if (is_locale_utf8())
65✔
311
                        return strdup("…");
65✔
312
                else
313
                        return strdup(".");
×
314

315
        case 2:
35✔
316
                if (!is_locale_utf8())
35✔
317
                        return strdup("..");
×
318
                break;
319
        }
320

321
        /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
322
         * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
323
         * either for the UTF-8 encoded character or for three ASCII characters. */
324
        need_space = is_locale_utf8() ? 1 : 3;
2,432✔
325

326
        t = new(char, new_length+3);
2,432✔
327
        if (!t)
2,432✔
328
                return NULL;
329

330
        assert(new_length >= need_space);
2,432✔
331

332
        x = ((new_length - need_space) * percent + 50) / 100;
2,432✔
333
        assert(x <= new_length - need_space);
2,432✔
334

335
        write_ellipsis(mempcpy(t, s, x), /* unicode = */ false);
2,432✔
336
        suffix_len = new_length - x - need_space;
2,432✔
337
        memcpy(t + x + 3, s + old_length - suffix_len, suffix_len);
2,432✔
338
        *(t + x + 3 + suffix_len) = '\0';
2,432✔
339

340
        return t;
2,432✔
341
}
342

343
char* ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
7,864✔
344
        size_t x, k, len, len2;
7,864✔
345
        const char *i, *j;
7,864✔
346
        int r;
7,864✔
347

348
        /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
349
         * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
350
         * strings.
351
         *
352
         * Ellipsation is done in a locale-dependent way:
353
         * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
354
         * 2. Otherwise, a unicode ellipsis is used ("…")
355
         *
356
         * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
357
         * the current locale is UTF-8.
358
         */
359

360
        assert(s);
7,864✔
361
        assert(percent <= 100);
7,864✔
362

363
        if (new_length == SIZE_MAX)
7,864✔
364
                return strndup(s, old_length);
×
365

366
        if (new_length == 0)
7,864✔
367
                return strdup("");
171✔
368

369
        bool has_ansi_seq = string_has_ansi_sequence(s, old_length);
7,693✔
370

371
        /* If no multibyte characters or ANSI sequences, use ascii_ellipsize_mem for speed */
372
        if (!has_ansi_seq && ascii_is_valid_n(s, old_length))
7,693✔
373
                return ascii_ellipsize_mem(s, old_length, new_length, percent);
4,167✔
374

375
        x = (new_length - 1) * percent / 100;
3,526✔
376
        assert(x <= new_length - 1);
3,526✔
377

378
        k = 0;
379
        for (i = s; i < s + old_length; ) {
49,185✔
380
                size_t slen = has_ansi_seq ? ansi_sequence_length(i, old_length - (i - s)) : 0;
47,993✔
381
                if (slen > 0) {
984✔
382
                        i += slen;
221✔
383
                        continue;  /* ANSI sequences don't take up any space in output */
221✔
384
                }
385

386
                char32_t c;
47,772✔
387
                r = utf8_encoded_to_unichar(i, &c);
47,772✔
388
                if (r < 0)
47,772✔
389
                        return NULL;
×
390

391
                int w = unichar_iswide(c) ? 2 : 1;
47,772✔
392
                if (k + w > x)
47,772✔
393
                        break;
394

395
                k += w;
45,438✔
396
                i += r;
45,438✔
397
        }
398

399
        const char *ansi_start = s + old_length;
3,526✔
400
        size_t ansi_len = 0;
3,526✔
401

402
        for (const char *t = j = s + old_length; t > i && k < new_length; ) {
13,110✔
403
                char32_t c;
9,670✔
404
                int w;
9,670✔
405
                const char *tt;
9,670✔
406

407
                if (has_ansi_seq && ansi_start >= t)
9,670✔
408
                        /* Figure out the previous ANSI sequence, if any */
409
                        ansi_len = previous_ansi_sequence(s, t - s, &ansi_start);
263✔
410

411
                /* If the sequence extends all the way to the current position, skip it. */
412
                if (has_ansi_seq && ansi_len > 0 && ansi_start + ansi_len == t) {
9,670✔
413
                        t = ansi_start;
112✔
414
                        continue;
112✔
415
                }
416

417
                tt = utf8_prev_char(t);
9,558✔
418
                r = utf8_encoded_to_unichar(tt, &c);
9,558✔
419
                if (r < 0)
9,558✔
420
                        return NULL;
×
421

422
                w = unichar_iswide(c) ? 2 : 1;
9,558✔
423
                if (k + w > new_length)
9,558✔
424
                        break;
425

426
                k += w;
9,472✔
427
                j = t = tt;  /* j should always point to the first "real" character */
9,472✔
428
        }
429

430
        /* We don't actually need to ellipsize */
431
        if (i >= j)
3,526✔
432
                return memdup_suffix0(s, old_length);
1,718✔
433

434
        if (k >= new_length) {
1,808✔
435
                /* Make space for ellipsis, if required and possible. We know that the edge character is not
436
                 * part of an ANSI sequence (because then we'd skip it). If the last character we looked at
437
                 * was wide, we don't need to make space. */
438
                if (j < s + old_length)
1,722✔
439
                        j = utf8_next_char(j);
1,722✔
440
                else if (i > s)
×
441
                        i = utf8_prev_char(i);
×
442
        }
443

444
        len = i - s;
1,808✔
445
        len2 = s + old_length - j;
1,808✔
446

447
        /* If we have ANSI, allow the same length as the source string + ellipsis. It'd be too involved to
448
         * figure out what exact space is needed. Strings with ANSI sequences are most likely to be fairly
449
         * short anyway. */
450
        size_t alloc_len = has_ansi_seq ? old_length + 3 + 1 : len + 3 + len2 + 1;
1,808✔
451

452
        char *e = new(char, alloc_len);
1,808✔
453
        if (!e)
1,808✔
454
                return NULL;
455

456
        memcpy_safe(e, s, len);
1,808✔
457
        write_ellipsis(e + len, /* unicode = */ true);
1,808✔
458

459
        char *dst = e + len + 3;
1,808✔
460

461
        if (has_ansi_seq)
1,808✔
462
                /* Copy over any ANSI sequences in full */
463
                for (const char *p = s + len; p < j; ) {
1,864✔
464
                        size_t slen = ansi_sequence_length(p, j - p);
1,729✔
465
                        if (slen > 0) {
1,729✔
466
                                dst = mempcpy(dst, p, slen);
262✔
467
                                p += slen;
262✔
468
                        } else
469
                                p = utf8_next_char(p);
1,467✔
470
                }
471

472
        memcpy_safe(dst, j, len2);
1,808✔
473
        dst[len2] = '\0';
1,808✔
474

475
        return e;
1,808✔
476
}
477

478
char* cellescape(char *buf, size_t len, const char *s) {
37,761✔
479
        /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
480
         * characters are copied as they are, everything else is escaped. The result
481
         * is different then if escaping and ellipsization was performed in two
482
         * separate steps, because each sequence is either stored in full or skipped.
483
         *
484
         * This function should be used for logging about strings which expected to
485
         * be plain ASCII in a safe way.
486
         *
487
         * An ellipsis will be used if s is too long. It was always placed at the
488
         * very end.
489
         */
490

491
        size_t i = 0, last_char_width[4] = {}, k = 0;
37,761✔
492

493
        assert(buf);
37,761✔
494
        assert(len > 0); /* at least a terminating NUL */
37,761✔
495
        assert(s);
37,761✔
496

497
        for (;;) {
833,579✔
498
                char four[4];
435,670✔
499
                int w;
435,670✔
500

501
                if (*s == 0) /* terminating NUL detected? then we are done! */
435,670✔
502
                        goto done;
37,725✔
503

504
                w = cescape_char(*s, four);
397,945✔
505
                if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
397,945✔
506
                                      * ellipsize at the previous location */
507
                        break;
508

509
                /* OK, there was space, let's add this escaped character to the buffer */
510
                memcpy(buf + i, four, w);
397,909✔
511
                i += w;
397,909✔
512

513
                /* And remember its width in the ring buffer */
514
                last_char_width[k] = w;
397,909✔
515
                k = (k + 1) % 4;
397,909✔
516

517
                s++;
397,909✔
518
        }
519

520
        /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
521
         * characters ideally, but the buffer is shorter than that in the first place take what we can get */
522
        for (size_t j = 0; j < ELEMENTSOF(last_char_width); j++) {
81✔
523

524
                if (i + 4 <= len) /* nice, we reached our space goal */
81✔
525
                        break;
526

527
                k = k == 0 ? 3 : k - 1;
57✔
528
                if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
57✔
529
                        break;
530

531
                assert(i >= last_char_width[k]);
45✔
532
                i -= last_char_width[k];
45✔
533
        }
534

535
        if (i + 4 <= len) /* yay, enough space */
36✔
536
                i += write_ellipsis(buf + i, /* unicode = */ false);
24✔
537
        else if (i + 3 <= len) { /* only space for ".." */
12✔
538
                buf[i++] = '.';
4✔
539
                buf[i++] = '.';
4✔
540
        } else if (i + 2 <= len) /* only space for a single "." */
8✔
541
                buf[i++] = '.';
4✔
542
        else
543
                assert(i + 1 <= len);
4✔
544

545
done:
4✔
546
        buf[i] = '\0';
37,761✔
547
        return buf;
37,761✔
548
}
549

550
char* strshorten(char *s, size_t l) {
21,722✔
551
        assert(s);
21,722✔
552

553
        if (l >= SIZE_MAX-1) /* Would not change anything */
21,722✔
554
                return s;
555

556
        if (strnlen(s, l+1) > l)
21,720✔
557
                s[l] = 0;
21✔
558

559
        return s;
560
}
561

562
int strgrowpad0(char **s, size_t l) {
16✔
563
        size_t sz;
16✔
564

565
        assert(s);
16✔
566

567
        if (*s) {
16✔
568
                sz = strlen(*s) + 1;
16✔
569
                if (sz >= l) /* never shrink */
16✔
570
                        return 0;
571
        } else
572
                sz = 0;
573

574
        char *q = realloc(*s, l);
16✔
575
        if (!q)
16✔
576
                return -ENOMEM;
577

578
        *s = q;
16✔
579

580
        memzero(*s + sz, l - sz);
16✔
581
        return 0;
582
}
583

584
char* strreplace(const char *text, const char *old_string, const char *new_string) {
2,548✔
585
        size_t l, old_len, new_len;
2,548✔
586
        char *t, *ret = NULL;
2,548✔
587
        const char *f;
2,548✔
588

589
        assert(old_string);
2,548✔
590
        assert(new_string);
2,548✔
591

592
        if (!text)
2,548✔
593
                return NULL;
2,548✔
594

595
        old_len = strlen(old_string);
2,547✔
596
        new_len = strlen(new_string);
2,547✔
597

598
        l = strlen(text);
2,547✔
599
        if (!GREEDY_REALLOC(ret, l+1))
2,547✔
600
                return NULL;
601

602
        f = text;
2,547✔
603
        t = ret;
2,547✔
604
        while (*f) {
107,034✔
605
                size_t d, nl;
104,487✔
606

607
                if (!startswith(f, old_string)) {
104,487✔
608
                        *(t++) = *(f++);
102,179✔
609
                        continue;
102,179✔
610
                }
611

612
                d = t - ret;
2,308✔
613
                nl = l - old_len + new_len;
2,308✔
614

615
                if (!GREEDY_REALLOC(ret, nl + 1))
2,308✔
616
                        return mfree(ret);
×
617

618
                l = nl;
2,308✔
619
                t = ret + d;
2,308✔
620

621
                t = stpcpy(t, new_string);
2,308✔
622
                f += old_len;
2,308✔
623
        }
624

625
        *t = 0;
2,547✔
626
        return ret;
2,547✔
627
}
628

629
static void advance_offsets(
386✔
630
                ssize_t diff,
631
                size_t offsets[2], /* note: we can't use [static 2] here, since this may be NULL */
632
                size_t shift[static 2],
633
                size_t size) {
634

635
        if (!offsets)
386✔
636
                return;
637

638
        assert(shift);
376✔
639

640
        if ((size_t) diff < offsets[0])
376✔
641
                shift[0] += size;
×
642
        if ((size_t) diff < offsets[1])
376✔
643
                shift[1] += size;
×
644
}
645

646
char* strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
120,278✔
647
        const char *begin = NULL;
120,278✔
648
        enum {
120,278✔
649
                STATE_OTHER,
650
                STATE_ESCAPE,
651
                STATE_CSI,
652
                STATE_OSC,
653
                STATE_OSC_CLOSING,
654
        } state = STATE_OTHER;
120,278✔
655
        _cleanup_(memstream_done) MemStream m = {};
120,278✔
656
        size_t isz, shift[2] = {}, n_carriage_returns = 0;
120,278✔
657
        FILE *f;
120,278✔
658

659
        assert(ibuf);
120,278✔
660
        assert(*ibuf);
120,278✔
661

662
        /* This does three things:
663
         *
664
         * 1. Replaces TABs by 8 spaces
665
         * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
666
         * 3. Strips ANSI operating system sequences (OSC), i.e. ESC ']' … ST sequences
667
         * 4. Strip trailing \r characters (since they would "move the cursor", but have no
668
         *    other effect).
669
         *
670
         * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
671
         * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
672
         * supposed to suppress the most basic formatting noise, but nothing else.
673
         *
674
         * Why care for OSC sequences? Well, to undo what terminal_urlify() and friends generate. */
675

676
        isz = _isz ? *_isz : strlen(*ibuf);
120,278✔
677

678
        /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
679
         * created f here and it doesn't leave our scope. */
680
        f = memstream_init(&m);
120,278✔
681
        if (!f)
120,278✔
682
                return NULL;
683

684
        for (const char *i = *ibuf; i < *ibuf + isz + 1; i++) {
14,434,665✔
685

686
                bool eot = i >= *ibuf + isz;
14,314,387✔
687

688
                switch (state) {
14,314,387✔
689

690
                case STATE_OTHER:
14,314,304✔
691
                        if (eot)
14,314,304✔
692
                                break;
693

694
                        if (*i == '\r') {
14,194,026✔
695
                                n_carriage_returns++;
7✔
696
                                break;
7✔
697
                        } else if (*i == '\n')
14,194,019✔
698
                                /* Ignore carriage returns before new line */
699
                                n_carriage_returns = 0;
34✔
700
                        for (; n_carriage_returns > 0; n_carriage_returns--)
14,194,021✔
701
                                fputc('\r', f);
2✔
702

703
                        if (*i == '\x1B')
14,194,019✔
704
                                state = STATE_ESCAPE;
705
                        else if (*i == '\t') {
14,194,003✔
706
                                fputs("        ", f);
381✔
707
                                advance_offsets(i - *ibuf, highlight, shift, 7);
381✔
708
                        } else
709
                                fputc(*i, f);
14,193,622✔
710

711
                        break;
712

713
                case STATE_ESCAPE:
16✔
714
                        assert(n_carriage_returns == 0);
16✔
715

716
                        if (eot) {
16✔
717
                                fputc('\x1B', f);
×
718
                                advance_offsets(i - *ibuf, highlight, shift, 1);
×
719
                                break;
720
                        } else if (*i == '[') { /* ANSI CSI */
16✔
721
                                state = STATE_CSI;
13✔
722
                                begin = i + 1;
13✔
723
                        } else if (*i == ']') { /* ANSI OSC */
3✔
724
                                state = STATE_OSC;
3✔
725
                                begin = i + 1;
3✔
726
                        } else {
727
                                fputc('\x1B', f);
×
728
                                fputc(*i, f);
×
729
                                advance_offsets(i - *ibuf, highlight, shift, 1);
×
730
                                state = STATE_OTHER;
×
731
                        }
732

733
                        break;
734

735
                case STATE_CSI:
41✔
736
                        assert(n_carriage_returns == 0);
41✔
737

738
                        if (eot || !strchr("01234567890;m", *i)) { /* EOT or invalid chars in sequence */
41✔
739
                                fputc('\x1B', f);
5✔
740
                                fputc('[', f);
5✔
741
                                advance_offsets(i - *ibuf, highlight, shift, 2);
5✔
742
                                state = STATE_OTHER;
5✔
743
                                i = begin-1;
5✔
744
                        } else if (*i == 'm')
36✔
745
                                state = STATE_OTHER;
8✔
746

747
                        break;
748

749
                case STATE_OSC:
24✔
750
                        assert(n_carriage_returns == 0);
24✔
751

752
                        /* There are three kinds of OSC terminators: \x07, \x1b\x5c or \x9c. We only support
753
                         * the first two, because the last one is a valid UTF-8 codepoint and hence creates
754
                         * an ambiguity (many Terminal emulators refuse to support it as well). */
755
                        if (eot || (!IN_SET(*i, '\x07', '\x1b') && !osc_char_is_valid(*i))) { /* EOT or invalid chars in sequence */
24✔
756
                                fputc('\x1B', f);
×
757
                                fputc(']', f);
×
758
                                advance_offsets(i - *ibuf, highlight, shift, 2);
×
759
                                state = STATE_OTHER;
×
760
                                i = begin-1;
×
761
                        } else if (*i == '\x07') /* Single character ST */
24✔
762
                                state = STATE_OTHER;
763
                        else if (*i == '\x1B')
23✔
764
                                state = STATE_OSC_CLOSING;
2✔
765

766
                        break;
767

768
                case STATE_OSC_CLOSING:
2✔
769
                        if (eot || *i != '\x5c') { /* EOT or incomplete two-byte ST in sequence */
2✔
770
                                fputc('\x1B', f);
×
771
                                fputc(']', f);
×
772
                                advance_offsets(i - *ibuf, highlight, shift, 2);
×
773
                                state = STATE_OTHER;
×
774
                                i = begin-1;
×
775
                        } else if (*i == '\x5c')
776
                                state = STATE_OTHER;
777

778
                        break;
779
                }
780
        }
781

782
        char *obuf;
120,278✔
783
        if (memstream_finalize(&m, &obuf, _isz) < 0)
120,278✔
784
                return NULL;
785

786
        free_and_replace(*ibuf, obuf);
120,278✔
787

788
        if (highlight) {
120,278✔
789
                highlight[0] += shift[0];
120,269✔
790
                highlight[1] += shift[1];
120,269✔
791
        }
792

793
        return *ibuf;
120,278✔
794
}
795

796
char* strextendv_with_separator(char **x, const char *separator, va_list ap) {
16,760,097✔
797
        _cleanup_free_ char *buffer = NULL;
16,760,097✔
798
        size_t f, l, l_separator;
16,760,097✔
799
        bool need_separator;
16,760,097✔
800
        char *nr, *p;
16,760,097✔
801

802
        if (!x)
16,760,097✔
803
                x = &buffer;
15,804,271✔
804

805
        l = f = strlen_ptr(*x);
16,760,097✔
806

807
        need_separator = !isempty(*x);
16,760,097✔
808
        l_separator = strlen_ptr(separator);
16,760,097✔
809

810
        va_list aq;
16,760,097✔
811
        va_copy(aq, ap);
16,760,097✔
812
        for (const char *t;;) {
63,243,997✔
813
                size_t n;
63,243,997✔
814

815
                t = va_arg(aq, const char *);
63,243,997✔
816
                if (!t)
63,243,997✔
817
                        break;
818
                if (t == POINTER_MAX)
46,483,900✔
819
                        continue;
3✔
820

821
                n = strlen(t);
46,483,897✔
822

823
                if (need_separator)
46,483,897✔
824
                        n += l_separator;
30,270,255✔
825

826
                if (n >= SIZE_MAX - l) {
46,483,897✔
827
                        va_end(aq);
×
828
                        return NULL;
×
829
                }
830

831
                l += n;
46,483,897✔
832
                need_separator = true;
46,483,897✔
833
        }
834
        va_end(aq);
16,760,097✔
835

836
        need_separator = !isempty(*x);
16,760,097✔
837

838
        nr = realloc(*x, GREEDY_ALLOC_ROUND_UP(l+1));
16,760,097✔
839
        if (!nr)
16,760,097✔
840
                return NULL;
841

842
        *x = nr;
16,760,097✔
843
        p = nr + f;
16,760,097✔
844

845
        for (;;) {
63,243,997✔
846
                const char *t;
63,243,997✔
847

848
                t = va_arg(ap, const char *);
63,243,997✔
849
                if (!t)
63,243,997✔
850
                        break;
851
                if (t == POINTER_MAX)
46,483,900✔
852
                        continue;
3✔
853

854
                if (need_separator && separator)
46,483,897✔
855
                        p = stpcpy(p, separator);
161,205✔
856

857
                p = stpcpy(p, t);
46,483,897✔
858

859
                need_separator = true;
46,483,897✔
860
        }
861

862
        assert(p == nr + l);
16,760,097✔
863
        *p = 0;
16,760,097✔
864

865
        /* If no buffer to extend was passed in return the start of the buffer */
866
        if (buffer)
16,760,097✔
867
                return TAKE_PTR(buffer);
15,804,271✔
868

869
        /* Otherwise we extended the buffer: return the end */
870
        return p;
871
}
872

873
char* strextend_with_separator_internal(char **x, const char *separator, ...) {
16,711,052✔
874
        va_list ap;
16,711,052✔
875
        char *ret;
16,711,052✔
876

877
        va_start(ap, separator);
16,711,052✔
878
        ret = strextendv_with_separator(x, separator, ap);
16,711,052✔
879
        va_end(ap);
16,711,052✔
880

881
        return ret;
16,711,052✔
882
}
883

884
int strextendf_with_separator(char **x, const char *separator, const char *format, ...) {
16,008✔
885
        size_t m, a, l_separator;
16,008✔
886
        va_list ap;
16,008✔
887
        int l;
16,008✔
888

889
        /* Appends a formatted string to the specified string. Don't use this in inner loops, since then
890
         * we'll spend a tonload of time in determining the length of the string passed in, over and over
891
         * again. */
892

893
        assert(x);
16,008✔
894
        assert(format);
16,008✔
895

896
        l_separator = isempty(*x) ? 0 : strlen_ptr(separator);
28,325✔
897

898
        /* Let's try to use the allocated buffer, if there's room at the end still. Otherwise let's extend by 64 chars. */
899
        if (*x) {
16,008✔
900
                m = strlen(*x);
12,317✔
901
                a = MALLOC_SIZEOF_SAFE(*x);
12,317✔
902
                assert(a >= m + 1);
12,317✔
903
        } else
904
                m = a = 0;
905

906
        if (a - m < 17 + l_separator) { /* if there's less than 16 chars space, then enlarge the buffer first */
16,008✔
907
                char *n;
9,953✔
908

909
                if (_unlikely_(l_separator > SIZE_MAX - 64)) /* overflow check #1 */
9,953✔
910
                        return -ENOMEM;
16,008✔
911
                if (_unlikely_(m > SIZE_MAX - 64 - l_separator)) /* overflow check #2 */
9,953✔
912
                        return -ENOMEM;
913

914
                n = realloc(*x, m + 64 + l_separator);
9,953✔
915
                if (!n)
9,953✔
916
                        return -ENOMEM;
917

918
                *x = n;
9,953✔
919
                a = MALLOC_SIZEOF_SAFE(*x);
9,953✔
920
        }
921

922
        /* Now, let's try to format the string into it */
923
        memcpy_safe(*x + m, separator, l_separator);
16,008✔
924
        va_start(ap, format);
16,008✔
925
        l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
16,008✔
926
        va_end(ap);
16,008✔
927

928
        assert(l >= 0);
16,008✔
929

930
        if ((size_t) l < a - m - l_separator) {
16,008✔
931
                char *n;
15,270✔
932

933
                /* Nice! This worked. We are done. But first, let's return the extra space we don't
934
                 * need. This should be a cheap operation, since we only lower the allocation size here,
935
                 * never increase. */
936
                n = realloc(*x, m + (size_t) l + l_separator + 1);
15,270✔
937
                if (n)
15,270✔
938
                        *x = n;
15,270✔
939
        } else {
940
                char *n;
738✔
941

942
                /* Wasn't enough. Then let's allocate exactly what we need. */
943

944
                if (_unlikely_((size_t) l > SIZE_MAX - (l_separator + 1))) /* overflow check #1 */
738✔
945
                        goto oom;
×
946
                if (_unlikely_(m > SIZE_MAX - ((size_t) l + l_separator + 1))) /* overflow check #2 */
738✔
947
                        goto oom;
×
948

949
                a = m + (size_t) l + l_separator + 1;
738✔
950
                n = realloc(*x, a);
738✔
951
                if (!n)
738✔
952
                        goto oom;
×
953
                *x = n;
738✔
954

955
                va_start(ap, format);
738✔
956
                l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
738✔
957
                va_end(ap);
738✔
958

959
                assert((size_t) l < a - m - l_separator);
738✔
960
        }
961

962
        return 0;
963

964
oom:
×
965
        /* truncate the bytes added after memcpy_safe() again */
966
        (*x)[m] = 0;
×
967
        return -ENOMEM;
×
968
}
969

970
char* strrep(const char *s, unsigned n) {
11✔
971
        char *r, *p;
11✔
972
        size_t l;
11✔
973

974
        assert(s);
11✔
975

976
        l = strlen(s);
11✔
977
        p = r = malloc(l * n + 1);
11✔
978
        if (!r)
11✔
979
                return NULL;
980

981
        for (unsigned i = 0; i < n; i++)
40,337✔
982
                p = stpcpy(p, s);
40,326✔
983

984
        *p = 0;
11✔
985
        return r;
11✔
986
}
987

988
int split_pair(const char *s, const char *sep, char **ret_first, char **ret_second) {
1,565✔
989
        assert(s);
1,565✔
990
        assert(!isempty(sep));
1,565✔
991
        assert(ret_first);
1,565✔
992
        assert(ret_second);
1,565✔
993

994
        const char *x = strstr(s, sep);
1,565✔
995
        if (!x)
1,565✔
996
                return -EINVAL;
1,565✔
997

998
        _cleanup_free_ char *a = strndup(s, x - s);
262✔
999
        if (!a)
262✔
1000
                return -ENOMEM;
1001

1002
        _cleanup_free_ char *b = strdup(x + strlen(sep));
262✔
1003
        if (!b)
262✔
1004
                return -ENOMEM;
1005

1006
        *ret_first = TAKE_PTR(a);
262✔
1007
        *ret_second = TAKE_PTR(b);
262✔
1008
        return 0;
262✔
1009
}
1010

1011
int free_and_strdup(char **p, const char *s) {
1,930,495✔
1012
        char *t;
1,930,495✔
1013

1014
        assert(p);
1,930,495✔
1015

1016
        /* Replaces a string pointer with a strdup()ed new string,
1017
         * possibly freeing the old one. */
1018

1019
        if (streq_ptr(*p, s))
1,930,495✔
1020
                return 0;
1,930,495✔
1021

1022
        if (s) {
1,573,809✔
1023
                t = strdup(s);
1,567,091✔
1024
                if (!t)
1,567,091✔
1025
                        return -ENOMEM;
1026
        } else
1027
                t = NULL;
1028

1029
        free_and_replace(*p, t);
1,573,809✔
1030

1031
        return 1;
1,573,809✔
1032
}
1033

1034
int free_and_strdup_warn(char **p, const char *s) {
44,396✔
1035
        int r;
44,396✔
1036

1037
        r = free_and_strdup(p, s);
44,396✔
1038
        if (r < 0)
44,396✔
1039
                return log_oom();
×
1040
        return r;
1041
}
1042

1043
int free_and_strndup(char **p, const char *s, size_t l) {
60,043✔
1044
        char *t;
60,043✔
1045

1046
        assert(p);
60,043✔
1047
        assert(s || l == 0);
60,043✔
1048

1049
        /* Replaces a string pointer with a strndup()ed new string,
1050
         * freeing the old one. */
1051

1052
        if (!*p && !s)
60,043✔
1053
                return 0;
60,043✔
1054

1055
        if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
60,043✔
1056
                return 0;
1057

1058
        if (s) {
28,323✔
1059
                t = strndup(s, l);
28,382✔
1060
                if (!t)
28,382✔
1061
                        return -ENOMEM;
1062
        } else
1063
                t = NULL;
1064

1065
        free_and_replace(*p, t);
28,383✔
1066
        return 1;
28,383✔
1067
}
1068

1069
int strdup_to_full(char **ret, const char *src) {
615,927✔
1070
        if (!src) {
615,927✔
1071
                if (ret)
224,989✔
1072
                        *ret = NULL;
224,988✔
1073

1074
                return 0;
224,989✔
1075
        } else {
1076
                if (ret) {
390,938✔
1077
                        char *t = strdup(src);
390,936✔
1078
                        if (!t)
390,936✔
1079
                                return -ENOMEM;
1080
                        *ret = t;
390,936✔
1081
                }
1082

1083
                return 1;
390,938✔
1084
        }
1085
};
1086

1087
bool string_is_safe(const char *p) {
153,341✔
1088
        if (!p)
153,341✔
1089
                return false;
1090

1091
        /* Checks if the specified string contains no quotes or control characters */
1092

1093
        for (const char *t = p; *t; t++) {
1,756,263✔
1094
                if (*t > 0 && *t < ' ') /* no control characters */
1,602,935✔
1095
                        return false;
1096

1097
                if (strchr(QUOTES "\\\x7f", *t))
1,602,927✔
1098
                        return false;
1099
        }
1100

1101
        return true;
1102
}
1103

1104
bool string_is_safe_ascii(const char *p) {
×
1105
        return ascii_is_valid(p) && string_is_safe(p);
×
1106
}
1107

1108
char* str_realloc(char *p) {
37,871✔
1109
        /* Reallocate *p to actual size. Ignore failure, and return the original string on error. */
1110

1111
        if (!p)
37,871✔
1112
                return NULL;
1113

1114
        return realloc(p, strlen(p) + 1) ?: p;
37,871✔
1115
}
1116

1117
char* string_erase(char *x) {
110✔
1118
        if (!x)
110✔
1119
                return NULL;
1120

1121
        /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1122
         * used them. */
1123
        explicit_bzero_safe(x, strlen(x));
110✔
1124
        return x;
110✔
1125
}
1126

1127
int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
228✔
1128
        const char *p = s, *e = s;
228✔
1129
        bool truncation_applied = false;
228✔
1130
        char *copy;
228✔
1131
        size_t n = 0;
228✔
1132

1133
        assert(s);
228✔
1134

1135
        /* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
1136
         * there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
1137
         * generated either. */
1138

1139
        for (;;) {
458✔
1140
                size_t k;
343✔
1141

1142
                k = strcspn(p, "\n");
343✔
1143

1144
                if (p[k] == 0) {
343✔
1145
                        if (k == 0) /* final empty line */
196✔
1146
                                break;
1147

1148
                        if (n >= n_lines) /* above threshold */
171✔
1149
                                break;
1150

1151
                        e = p + k; /* last line to include */
154✔
1152
                        break;
154✔
1153
                }
1154

1155
                assert(p[k] == '\n');
147✔
1156

1157
                if (n >= n_lines)
147✔
1158
                        break;
1159

1160
                if (k > 0)
115✔
1161
                        e = p + k;
92✔
1162

1163
                p += k + 1;
115✔
1164
                n++;
115✔
1165
        }
1166

1167
        /* e points after the last character we want to keep */
1168
        if (isempty(e))
228✔
1169
                copy = strdup(s);
158✔
1170
        else {
1171
                if (!in_charset(e, "\n")) /* We only consider things truncated if we remove something that
70✔
1172
                                           * isn't a new-line or a series of them */
1173
                        truncation_applied = true;
42✔
1174

1175
                copy = strndup(s, e - s);
70✔
1176
        }
1177
        if (!copy)
228✔
1178
                return -ENOMEM;
1179

1180
        *ret = copy;
228✔
1181
        return truncation_applied;
228✔
1182
}
1183

1184
int string_extract_line(const char *s, size_t i, char **ret) {
163,768✔
1185
        const char *p = s;
163,768✔
1186
        size_t c = 0;
163,768✔
1187

1188
        /* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
1189
         * and == 0 if we are looking at the last line or already beyond the last line. As special
1190
         * optimization, if the first line is requested and the string only consists of one line we return
1191
         * NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
1192
         * common case. */
1193

1194
        for (;;) {
349,990✔
1195
                const char *q;
256,879✔
1196

1197
                q = strchr(p, '\n');
256,879✔
1198
                if (i == c) {
256,879✔
1199
                        /* The line we are looking for! */
1200

1201
                        if (q) {
160,549✔
1202
                                char *m;
3,356✔
1203

1204
                                m = strndup(p, q - p);
3,356✔
1205
                                if (!m)
3,356✔
1206
                                        return -ENOMEM;
1207

1208
                                *ret = m;
3,356✔
1209
                                return !isempty(q + 1); /* More coming? */
6,712✔
1210
                        } else
1211
                                /* Tell the caller to use the input string if equal */
1212
                                return strdup_to(ret, p != s ? p : NULL);
312,965✔
1213
                }
1214

1215
                if (!q)
96,330✔
1216
                        /* No more lines, return empty line */
1217
                        return strdup_to(ret, "");
3,219✔
1218

1219
                p = q + 1;
93,111✔
1220
                c++;
93,111✔
1221
        }
1222
}
1223

1224
int string_contains_word_strv(const char *string, const char *separators, char * const *words, const char **ret_word) {
71✔
1225
        /* In the default mode with no separators specified, we split on whitespace and coalesce separators. */
1226
        const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
71✔
1227
        const char *found = NULL;
71✔
1228
        int r;
196✔
1229

1230
        for (;;) {
321✔
1231
                _cleanup_free_ char *w = NULL;
125✔
1232

1233
                r = extract_first_word(&string, &w, separators, flags);
196✔
1234
                if (r < 0)
196✔
1235
                        return r;
×
1236
                if (r == 0)
196✔
1237
                        break;
1238

1239
                found = strv_find(words, w);
146✔
1240
                if (found)
146✔
1241
                        break;
1242
        }
1243

1244
        if (ret_word)
71✔
1245
                *ret_word = found;
7✔
1246
        return !!found;
71✔
1247
}
1248

1249
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
8,673✔
1250
        if (!s1 && !s2)
8,673✔
1251
                return true;
1252
        if (!s1 || !s2)
8,672✔
1253
                return false;
1254

1255
        if (!ok)
8,670✔
1256
                ok = WHITESPACE;
13✔
1257

1258
        for (; *s1 && *s2; s1++, s2++)
16,408✔
1259
                if (*s1 != *s2)
9,907✔
1260
                        break;
1261

1262
        return in_charset(s1, ok) && in_charset(s2, ok);
10,845✔
1263
}
1264

1265
char* string_replace_char(char *str, char old_char, char new_char) {
601,465✔
1266
        assert(str);
601,465✔
1267
        assert(old_char != '\0');
601,465✔
1268
        assert(new_char != '\0');
601,465✔
1269
        assert(old_char != new_char);
601,465✔
1270

1271
        for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
606,025✔
1272
                *p = new_char;
4,560✔
1273

1274
        return str;
601,465✔
1275
}
1276

1277
int make_cstring(const char *s, size_t n, MakeCStringMode mode, char **ret) {
1,410✔
1278
        char *b;
1,410✔
1279

1280
        assert(s || n == 0);
1,410✔
1281
        assert(mode >= 0);
1,410✔
1282
        assert(mode < _MAKE_CSTRING_MODE_MAX);
1,410✔
1283

1284
        /* Converts a sized character buffer into a NUL-terminated NUL string, refusing if there are embedded
1285
         * NUL bytes. Whether to expect a trailing NUL byte can be specified via 'mode' */
1286

1287
        if (n == 0) {
1,410✔
1288
                if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
20✔
1289
                        return -EINVAL;
1290

1291
                if (!ret)
19✔
1292
                        return 0;
1293

1294
                b = new0(char, 1);
19✔
1295
        } else {
1296
                const char *nul;
1,390✔
1297

1298
                nul = memchr(s, 0, n);
1,390✔
1299
                if (nul) {
1,390✔
1300
                        if (nul < s + n - 1 || /* embedded NUL? */
19✔
1301
                            mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
1302
                                return -EINVAL;
1303

1304
                        n--;
1305
                } else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
1,371✔
1306
                        return -EINVAL;
1307

1308
                if (!ret)
1,375✔
1309
                        return 0;
1310

1311
                b = memdup_suffix0(s, n);
1,375✔
1312
        }
1313
        if (!b)
1,394✔
1314
                return -ENOMEM;
1315

1316
        *ret = b;
1,394✔
1317
        return 0;
1,394✔
1318
}
1319

1320
size_t strspn_from_end(const char *str, const char *accept) {
568,808✔
1321
        size_t n = 0;
568,808✔
1322

1323
        if (isempty(str))
568,808✔
1324
                return 0;
1325

1326
        if (isempty(accept))
568,805✔
1327
                return 0;
1328

1329
        for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
1,122,944✔
1330
                n++;
554,140✔
1331

1332
        return n;
1333
}
1334

1335
char* strdupspn(const char *a, const char *accept) {
×
1336
        if (isempty(a) || isempty(accept))
×
1337
                return strdup("");
×
1338

1339
        return strndup(a, strspn(a, accept));
×
1340
}
1341

1342
char* strdupcspn(const char *a, const char *reject) {
44,704✔
1343
        if (isempty(a))
44,704✔
1344
                return strdup("");
×
1345
        if (isempty(reject))
44,704✔
1346
                return strdup(a);
×
1347

1348
        return strndup(a, strcspn(a, reject));
44,704✔
1349
}
1350

1351
char* find_line_startswith(const char *haystack, const char *needle) {
577✔
1352
        char *p;
577✔
1353

1354
        assert(haystack);
577✔
1355
        assert(needle);
577✔
1356

1357
        /* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
1358
         * first character after it */
1359

1360
        p = strstr(haystack, needle);
577✔
1361
        if (!p)
577✔
1362
                return NULL;
1363

1364
        if (p > haystack)
202✔
1365
                while (p[-1] != '\n') {
18✔
1366
                        p = strstr(p + 1, needle);
9✔
1367
                        if (!p)
9✔
1368
                                return NULL;
1369
                }
1370

1371
        return p + strlen(needle);
201✔
1372
}
1373

1374
char* find_line(const char *haystack, const char *needle) {
×
1375
        char *p;
×
1376

1377
        assert(haystack);
×
1378
        assert(needle);
×
1379

1380
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1381
         * beginning of the line */
1382

1383
        p = find_line_startswith(haystack, needle);
×
1384
        if (!p)
×
1385
                return NULL;
1386

1387
        if (*p == 0 || strchr(NEWLINE, *p))
×
1388
                return p - strlen(needle);
×
1389

1390
        return NULL;
1391
}
1392

1393
char* find_line_after(const char *haystack, const char *needle) {
×
1394
        char *p;
×
1395

1396
        assert(haystack);
×
1397
        assert(needle);
×
1398

1399
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1400
         * next line after it */
1401

1402
        p = find_line_startswith(haystack, needle);
×
1403
        if (!p)
×
1404
                return NULL;
1405

1406
        if (*p == 0)
×
1407
                return p;
1408
        if (strchr(NEWLINE, *p))
×
1409
                return p + 1;
×
1410

1411
        return NULL;
1412
}
1413

1414
bool version_is_valid(const char *s) {
4,035✔
1415
        if (isempty(s))
4,035✔
1416
                return false;
1417

1418
        if (!filename_part_is_valid(s))
4,033✔
1419
                return false;
1420

1421
        /* This is a superset of the characters used by semver. We additionally allow "," and "_". */
1422
        if (!in_charset(s, ALPHANUMERICAL ".,_-+"))
4,033✔
1423
                return false;
×
1424

1425
        return true;
1426
}
1427

1428
bool version_is_valid_versionspec(const char *s) {
76✔
1429
        if (!filename_part_is_valid(s))
76✔
1430
                return false;
1431

1432
        if (!in_charset(s, ALPHANUMERICAL "-.~^"))
76✔
1433
                return false;
×
1434

1435
        return true;
1436
}
1437

1438
ssize_t strlevenshtein(const char *x, const char *y) {
90✔
1439
        _cleanup_free_ size_t *t0 = NULL, *t1 = NULL, *t2 = NULL;
180✔
1440
        size_t xl, yl;
90✔
1441

1442
        /* This is inspired from the Linux kernel's Levenshtein implementation */
1443

1444
        if (streq_ptr(x, y))
90✔
1445
                return 0;
1446

1447
        xl = strlen_ptr(x);
86✔
1448
        if (xl > SSIZE_MAX)
85✔
1449
                return -E2BIG;
1450

1451
        yl = strlen_ptr(y);
86✔
1452
        if (yl > SSIZE_MAX)
85✔
1453
                return -E2BIG;
1454

1455
        if (isempty(x))
86✔
1456
                return yl;
3✔
1457
        if (isempty(y))
83✔
1458
                return xl;
1✔
1459

1460
        t0 = new0(size_t, yl + 1);
82✔
1461
        if (!t0)
82✔
1462
                return -ENOMEM;
1463
        t1 = new0(size_t, yl + 1);
82✔
1464
        if (!t1)
82✔
1465
                return -ENOMEM;
1466
        t2 = new0(size_t, yl + 1);
82✔
1467
        if (!t2)
82✔
1468
                return -ENOMEM;
1469

1470
        for (size_t i = 0; i <= yl; i++)
905✔
1471
                t1[i] = i;
823✔
1472

1473
        for (size_t i = 0; i < xl; i++) {
453✔
1474
                t2[0] = i + 1;
371✔
1475

1476
                for (size_t j = 0; j < yl; j++) {
4,228✔
1477
                        /* Substitution */
1478
                        t2[j+1] = t1[j] + (x[i] != y[j]);
3,857✔
1479

1480
                        /* Swap */
1481
                        if (i > 0 && j > 0 && x[i-1] == y[j] && x[i] == y[j-1] && t2[j+1] > t0[j-1] + 1)
3,857✔
1482
                                t2[j+1] = t0[j-1] + 1;
10✔
1483

1484
                        /* Deletion */
1485
                        if (t2[j+1] > t1[j+1] + 1)
3,857✔
1486
                                t2[j+1] = t1[j+1] + 1;
141✔
1487

1488
                        /* Insertion */
1489
                        if (t2[j+1] > t2[j] + 1)
3,857✔
1490
                                t2[j+1] = t2[j] + 1;
638✔
1491
                }
1492

1493
                size_t *dummy = t0;
1494
                t0 = t1;
1495
                t1 = t2;
1496
                t2 = dummy;
1497
        }
1498

1499
        return t1[yl];
82✔
1500
}
1501

1502
char* strrstr(const char *haystack, const char *needle) {
7,261✔
1503
        /* Like strstr() but returns the last rather than the first occurrence of "needle" in "haystack". */
1504

1505
        if (!haystack || !needle)
7,261✔
1506
                return NULL;
1507

1508
        /* Special case: for the empty string we return the very last possible occurrence, i.e. *after* the
1509
         * last char, not before. */
1510
        if (*needle == 0)
7,258✔
1511
                return strchr(haystack, 0);
2✔
1512

1513
        for (const char *p = strstr(haystack, needle), *q; p; p = q) {
7,266✔
1514
                q = strstr(p + 1, needle);
25✔
1515
                if (!q)
25✔
1516
                        return (char *) p;
1517
        }
1518
        return NULL;
1519
}
1520

1521
size_t str_common_prefix(const char *a, const char *b) {
16✔
1522
        assert(a);
16✔
1523
        assert(b);
16✔
1524

1525
        /* Returns the length of the common prefix of the two specified strings, or SIZE_MAX in case the
1526
         * strings are fully identical. */
1527

1528
        for (size_t n = 0;; n++) {
39✔
1529
                char c = a[n];
55✔
1530
                if (c != b[n])
55✔
1531
                        return n;
1532
                if (c == 0)
42✔
1533
                        return SIZE_MAX;
1534
        }
1535
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc