Coverage Report

Created: 2026-08-25 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gstreamer/subprojects/glib-2.86.3/glib/gstrfuncs.c
Line
Count
Source
1
/* GLIB - Library of useful routines for C programming
2
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3
 *
4
 * SPDX-License-Identifier: LGPL-2.1-or-later
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
/*
21
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22
 * file for a list of people on the GLib Team.  See the ChangeLog
23
 * files for a list of changes.  These files are distributed with
24
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
25
 */
26
27
/*
28
 * MT safe
29
 */
30
31
#include "config.h"
32
33
#include <stdarg.h>
34
#include <stdio.h>
35
#include <stdlib.h>
36
#include <locale.h>
37
#include <string.h>
38
#include <locale.h>
39
#include <errno.h>
40
#include <garray.h>
41
#include <ctype.h>              /* For tolower() */
42
43
#ifdef HAVE_XLOCALE_H
44
/* Needed on BSD/OS X for e.g. strtod_l */
45
#include <xlocale.h>
46
#endif
47
48
#ifdef G_OS_WIN32
49
#include <windows.h>
50
#endif
51
52
/* do not include <unistd.h> here, it may interfere with g_strsignal() */
53
54
#include "gstrfuncs.h"
55
56
#include "gprintf.h"
57
#include "gprintfint.h"
58
#include "glibintl.h"
59
60
/**
61
 * g_ascii_isalnum:
62
 * @c: any character
63
 *
64
 * Determines whether a character is alphanumeric.
65
 *
66
 * Unlike the standard C library `isalnum()` function, this only
67
 * recognizes standard ASCII letters and ignores the locale,
68
 * returning false for all non-ASCII characters. Also, unlike
69
 * the standard library function, this takes a `char`, not an `int`,
70
 * so don't call it on `EOF`, but no need to cast to `guchar` before
71
 * passing a possibly non-ASCII character in.
72
 *
73
 * Returns: true if @c is an ASCII alphanumeric character
74
 */
75
76
/**
77
 * g_ascii_isalpha:
78
 * @c: any character
79
 *
80
 * Determines whether a character is alphabetic (i.e. a letter).
81
 *
82
 * Unlike the standard C library `isalpha()` function, this only
83
 * recognizes standard ASCII letters and ignores the locale,
84
 * returning false for all non-ASCII characters. Also, unlike
85
 * the standard library function, this takes a `char`, not an `int`,
86
 * so don't call it on `EOF`, but no need to cast to `guchar` before
87
 * passing a possibly non-ASCII character in.
88
 *
89
 * Returns: true if @c is an ASCII alphabetic character
90
 */
91
92
/**
93
 * g_ascii_iscntrl:
94
 * @c: any character
95
 *
96
 * Determines whether a character is a control character.
97
 *
98
 * Unlike the standard C library `iscntrl()` function, this only
99
 * recognizes standard ASCII control characters and ignores the
100
 * locale, returning false for all non-ASCII characters. Also,
101
 * unlike the standard library function, this takes a `char`, not
102
 * an `int`, so don't call it on `EOF`, but no need to cast to `guchar`
103
 * before passing a possibly non-ASCII character in.
104
 *
105
 * Returns: true if @c is an ASCII control character
106
 */
107
108
/**
109
 * g_ascii_isdigit:
110
 * @c: any character
111
 *
112
 * Determines whether a character is digit (0-9).
113
 *
114
 * Unlike the standard C library `isdigit()` function, this takes
115
 * a `char`, not an `int`, so don't call it  on `EOF`, but no need to
116
 * cast to `guchar` before passing a possibly non-ASCII character in.
117
 *
118
 * Returns: true if @c is an ASCII digit
119
 */
120
121
/**
122
 * g_ascii_isgraph:
123
 * @c: any character
124
 *
125
 * Determines whether a character is a printing character and not a space.
126
 *
127
 * Unlike the standard C library `isgraph()` function, this only
128
 * recognizes standard ASCII characters and ignores the locale,
129
 * returning false for all non-ASCII characters. Also, unlike
130
 * the standard library function, this takes a `char`, not an `int`,
131
 * so don't call it on `EOF`, but no need to cast to `guchar` before
132
 * passing a possibly non-ASCII character in.
133
 *
134
 * Returns: true if @c is an ASCII printing character other than space
135
 */
136
137
/**
138
 * g_ascii_islower:
139
 * @c: any character
140
 *
141
 * Determines whether a character is an ASCII lower case letter.
142
 *
143
 * Unlike the standard C library `islower()` function, this only
144
 * recognizes standard ASCII letters and ignores the locale,
145
 * returning false for all non-ASCII characters. Also, unlike
146
 * the standard library function, this takes a `char`, not an `int`,
147
 * so don't call it on `EOF`, but no need to worry about casting
148
 * to `guchar` before passing a possibly non-ASCII character in.
149
 *
150
 * Returns: true if @c is an ASCII lower case letter
151
 */
152
153
/**
154
 * g_ascii_isprint:
155
 * @c: any character
156
 *
157
 * Determines whether a character is a printing character.
158
 *
159
 * Unlike the standard C library `isprint()` function, this only
160
 * recognizes standard ASCII characters and ignores the locale,
161
 * returning false for all non-ASCII characters. Also, unlike
162
 * the standard library function, this takes a `char`, not an `int`,
163
 * so don't call it on `EOF`, but no need to cast to `guchar` before
164
 * passing a possibly non-ASCII character in.
165
 *
166
 * Returns: true if @c is an ASCII printing character
167
 */
168
169
/**
170
 * g_ascii_ispunct:
171
 * @c: any character
172
 *
173
 * Determines whether a character is a punctuation character.
174
 *
175
 * Unlike the standard C library `ispunct()` function, this only
176
 * recognizes standard ASCII letters and ignores the locale,
177
 * returning false for all non-ASCII characters. Also, unlike
178
 * the standard library function, this takes a `char`, not an `int`,
179
 * so don't call it on `EOF`, but no need to cast to `guchar` before
180
 * passing a possibly non-ASCII character in.
181
 *
182
 * Returns: true if @c is an ASCII punctuation character
183
 */
184
185
/**
186
 * g_ascii_isspace:
187
 * @c: any character
188
 *
189
 * Determines whether a character is a white-space character.
190
 *
191
 * Unlike the standard C library `isspace()` function, this only
192
 * recognizes standard ASCII white-space and ignores the locale,
193
 * returning false for all non-ASCII characters. Also, unlike
194
 * the standard library function, this takes a `char`, not an `int`,
195
 * so don't call it on `EOF`, but no need to cast to `guchar` before
196
 * passing a possibly non-ASCII character in.
197
 *
198
 * Returns: true if @c is an ASCII white-space character
199
 */
200
201
/**
202
 * g_ascii_isupper:
203
 * @c: any character
204
 *
205
 * Determines whether a character is an ASCII upper case letter.
206
 *
207
 * Unlike the standard C library `isupper()` function, this only
208
 * recognizes standard ASCII letters and ignores the locale,
209
 * returning false for all non-ASCII characters. Also, unlike
210
 * the standard library function, this takes a `char`, not an `int`,
211
 * so don't call it on `EOF`, but no need to worry about casting
212
 * to `guchar` before passing a possibly non-ASCII character in.
213
 *
214
 * Returns: true if @c is an ASCII upper case letter
215
 */
216
217
/**
218
 * g_ascii_isxdigit:
219
 * @c: any character
220
 *
221
 * Determines whether a character is a hexadecimal-digit character.
222
 *
223
 * Unlike the standard C library `isxdigit()` function, this takes
224
 * a `char`, not an `int`, so don't call it on `EOF`, but no need to
225
 * cast to `guchar` before passing a possibly non-ASCII character in.
226
 *
227
 * Returns: true if @c is an ASCII hexadecimal-digit character
228
 */
229
230
/**
231
 * G_ASCII_DTOSTR_BUF_SIZE:
232
 *
233
 * A good size for a buffer to be passed into [func@GLib.ascii_dtostr].
234
 * It is guaranteed to be enough for all output of that function
235
 * on systems with 64bit IEEE-compatible doubles.
236
 *
237
 * The typical usage would be something like:
238
 * ```C
239
 * char buf[G_ASCII_DTOSTR_BUF_SIZE];
240
 *
241
 * fprintf (out, "value=%s\n", g_ascii_dtostr (buf, sizeof (buf), value));
242
 * ```
243
 */
244
245
/**
246
 * g_strstrip:
247
 * @string: a string to remove the leading and trailing whitespace from
248
 *
249
 * Removes leading and trailing whitespace from a string.
250
 *
251
 * See [func@GLib.strchomp] and [func@GLib.strchug].
252
 *
253
 * Returns: @string
254
 */
255
256
/**
257
 * G_STR_DELIMITERS:
258
 *
259
 * The standard delimiters, used in [func@GLib.strdelimit].
260
 */
261
262
static const guint16 ascii_table_data[256] = {
263
  0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
264
  0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004,
265
  0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
266
  0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
267
  0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
268
  0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
269
  0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459,
270
  0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
271
  0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253,
272
  0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
273
  0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
274
  0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
275
  0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073,
276
  0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
277
  0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
278
  0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004
279
  /* the upper 128 are all zeroes */
280
};
281
282
const guint16 * const g_ascii_table = ascii_table_data;
283
284
#if defined(HAVE_NEWLOCALE) && \
285
    defined(HAVE_USELOCALE)
286
#define USE_XLOCALE 1
287
#endif
288
289
#ifdef USE_XLOCALE
290
static locale_t
291
get_C_locale (void)
292
1.08M
{
293
1.08M
  static gsize initialized = FALSE;
294
1.08M
  static locale_t C_locale = NULL;
295
296
1.08M
  if (g_once_init_enter (&initialized))
297
9
    {
298
9
      C_locale = newlocale (LC_ALL_MASK, "C", NULL);
299
9
      g_once_init_leave (&initialized, TRUE);
300
9
    }
301
302
1.08M
  return C_locale;
303
1.08M
}
304
#endif
305
306
/**
307
 * g_strdup:
308
 * @str: (nullable): the string to duplicate
309
 *
310
 * Duplicates a string. If @str is `NULL` it returns `NULL`.
311
 *
312
 * Returns: a newly-allocated copy of @str
313
 */
314
gchar*
315
(g_strdup) (const gchar *str)
316
6.23M
{
317
6.23M
  gchar *new_str;
318
6.23M
  gsize length;
319
320
6.23M
  if G_LIKELY (str)
321
6.21M
    {
322
6.21M
      length = strlen (str) + 1;
323
6.21M
      new_str = g_new (char, length);
324
6.21M
      memcpy (new_str, str, length);
325
6.21M
    }
326
23.2k
  else
327
23.2k
    new_str = NULL;
328
329
6.23M
  return new_str;
330
6.23M
}
331
332
/**
333
 * g_memdup:
334
 * @mem: the memory to copy
335
 * @byte_size: the number of bytes to copy
336
 *
337
 * Allocates @byte_size bytes of memory, and copies @byte_size bytes into it
338
 * from @mem. If @mem is `NULL` it returns `NULL`.
339
 *
340
 * Returns: (transfer full) (nullable): a pointer to the newly-allocated copy of the memory
341
 *
342
 * Deprecated: 2.68: Use [func@GLib.memdup2] instead, as it accepts a gsize argument
343
 *   for @byte_size, avoiding the possibility of overflow in a `gsize` → `guint`
344
 *   conversion
345
 */
346
gpointer
347
g_memdup (gconstpointer mem,
348
          guint         byte_size)
349
0
{
350
0
  gpointer new_mem;
351
352
0
  if (mem && byte_size != 0)
353
0
    {
354
0
      new_mem = g_malloc (byte_size);
355
0
      memcpy (new_mem, mem, byte_size);
356
0
    }
357
0
  else
358
0
    new_mem = NULL;
359
360
0
  return new_mem;
361
0
}
362
363
/**
364
 * g_memdup2:
365
 * @mem: (nullable): the memory to copy
366
 * @byte_size: the number of bytes to copy
367
 *
368
 * Allocates @byte_size bytes of memory, and copies @byte_size bytes into it
369
 * from @mem. If @mem is `NULL` it returns `NULL`.
370
 *
371
 * This replaces [func@GLib.memdup], which was prone to integer overflows when
372
 * converting the argument from a `gsize` to a `guint`.
373
 *
374
 * Returns: (transfer full) (nullable): a pointer to the newly-allocated copy of the memory
375
 *
376
 * Since: 2.68
377
 */
378
gpointer
379
g_memdup2 (gconstpointer mem,
380
           gsize         byte_size)
381
700k
{
382
700k
  gpointer new_mem;
383
384
700k
  if (mem && byte_size != 0)
385
657k
    {
386
657k
      new_mem = g_malloc (byte_size);
387
657k
      memcpy (new_mem, mem, byte_size);
388
657k
    }
389
43.3k
  else
390
43.3k
    new_mem = NULL;
391
392
700k
  return new_mem;
393
700k
}
394
395
/**
396
 * g_strndup:
397
 * @str: (nullable): the string to duplicate
398
 * @n: the maximum number of bytes to copy from @str
399
 *
400
 * Duplicates the first @n bytes of a string, returning a newly-allocated
401
 * buffer @n + 1 bytes long which will always be nul-terminated. If @str
402
 * is less than @n bytes long the buffer is padded with nuls. If @str is
403
 * `NULL` it returns `NULL`.
404
 *
405
 * To copy a number of characters from a UTF-8 encoded string,
406
 * use [func@GLib.utf8_strncpy] instead.
407
 *
408
 * Returns: (nullable): a newly-allocated buffer containing the first
409
 *    @n bytes of @str
410
 */
411
gchar*
412
g_strndup (const gchar *str,
413
           gsize        n)
414
2.45M
{
415
2.45M
  gchar *new_str;
416
417
2.45M
  if (str)
418
2.45M
    {
419
2.45M
      g_return_val_if_fail (n < G_MAXSIZE, NULL);
420
421
2.45M
      new_str = g_new (gchar, n + 1);
422
2.45M
      strncpy (new_str, str, n);
423
2.45M
      new_str[n] = '\0';
424
2.45M
    }
425
0
  else
426
0
    new_str = NULL;
427
428
2.45M
  return new_str;
429
2.45M
}
430
431
/**
432
 * g_strnfill:
433
 * @length: the length of the new string
434
 * @fill_char: the byte to fill the string with
435
 *
436
 * Creates a new string @length bytes long filled with @fill_char.
437
 *
438
 * Returns: a newly-allocated string filled with @fill_char
439
 */
440
gchar*
441
g_strnfill (gsize length,
442
            gchar fill_char)
443
0
{
444
0
  gchar *str;
445
446
0
  g_return_val_if_fail (length < G_MAXSIZE, NULL);
447
448
0
  str = g_new (gchar, length + 1);
449
0
  memset (str, (guchar)fill_char, length);
450
0
  str[length] = '\0';
451
452
0
  return str;
453
0
}
454
455
/**
456
 * g_stpcpy:
457
 * @dest: destination buffer
458
 * @src: source string
459
 *
460
 * Copies a nul-terminated string into the destination buffer, including
461
 * the trailing nul byte, and returns a pointer to the trailing nul byte
462
 * in `dest`.  The return value is useful for concatenating multiple
463
 * strings without having to repeatedly scan for the end.
464
 *
465
 * Returns: a pointer to the trailing nul byte in `dest`
466
 **/
467
gchar *
468
g_stpcpy (gchar       *dest,
469
          const gchar *src)
470
786k
{
471
786k
#ifdef HAVE_STPCPY
472
786k
  g_return_val_if_fail (dest != NULL, NULL);
473
786k
  g_return_val_if_fail (src != NULL, NULL);
474
786k
  return stpcpy (dest, src);
475
#else
476
  gchar *d = dest;
477
  const gchar *s = src;
478
479
  g_return_val_if_fail (dest != NULL, NULL);
480
  g_return_val_if_fail (src != NULL, NULL);
481
  do
482
    *d++ = *s;
483
  while (*s++ != '\0');
484
485
  return d - 1;
486
#endif
487
786k
}
488
489
/**
490
 * g_strdup_vprintf:
491
 * @format: (not nullable): a standard `printf()` format string, but notice
492
 *   [string precision pitfalls](string-utils.html#string-precision-pitfalls)
493
 * @args: the list of parameters to insert into the format string
494
 *
495
 * Similar to the standard C `vsprintf()` function but safer, since it
496
 * calculates the maximum space required and allocates memory to hold
497
 * the result.
498
 *
499
 * The returned string is guaranteed to be non-NULL, unless @format
500
 * contains `%lc` or `%ls` conversions, which can fail if no multibyte
501
 * representation is available for the given character.
502
 *
503
 * See also [func@GLib.vasprintf], which offers the same functionality, but
504
 * additionally returns the length of the allocated string.
505
 *
506
 * Returns: (nullable) (transfer full): a newly-allocated string holding the
507
 *   result
508
 */
509
gchar*
510
g_strdup_vprintf (const gchar *format,
511
                  va_list      args)
512
1.36M
{
513
1.36M
  gchar *string = NULL;
514
515
1.36M
  g_vasprintf (&string, format, args);
516
517
1.36M
  return string;
518
1.36M
}
519
520
/**
521
 * g_strdup_printf:
522
 * @format: (not nullable): a standard `printf()` format string, but notice
523
 *   [string precision pitfalls](string-utils.html#string-precision-pitfalls)
524
 * @...: the parameters to insert into the format string
525
 *
526
 * Similar to the standard C `sprintf()` function but safer, since it
527
 * calculates the maximum space required and allocates memory to hold
528
 * the result.
529
 *
530
 * The returned string is guaranteed to be non-NULL, unless @format
531
 * contains `%lc` or `%ls` conversions, which can fail if no multibyte
532
 * representation is available for the given character.
533
 *
534
 * Returns: (nullable) (transfer full): a newly-allocated string holding the
535
 *   result
536
 */
537
gchar*
538
g_strdup_printf (const gchar *format,
539
                 ...)
540
1.28M
{
541
1.28M
  gchar *buffer;
542
1.28M
  va_list args;
543
544
1.28M
  va_start (args, format);
545
1.28M
  buffer = g_strdup_vprintf (format, args);
546
1.28M
  va_end (args);
547
548
1.28M
  return buffer;
549
1.28M
}
550
551
/**
552
 * g_strconcat:
553
 * @string1: the first string to add, which must not be `NULL`
554
 * @...: a `NULL`-terminated list of strings to append to the string
555
 *
556
 * Concatenates all of the given strings into one long string.
557
 *
558
 * The variable argument list must end with `NULL`. If you forget the `NULL`,
559
 * `g_strconcat()` will start appending random memory junk to your string.
560
 *
561
 * Note that this function is usually not the right function to use to
562
 * assemble a translated message from pieces, since proper translation
563
 * often requires the pieces to be reordered.
564
 *
565
 * Returns: a newly-allocated string containing all the string arguments
566
 */
567
gchar*
568
g_strconcat (const gchar *string1, ...)
569
52.8k
{
570
52.8k
  gsize   l;
571
52.8k
  va_list args;
572
52.8k
  gchar   *s;
573
52.8k
  gchar   *concat;
574
52.8k
  gchar   *ptr;
575
576
52.8k
  if (!string1)
577
0
    return NULL;
578
579
52.8k
  l = 1 + strlen (string1);
580
52.8k
  va_start (args, string1);
581
52.8k
  s = va_arg (args, gchar*);
582
161k
  while (s)
583
108k
    {
584
108k
      l += strlen (s);
585
108k
      s = va_arg (args, gchar*);
586
108k
    }
587
52.8k
  va_end (args);
588
589
52.8k
  concat = g_new (gchar, l);
590
52.8k
  ptr = concat;
591
592
52.8k
  ptr = g_stpcpy (ptr, string1);
593
52.8k
  va_start (args, string1);
594
52.8k
  s = va_arg (args, gchar*);
595
161k
  while (s)
596
108k
    {
597
108k
      ptr = g_stpcpy (ptr, s);
598
108k
      s = va_arg (args, gchar*);
599
108k
    }
600
52.8k
  va_end (args);
601
602
52.8k
  return concat;
603
52.8k
}
604
605
/**
606
 * g_strtod:
607
 * @nptr: the string to convert to a numeric value
608
 * @endptr: (out) (transfer none) (optional): if non-`NULL`, it returns the
609
 *   character after the last character used in the conversion
610
 *
611
 * Converts a string to a floating point value.
612
 *
613
 * It calls the standard `strtod()` function to handle the conversion, but
614
 * if the string is not completely converted it attempts the conversion
615
 * again with [func@GLib.ascii_strtod], and returns the best match.
616
 *
617
 * This function should seldom be used. The normal situation when reading
618
 * numbers not for human consumption is to use [func@GLib.ascii_strtod]. Only when
619
 * you know that you must expect both locale formatted and C formatted numbers
620
 * should you use this. Make sure that you don't pass strings such as comma
621
 * separated lists of values, since the commas may be interpreted as a decimal
622
 * point in some locales, causing unexpected results.
623
 *
624
 * Returns: the converted value
625
 **/
626
gdouble
627
g_strtod (const gchar *nptr,
628
          gchar      **endptr)
629
1.54k
{
630
1.54k
  gchar *fail_pos_1;
631
1.54k
  gchar *fail_pos_2;
632
1.54k
  gdouble val_1;
633
1.54k
  gdouble val_2 = 0;
634
635
1.54k
  g_return_val_if_fail (nptr != NULL, 0);
636
637
1.54k
  fail_pos_1 = NULL;
638
1.54k
  fail_pos_2 = NULL;
639
640
1.54k
  val_1 = strtod (nptr, &fail_pos_1);
641
642
1.54k
  if (fail_pos_1 && fail_pos_1[0] != 0)
643
1.43k
    val_2 = g_ascii_strtod (nptr, &fail_pos_2);
644
645
1.54k
  if (!fail_pos_1 || fail_pos_1[0] == 0 || fail_pos_1 >= fail_pos_2)
646
1.54k
    {
647
1.54k
      if (endptr)
648
0
        *endptr = fail_pos_1;
649
1.54k
      return val_1;
650
1.54k
    }
651
0
  else
652
0
    {
653
0
      if (endptr)
654
0
        *endptr = fail_pos_2;
655
0
      return val_2;
656
0
    }
657
1.54k
}
658
659
/**
660
 * g_ascii_strtod:
661
 * @nptr: the string to convert to a numeric value
662
 * @endptr: (out) (transfer none) (optional): if non-`NULL`, it returns the
663
 *   character after the last character used in the conversion
664
 *
665
 * Converts a string to a floating point value.
666
 *
667
 * This function behaves like the standard `strtod()` function
668
 * does in the C locale. It does this without actually changing
669
 * the current locale, since that would not be thread-safe.
670
 * A limitation of the implementation is that this function
671
 * will still accept localized versions of infinities and NANs.
672
 *
673
 * This function is typically used when reading configuration
674
 * files or other non-user input that should be locale independent.
675
 * To handle input from the user you should normally use the
676
 * locale-sensitive system `strtod()` function.
677
 *
678
 * To convert from a gdouble to a string in a locale-insensitive
679
 * way, use [func@GLib.ascii_dtostr].
680
 *
681
 * If the correct value would cause overflow, plus or minus `HUGE_VAL`
682
 * is returned (according to the sign of the value), and `ERANGE` is
683
 * stored in `errno`. If the correct value would cause underflow,
684
 * zero is returned and `ERANGE` is stored in `errno`.
685
 *
686
 * This function resets `errno` before calling `strtod()` so that
687
 * you can reliably detect overflow and underflow.
688
 *
689
 * Returns: the converted value
690
 */
691
gdouble
692
g_ascii_strtod (const gchar *nptr,
693
                gchar      **endptr)
694
511k
{
695
511k
#if defined(USE_XLOCALE) && defined(HAVE_STRTOD_L)
696
511k
  locale_t c_locale;
697
698
511k
  g_return_val_if_fail (nptr != NULL, 0);
699
700
511k
  c_locale = get_C_locale ();
701
511k
  errno = 0;
702
703
511k
  return strtod_l (nptr, endptr, c_locale);
704
705
#else
706
707
  gchar *fail_pos;
708
  gdouble val;
709
#ifndef __BIONIC__
710
  struct lconv *locale_data;
711
#endif
712
  const char *decimal_point;
713
  gsize decimal_point_len;
714
  const char *p, *decimal_point_pos;
715
  const char *end = NULL; /* Silence gcc */
716
  int strtod_errno;
717
718
  g_return_val_if_fail (nptr != NULL, 0);
719
720
  fail_pos = NULL;
721
722
#ifndef __BIONIC__
723
  locale_data = localeconv ();
724
  decimal_point = locale_data->decimal_point;
725
  decimal_point_len = strlen (decimal_point);
726
#else
727
  decimal_point = ".";
728
  decimal_point_len = 1;
729
#endif
730
731
  g_assert (decimal_point_len != 0);
732
733
  decimal_point_pos = NULL;
734
  end = NULL;
735
736
  if (decimal_point[0] != '.' ||
737
      decimal_point[1] != 0)
738
    {
739
      p = nptr;
740
      /* Skip leading space */
741
      while (g_ascii_isspace (*p))
742
        p++;
743
744
      /* Skip leading optional sign */
745
      if (*p == '+' || *p == '-')
746
        p++;
747
748
      if (p[0] == '0' &&
749
          (p[1] == 'x' || p[1] == 'X'))
750
        {
751
          p += 2;
752
          /* HEX - find the (optional) decimal point */
753
754
          while (g_ascii_isxdigit (*p))
755
            p++;
756
757
          if (*p == '.')
758
            decimal_point_pos = p++;
759
760
          while (g_ascii_isxdigit (*p))
761
            p++;
762
763
          if (*p == 'p' || *p == 'P')
764
            p++;
765
          if (*p == '+' || *p == '-')
766
            p++;
767
          while (g_ascii_isdigit (*p))
768
            p++;
769
770
          end = p;
771
        }
772
      else if (g_ascii_isdigit (*p) || *p == '.')
773
        {
774
          while (g_ascii_isdigit (*p))
775
            p++;
776
777
          if (*p == '.')
778
            decimal_point_pos = p++;
779
780
          while (g_ascii_isdigit (*p))
781
            p++;
782
783
          if (*p == 'e' || *p == 'E')
784
            p++;
785
          if (*p == '+' || *p == '-')
786
            p++;
787
          while (g_ascii_isdigit (*p))
788
            p++;
789
790
          end = p;
791
        }
792
      /* For the other cases, we need not convert the decimal point */
793
    }
794
795
  if (decimal_point_pos)
796
    {
797
      char *copy, *c;
798
799
      /* We need to convert the '.' to the locale specific decimal point */
800
      copy = g_malloc (end - nptr + 1 + decimal_point_len);
801
802
      c = copy;
803
      memcpy (c, nptr, decimal_point_pos - nptr);
804
      c += decimal_point_pos - nptr;
805
      memcpy (c, decimal_point, decimal_point_len);
806
      c += decimal_point_len;
807
      memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
808
      c += end - (decimal_point_pos + 1);
809
      *c = 0;
810
811
      errno = 0;
812
      val = strtod (copy, &fail_pos);
813
      strtod_errno = errno;
814
815
      if (fail_pos)
816
        {
817
          if (fail_pos - copy > decimal_point_pos - nptr)
818
            fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
819
          else
820
            fail_pos = (char *)nptr + (fail_pos - copy);
821
        }
822
823
      g_free (copy);
824
825
    }
826
  else if (end)
827
    {
828
      char *copy;
829
830
      copy = g_malloc (end - (char *)nptr + 1);
831
      memcpy (copy, nptr, end - nptr);
832
      *(copy + (end - (char *)nptr)) = 0;
833
834
      errno = 0;
835
      val = strtod (copy, &fail_pos);
836
      strtod_errno = errno;
837
838
      if (fail_pos)
839
        {
840
          fail_pos = (char *)nptr + (fail_pos - copy);
841
        }
842
843
      g_free (copy);
844
    }
845
  else
846
    {
847
      errno = 0;
848
      val = strtod (nptr, &fail_pos);
849
      strtod_errno = errno;
850
    }
851
852
  if (endptr)
853
    *endptr = fail_pos;
854
855
  errno = strtod_errno;
856
857
  return val;
858
#endif
859
511k
}
860
861
862
/**
863
 * g_ascii_dtostr:
864
 * @buffer: a buffer to place the resulting string in
865
 * @buf_len: the length of the buffer
866
 * @d: the value to convert
867
 *
868
 * Converts a `gdouble` to a string, using the '.' as
869
 * decimal point.
870
 *
871
 * This function generates enough precision that converting
872
 * the string back using [func@GLib.ascii_strtod] gives the same machine-number
873
 * (on machines with IEEE compatible 64bit doubles). It is
874
 * guaranteed that the size of the resulting string will never
875
 * be larger than [const@GLib.ASCII_DTOSTR_BUF_SIZE] bytes, including the terminating
876
 * nul character, which is always added.
877
 *
878
 * Returns: the pointer to the buffer with the converted string
879
 **/
880
gchar *
881
g_ascii_dtostr (gchar       *buffer,
882
                gint         buf_len,
883
                gdouble      d)
884
0
{
885
0
  return g_ascii_formatd (buffer, buf_len, "%.17g", d);
886
0
}
887
888
#pragma GCC diagnostic push
889
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
890
891
/**
892
 * g_ascii_formatd:
893
 * @buffer: a buffer to place the resulting string in
894
 * @buf_len: the length of the buffer
895
 * @format: the `printf()`-style format to use for the
896
 *   code to use for converting
897
 * @d: the value to convert
898
 *
899
 * Converts a `gdouble` to a string, using the '.' as
900
 * decimal point. To format the number you pass in
901
 * a `printf()`-style format string. Allowed conversion
902
 * specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.
903
 *
904
 * The @format must just be a single format specifier
905
 * starting with `%`, expecting a `gdouble` argument.
906
 *
907
 * The returned buffer is guaranteed to be nul-terminated.
908
 *
909
 * If you just want to want to serialize the value into a
910
 * string, use [func@GLib.ascii_dtostr].
911
 *
912
 * Returns: the pointer to the buffer with the converted string
913
 */
914
gchar *
915
g_ascii_formatd (gchar       *buffer,
916
                 gint         buf_len,
917
                 const gchar *format,
918
                 gdouble      d)
919
0
{
920
0
#ifdef USE_XLOCALE
921
0
  locale_t old_locale;
922
923
0
  g_return_val_if_fail (buffer != NULL, NULL);
924
0
  g_return_val_if_fail (format[0] == '%', NULL);
925
0
  g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL);
926
927
0
  old_locale = uselocale (get_C_locale ());
928
0
   _g_snprintf (buffer, buf_len, format, d);
929
0
  uselocale (old_locale);
930
931
0
  return buffer;
932
#else
933
#ifndef __BIONIC__
934
  struct lconv *locale_data;
935
#endif
936
  const char *decimal_point;
937
  gsize decimal_point_len;
938
  gchar *p;
939
  size_t rest_len;
940
  gchar format_char;
941
942
  g_return_val_if_fail (buffer != NULL, NULL);
943
  g_return_val_if_fail (format[0] == '%', NULL);
944
  g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL);
945
946
  format_char = format[strlen (format) - 1];
947
948
  g_return_val_if_fail (format_char == 'e' || format_char == 'E' ||
949
                        format_char == 'f' || format_char == 'F' ||
950
                        format_char == 'g' || format_char == 'G',
951
                        NULL);
952
953
  if (format[0] != '%')
954
    return NULL;
955
956
  if (strpbrk (format + 1, "'l%"))
957
    return NULL;
958
959
  if (!(format_char == 'e' || format_char == 'E' ||
960
        format_char == 'f' || format_char == 'F' ||
961
        format_char == 'g' || format_char == 'G'))
962
    return NULL;
963
964
  _g_snprintf (buffer, buf_len, format, d);
965
966
#ifndef __BIONIC__
967
  locale_data = localeconv ();
968
  decimal_point = locale_data->decimal_point;
969
  decimal_point_len = strlen (decimal_point);
970
#else
971
  decimal_point = ".";
972
  decimal_point_len = 1;
973
#endif
974
975
  g_assert (decimal_point_len != 0);
976
977
  if (decimal_point[0] != '.' ||
978
      decimal_point[1] != 0)
979
    {
980
      p = buffer;
981
982
      while (g_ascii_isspace (*p))
983
        p++;
984
985
      if (*p == '+' || *p == '-')
986
        p++;
987
988
      while (isdigit ((guchar)*p))
989
        p++;
990
991
      if (strncmp (p, decimal_point, decimal_point_len) == 0)
992
        {
993
          *p = '.';
994
          p++;
995
          if (decimal_point_len > 1)
996
            {
997
              rest_len = strlen (p + (decimal_point_len - 1));
998
              memmove (p, p + (decimal_point_len - 1), rest_len);
999
              p[rest_len] = 0;
1000
            }
1001
        }
1002
    }
1003
1004
  return buffer;
1005
#endif
1006
0
}
1007
#pragma GCC diagnostic pop
1008
1009
#define ISSPACE(c)              ((c) == ' ' || (c) == '\f' || (c) == '\n' || \
1010
                                 (c) == '\r' || (c) == '\t' || (c) == '\v')
1011
18.7M
#define ISUPPER(c)              ((c) >= 'A' && (c) <= 'Z')
1012
#define ISLOWER(c)              ((c) >= 'a' && (c) <= 'z')
1013
#define ISALPHA(c)              (ISUPPER (c) || ISLOWER (c))
1014
#define TOUPPER(c)              (ISLOWER (c) ? (c) - 'a' + 'A' : (c))
1015
18.7M
#define TOLOWER(c)              (ISUPPER (c) ? (c) - 'A' + 'a' : (c))
1016
1017
#if !defined(USE_XLOCALE) || !defined(HAVE_STRTOULL_L) || !defined(HAVE_STRTOLL_L)
1018
1019
static guint64
1020
g_parse_long_long (const gchar  *nptr,
1021
                   const gchar **endptr,
1022
                   guint         base,
1023
                   gboolean     *negative)
1024
{
1025
  /* this code is based on the strtol(3) code from GNU libc released under
1026
   * the GNU Lesser General Public License.
1027
   *
1028
   * Copyright (C) 1991,92,94,95,96,97,98,99,2000,01,02
1029
   *        Free Software Foundation, Inc.
1030
   */
1031
  gboolean overflow;
1032
  guint64 cutoff;
1033
  guint64 cutlim;
1034
  guint64 ui64;
1035
  const gchar *s, *save;
1036
  guchar c;
1037
1038
  g_return_val_if_fail (nptr != NULL, 0);
1039
1040
  *negative = FALSE;
1041
  if (base == 1 || base > 36)
1042
    {
1043
      errno = EINVAL;
1044
      if (endptr)
1045
        *endptr = nptr;
1046
      return 0;
1047
    }
1048
1049
  save = s = nptr;
1050
1051
  /* Skip white space.  */
1052
  while (ISSPACE (*s))
1053
    ++s;
1054
1055
  if (G_UNLIKELY (!*s))
1056
    goto noconv;
1057
1058
  /* Check for a sign.  */
1059
  if (*s == '-')
1060
    {
1061
      *negative = TRUE;
1062
      ++s;
1063
    }
1064
  else if (*s == '+')
1065
    ++s;
1066
1067
  /* Recognize number prefix and if BASE is zero, figure it out ourselves.  */
1068
  if (*s == '0')
1069
    {
1070
      if ((base == 0 || base == 16) && TOUPPER (s[1]) == 'X')
1071
        {
1072
          s += 2;
1073
          base = 16;
1074
        }
1075
      else if (base == 0)
1076
        base = 8;
1077
    }
1078
  else if (base == 0)
1079
    base = 10;
1080
1081
  /* Save the pointer so we can check later if anything happened.  */
1082
  save = s;
1083
  cutoff = G_MAXUINT64 / base;
1084
  cutlim = G_MAXUINT64 % base;
1085
1086
  overflow = FALSE;
1087
  ui64 = 0;
1088
  c = *s;
1089
  for (; c; c = *++s)
1090
    {
1091
      if (c >= '0' && c <= '9')
1092
        c -= '0';
1093
      else if (ISALPHA (c))
1094
        c = TOUPPER (c) - 'A' + 10;
1095
      else
1096
        break;
1097
      if (c >= base)
1098
        break;
1099
      /* Check for overflow.  */
1100
      if (ui64 > cutoff || (ui64 == cutoff && c > cutlim))
1101
        overflow = TRUE;
1102
      else
1103
        {
1104
          ui64 *= base;
1105
          ui64 += c;
1106
        }
1107
    }
1108
1109
  /* Check if anything actually happened.  */
1110
  if (s == save)
1111
    goto noconv;
1112
1113
  /* Store in ENDPTR the address of one character
1114
     past the last character we converted.  */
1115
  if (endptr)
1116
    *endptr = s;
1117
1118
  if (G_UNLIKELY (overflow))
1119
    {
1120
      errno = ERANGE;
1121
      return G_MAXUINT64;
1122
    }
1123
1124
  return ui64;
1125
1126
 noconv:
1127
  /* We must handle a special case here: the base is 0 or 16 and the
1128
     first two characters are '0' and 'x', but the rest are no
1129
     hexadecimal digits.  This is no error case.  We return 0 and
1130
     ENDPTR points to the `x`.  */
1131
  if (endptr)
1132
    {
1133
      if (save - nptr >= 2 && TOUPPER (save[-1]) == 'X'
1134
          && save[-2] == '0')
1135
        *endptr = &save[-1];
1136
      else
1137
        /*  There was no number to convert.  */
1138
        *endptr = nptr;
1139
    }
1140
  return 0;
1141
}
1142
#endif /* !defined(USE_XLOCALE) || !defined(HAVE_STRTOULL_L) || !defined(HAVE_STRTOLL_L) */
1143
1144
/**
1145
 * g_ascii_strtoull:
1146
 * @nptr: the string to convert to a numeric value
1147
 * @endptr: (out) (transfer none) (optional): if non-`NULL`, it returns the
1148
 *   character after the last character used in the conversion
1149
 * @base: to be used for the conversion, 2..36 or 0
1150
 *
1151
 * Converts a string to a `guint64` value.
1152
 *
1153
 * This function behaves like the standard `strtoull()` function
1154
 * does in the C locale. It does this without actually
1155
 * changing the current locale, since that would not be
1156
 * thread-safe.
1157
 *
1158
 * Note that input with a leading minus sign (`-`) is accepted, and will return
1159
 * the negation of the parsed number, unless that would overflow a `guint64`.
1160
 * Critically, this means you cannot assume that a short fixed length input will
1161
 * result in a low return value, as the input could have a leading `-`.
1162
 *
1163
 * This function is typically used when reading configuration
1164
 * files or other non-user input that should be locale independent.
1165
 * To handle input from the user you should normally use the
1166
 * locale-sensitive system `strtoull()` function.
1167
 *
1168
 * If the correct value would cause overflow, [const@GLib.MAXUINT64]
1169
 * is returned, and `ERANGE` is stored in `errno`.
1170
 * If the base is outside the valid range, zero is returned, and
1171
 * `EINVAL` is stored in `errno`.
1172
 * If the string conversion fails, zero is returned, and @endptr returns
1173
 * @nptr (if @endptr is non-`NULL`).
1174
 *
1175
 * Returns: the converted value, or zero on error
1176
 *
1177
 * Since: 2.2
1178
 */
1179
guint64
1180
g_ascii_strtoull (const gchar *nptr,
1181
                  gchar      **endptr,
1182
                  guint        base)
1183
577k
{
1184
577k
#if defined(USE_XLOCALE) && defined(HAVE_STRTOULL_L)
1185
577k
  locale_t c_locale = get_C_locale ();
1186
1187
577k
  errno = 0;
1188
577k
  return strtoull_l (nptr, endptr, base, c_locale);
1189
#else
1190
  gboolean negative;
1191
  guint64 result;
1192
1193
  result = g_parse_long_long (nptr, (const gchar **) endptr, base, &negative);
1194
1195
  /* Return the result of the appropriate sign.  */
1196
  return negative ? -result : result;
1197
#endif
1198
577k
}
1199
1200
/**
1201
 * g_ascii_strtoll:
1202
 * @nptr: the string to convert to a numeric value
1203
 * @endptr: (out) (transfer none) (optional): if non-`NULL`, it returns the
1204
 *   character after the last character used in the conversion
1205
 * @base: to be used for the conversion, 2..36 or 0
1206
 *
1207
 * Converts a string to a `gint64` value.
1208
 *
1209
 * This function behaves like the standard `strtoll()` function
1210
 * does in the C locale. It does this without actually
1211
 * changing the current locale, since that would not be
1212
 * thread-safe.
1213
 *
1214
 * This function is typically used when reading configuration
1215
 * files or other non-user input that should be locale independent.
1216
 * To handle input from the user you should normally use the
1217
 * locale-sensitive system `strtoll()` function.
1218
 *
1219
 * If the correct value would cause overflow, [const@GLib.MAXINT64] or
1220
 * [const@GLib.MININT64] is returned, and `ERANGE` is stored in `errno`.
1221
 * If the base is outside the valid range, zero is returned, and
1222
 * `EINVAL` is stored in `errno`. If the
1223
 * string conversion fails, zero is returned, and @endptr returns @nptr
1224
 * (if @endptr is non-`NULL`).
1225
 *
1226
 * Returns: the converted value, or zero on error
1227
 *
1228
 * Since: 2.12
1229
 */
1230
gint64
1231
g_ascii_strtoll (const gchar *nptr,
1232
                 gchar      **endptr,
1233
                 guint        base)
1234
137
{
1235
137
#if defined(USE_XLOCALE) && defined(HAVE_STRTOLL_L)
1236
137
  locale_t c_locale = get_C_locale ();
1237
1238
137
  errno = 0;
1239
137
  return strtoll_l (nptr, endptr, base, c_locale);
1240
#else
1241
  gboolean negative;
1242
  guint64 result;
1243
1244
  result = g_parse_long_long (nptr, (const gchar **) endptr, base, &negative);
1245
1246
  if (negative && result > (guint64) G_MININT64)
1247
    {
1248
      errno = ERANGE;
1249
      return G_MININT64;
1250
    }
1251
  else if (!negative && result > (guint64) G_MAXINT64)
1252
    {
1253
      errno = ERANGE;
1254
      return G_MAXINT64;
1255
    }
1256
  else if (negative)
1257
    return (result == (guint64) G_MININT64) ? G_MININT64 : -(gint64) result;
1258
  else
1259
    return (gint64) result;
1260
#endif
1261
137
}
1262
1263
/**
1264
 * g_strerror:
1265
 * @errnum: the system error number. See the standard C `errno` documentation
1266
 *
1267
 * Returns a string corresponding to the given error code, e.g. "no
1268
 * such process".
1269
 *
1270
 * Unlike `strerror()`, this always returns a string in
1271
 * UTF-8 encoding, and the pointer is guaranteed to remain valid for
1272
 * the lifetime of the process. If the error code is unknown, it returns a
1273
 * string like “Unknown error <code\>”.
1274
 *
1275
 * Note that the string may be translated according to the current locale.
1276
 *
1277
 * The value of `errno` will not be changed by this function. However, it may
1278
 * be changed by intermediate function calls, so you should save its value
1279
 * as soon as the call returns:
1280
 * ```C
1281
 * int saved_errno;
1282
 *
1283
 * ret = read (blah);
1284
 * saved_errno = errno;
1285
 *
1286
 * g_strerror (saved_errno);
1287
 * ```
1288
 *
1289
 * Returns: the string describing the error code
1290
 */
1291
const gchar *
1292
g_strerror (gint errnum)
1293
108
{
1294
108
  static GHashTable *errors;
1295
108
  G_LOCK_DEFINE_STATIC (errors);
1296
108
  const gchar *msg;
1297
108
  gint saved_errno = errno;
1298
1299
108
  G_LOCK (errors);
1300
108
  if (errors)
1301
99
    msg = g_hash_table_lookup (errors, GINT_TO_POINTER (errnum));
1302
9
  else
1303
9
    {
1304
9
      errors = g_hash_table_new (NULL, NULL);
1305
9
      msg = NULL;
1306
9
    }
1307
1308
108
  if (!msg)
1309
9
    {
1310
9
      gchar buf[1024];
1311
9
      GError *error = NULL;
1312
#if defined(HAVE_STRERROR_R) && !defined(STRERROR_R_CHAR_P)
1313
      int ret;
1314
#endif
1315
1316
#if defined(G_OS_WIN32)
1317
      strerror_s (buf, sizeof (buf), errnum);
1318
      msg = buf;
1319
#elif defined(HAVE_STRERROR_R)
1320
      /* Match the condition in strerror_r(3) for glibc */
1321
9
#  if defined(STRERROR_R_CHAR_P)
1322
9
      msg = strerror_r (errnum, buf, sizeof (buf));
1323
#  else
1324
      ret = strerror_r (errnum, buf, sizeof (buf));
1325
      if (ret == 0 || ret == EINVAL)
1326
        msg = buf;
1327
#  endif /* HAVE_STRERROR_R */
1328
#else
1329
      g_strlcpy (buf, strerror (errnum), sizeof (buf));
1330
      msg = buf;
1331
#endif
1332
1333
9
      if (!msg)
1334
0
        {
1335
0
          G_UNLOCK (errors);
1336
1337
0
          errno = saved_errno;
1338
0
          return NULL;
1339
0
        }
1340
1341
9
      if (!g_get_console_charset (NULL))
1342
9
        {
1343
9
          msg = g_locale_to_utf8 (msg, -1, NULL, NULL, &error);
1344
9
          if (error)
1345
0
            {
1346
0
              g_print ("%s\n", error->message);
1347
0
              g_error_free (error);
1348
0
            }
1349
9
        }
1350
0
      else if (msg == (const gchar *)buf)
1351
0
        msg = g_strdup (buf);
1352
1353
9
      g_hash_table_insert (errors, GINT_TO_POINTER (errnum), (char *) msg);
1354
9
    }
1355
108
  G_UNLOCK (errors);
1356
1357
108
  errno = saved_errno;
1358
108
  return msg;
1359
108
}
1360
1361
/**
1362
 * g_strsignal:
1363
 * @signum: the signal number. See the `signal` documentation
1364
 *
1365
 * Returns a string describing the given signal, e.g. "Segmentation fault".
1366
 * If the signal is unknown, it returns “unknown signal (<signum\>)”.
1367
 *
1368
 * You should use this function in preference to `strsignal()`, because it
1369
 * returns a string in UTF-8 encoding, and since not all platforms support
1370
 * the `strsignal()` function.
1371
 *
1372
 * Returns: the string describing the signal
1373
 */
1374
const gchar *
1375
g_strsignal (gint signum)
1376
0
{
1377
0
  gchar *msg;
1378
0
  gchar *tofree;
1379
0
  const gchar *ret;
1380
1381
0
  msg = tofree = NULL;
1382
1383
0
#ifdef HAVE_STRSIGNAL
1384
0
  msg = strsignal (signum);
1385
0
  if (!g_get_console_charset (NULL))
1386
0
    msg = tofree = g_locale_to_utf8 (msg, -1, NULL, NULL, NULL);
1387
0
#endif
1388
1389
0
  if (!msg)
1390
0
    msg = tofree = g_strdup_printf ("unknown signal (%d)", signum);
1391
0
  ret = g_intern_string (msg);
1392
0
  g_free (tofree);
1393
1394
0
  return ret;
1395
0
}
1396
1397
/* Functions g_strlcpy and g_strlcat were originally developed by
1398
 * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1399
 * See http://www.openbsd.org/cgi-bin/man.cgi?query=strlcpy
1400
 * for more information.
1401
 */
1402
1403
#ifdef HAVE_STRLCPY
1404
/* Use the native ones, if available; they might be implemented in assembly */
1405
gsize
1406
g_strlcpy (gchar       *dest,
1407
           const gchar *src,
1408
           gsize        dest_size)
1409
{
1410
  g_return_val_if_fail (dest != NULL, 0);
1411
  g_return_val_if_fail (src  != NULL, 0);
1412
1413
  return strlcpy (dest, src, dest_size);
1414
}
1415
1416
gsize
1417
g_strlcat (gchar       *dest,
1418
           const gchar *src,
1419
           gsize        dest_size)
1420
{
1421
  g_return_val_if_fail (dest != NULL, 0);
1422
  g_return_val_if_fail (src  != NULL, 0);
1423
1424
  return strlcat (dest, src, dest_size);
1425
}
1426
1427
#else /* ! HAVE_STRLCPY */
1428
/**
1429
 * g_strlcpy:
1430
 * @dest: destination buffer
1431
 * @src: source buffer
1432
 * @dest_size: length of @dest in bytes
1433
 *
1434
 * Portability wrapper that calls `strlcpy()` on systems which have it,
1435
 * and emulates `strlcpy()` otherwise. Copies @src to @dest; @dest is
1436
 * guaranteed to be nul-terminated; @src must be nul-terminated;
1437
 * @dest_size is the buffer size, not the number of bytes to copy.
1438
 *
1439
 * At most @dest_size - 1 characters will be copied. Always nul-terminates
1440
 * (unless @dest_size is 0). This function does not allocate memory. Unlike
1441
 * `strncpy()`, this function doesn't pad @dest (so it's often faster). It
1442
 * returns the size of the attempted result, `strlen (src)`, so if
1443
 * @retval >= @dest_size, truncation occurred.
1444
 *
1445
 * Caveat: `strlcpy()` is supposedly more secure than `strcpy()` or `strncpy()`,
1446
 * but if you really want to avoid screwups, [func@GLib.strdup] is an even better
1447
 * idea.
1448
 *
1449
 * Returns: length of @src
1450
 */
1451
gsize
1452
g_strlcpy (gchar       *dest,
1453
           const gchar *src,
1454
           gsize        dest_size)
1455
52.8k
{
1456
52.8k
  gchar *d = dest;
1457
52.8k
  const gchar *s = src;
1458
52.8k
  gsize n = dest_size;
1459
1460
52.8k
  g_return_val_if_fail (dest != NULL, 0);
1461
52.8k
  g_return_val_if_fail (src  != NULL, 0);
1462
1463
  /* Copy as many bytes as will fit */
1464
52.8k
  if (n != 0 && --n != 0)
1465
52.8k
    do
1466
1.16M
      {
1467
1.16M
        gchar c = *s++;
1468
1469
1.16M
        *d++ = c;
1470
1.16M
        if (c == 0)
1471
15.6k
          break;
1472
1.16M
      }
1473
1.15M
    while (--n != 0);
1474
1475
  /* If not enough room in dest, add NUL and traverse rest of src */
1476
52.8k
  if (n == 0)
1477
37.1k
    {
1478
37.1k
      if (dest_size != 0)
1479
37.1k
        *d = 0;
1480
161k
      while (*s++)
1481
124k
        ;
1482
37.1k
    }
1483
1484
52.8k
  return s - src - 1;  /* count does not include NUL */
1485
52.8k
}
1486
1487
/**
1488
 * g_strlcat:
1489
 * @dest: destination buffer, already containing one nul-terminated string
1490
 * @src: source buffer
1491
 * @dest_size: length of @dest buffer in bytes (not length of existing string
1492
 *   inside @dest)
1493
 *
1494
 * Portability wrapper that calls `strlcat()` on systems which have it,
1495
 * and emulates it otherwise. Appends nul-terminated @src string to @dest,
1496
 * guaranteeing nul-termination for @dest. The total size of @dest won't
1497
 * exceed @dest_size.
1498
 *
1499
 * At most @dest_size - 1 characters will be copied. Unlike `strncat()`,
1500
 * @dest_size is the full size of dest, not the space left over. This
1501
 * function does not allocate memory. It always nul-terminates (unless
1502
 * @dest_size == 0 or there were no nul characters in the @dest_size
1503
 * characters of dest to start with).
1504
 *
1505
 * Caveat: this is supposedly a more secure alternative to `strcat()` or
1506
 * `strncat()`, but for real security [func@GLib.strconcat] is harder to mess up.
1507
 *
1508
 * Returns: size of attempted result, which is `MIN (dest_size, strlen
1509
 *   (original dest)) + strlen (src)`, so if @retval >= @dest_size,
1510
 *   truncation occurred
1511
 */
1512
gsize
1513
g_strlcat (gchar       *dest,
1514
           const gchar *src,
1515
           gsize        dest_size)
1516
17.1k
{
1517
17.1k
  gchar *d = dest;
1518
17.1k
  const gchar *s = src;
1519
17.1k
  gsize bytes_left = dest_size;
1520
17.1k
  gsize dlength;  /* Logically, MIN (strlen (d), dest_size) */
1521
1522
17.1k
  g_return_val_if_fail (dest != NULL, 0);
1523
17.1k
  g_return_val_if_fail (src  != NULL, 0);
1524
1525
  /* Find the end of dst and adjust bytes left but don't go past end */
1526
17.1k
  while (*d != 0 && bytes_left-- != 0)
1527
0
    d++;
1528
17.1k
  dlength = d - dest;
1529
17.1k
  bytes_left = dest_size - dlength;
1530
1531
17.1k
  if (bytes_left == 0)
1532
0
    return dlength + strlen (s);
1533
1534
34.3k
  while (*s != 0)
1535
17.1k
    {
1536
17.1k
      if (bytes_left != 1)
1537
17.1k
        {
1538
17.1k
          *d++ = *s;
1539
17.1k
          bytes_left--;
1540
17.1k
        }
1541
17.1k
      s++;
1542
17.1k
    }
1543
17.1k
  *d = 0;
1544
1545
17.1k
  return dlength + (s - src);  /* count does not include NUL */
1546
17.1k
}
1547
#endif /* ! HAVE_STRLCPY */
1548
1549
/**
1550
 * g_ascii_strdown:
1551
 * @str: a string
1552
 * @len: length of @str in bytes, or `-1` if @str is nul-terminated
1553
 *
1554
 * Converts all upper case ASCII letters to lower case ASCII letters, with
1555
 * semantics that exactly match [func@GLib.ascii_tolower].
1556
 *
1557
 * Returns: a newly-allocated string, with all the upper case characters in
1558
 *   @str converted to lower case. (Note that this is unlike the old
1559
 *   [func@GLib.strdown], which modified the string in place.)
1560
 */
1561
gchar*
1562
g_ascii_strdown (const gchar *str,
1563
                 gssize       len)
1564
87.5k
{
1565
87.5k
  gchar *result, *s;
1566
1567
87.5k
  g_return_val_if_fail (str != NULL, NULL);
1568
1569
87.5k
  if (len < 0)
1570
57.0k
    result = g_strdup (str);
1571
30.5k
  else
1572
30.5k
    result = g_strndup (str, (gsize) len);
1573
1574
328k
  for (s = result; *s; s++)
1575
240k
    *s = g_ascii_tolower (*s);
1576
1577
87.5k
  return result;
1578
87.5k
}
1579
1580
/**
1581
 * g_ascii_strup:
1582
 * @str: a string
1583
 * @len: length of @str in bytes, or `-1` if @str is nul-terminated
1584
 *
1585
 * Converts all lower case ASCII letters to upper case ASCII letters, with
1586
 * semantics that exactly match [func@GLib.ascii_toupper].
1587
 *
1588
 * Returns: a newly-allocated string, with all the lower case characters
1589
 *   in @str converted to upper case. (Note that this is unlike the old
1590
 *   [func@GLib.strup], which modified the string in place.)
1591
 */
1592
gchar*
1593
g_ascii_strup (const gchar *str,
1594
               gssize       len)
1595
4.62k
{
1596
4.62k
  gchar *result, *s;
1597
1598
4.62k
  g_return_val_if_fail (str != NULL, NULL);
1599
1600
4.62k
  if (len < 0)
1601
4.62k
    result = g_strdup (str);
1602
0
  else
1603
0
    result = g_strndup (str, (gsize) len);
1604
1605
49.8k
  for (s = result; *s; s++)
1606
45.2k
    *s = g_ascii_toupper (*s);
1607
1608
4.62k
  return result;
1609
4.62k
}
1610
1611
/**
1612
 * g_strdown:
1613
 * @string: the string to convert
1614
 *
1615
 * Converts a string to lower case.
1616
 *
1617
 * Returns: the string
1618
 *
1619
 * Deprecated: 2.2: This function is totally broken for the reasons discussed
1620
 *   in the [func@GLib.strncasecmp] docs — use [func@GLib.ascii_strdown] or
1621
 *   [func@GLib.utf8_strdown] instead.
1622
 **/
1623
gchar*
1624
g_strdown (gchar *string)
1625
0
{
1626
0
  guchar *s;
1627
1628
0
  g_return_val_if_fail (string != NULL, NULL);
1629
1630
0
  s = (guchar *) string;
1631
1632
0
  while (*s)
1633
0
    {
1634
0
      if (isupper (*s))
1635
0
        *s = tolower (*s);
1636
0
      s++;
1637
0
    }
1638
1639
0
  return (gchar *) string;
1640
0
}
1641
1642
/**
1643
 * g_strup:
1644
 * @string: the string to convert
1645
 *
1646
 * Converts a string to upper case.
1647
 *
1648
 * Returns: the string
1649
 *
1650
 * Deprecated: 2.2: This function is totally broken for the reasons discussed
1651
 *   in the [func@GLib.strncasecmp] docs — use [func@GLib.ascii_strup] or
1652
 *   [func@GLib.utf8_strup] instead.
1653
 */
1654
gchar*
1655
g_strup (gchar *string)
1656
0
{
1657
0
  guchar *s;
1658
1659
0
  g_return_val_if_fail (string != NULL, NULL);
1660
1661
0
  s = (guchar *) string;
1662
1663
0
  while (*s)
1664
0
    {
1665
0
      if (islower (*s))
1666
0
        *s = toupper (*s);
1667
0
      s++;
1668
0
    }
1669
1670
0
  return (gchar *) string;
1671
0
}
1672
1673
/**
1674
 * g_strreverse:
1675
 * @string: the string to reverse
1676
 *
1677
 * Reverses all of the bytes in a string. For example,
1678
 * `g_strreverse ("abcdef")` will result in "fedcba".
1679
 *
1680
 * Note that `g_strreverse()` doesn't work on UTF-8 strings
1681
 * containing multibyte characters. For that purpose, use
1682
 * [func@GLib.utf8_strreverse].
1683
 *
1684
 * Returns: the @string, reversed in place
1685
 */
1686
gchar*
1687
g_strreverse (gchar *string)
1688
0
{
1689
0
  g_return_val_if_fail (string != NULL, NULL);
1690
1691
0
  if (*string)
1692
0
    {
1693
0
      gchar *h, *t;
1694
1695
0
      h = string;
1696
0
      t = string + strlen (string) - 1;
1697
1698
0
      while (h < t)
1699
0
        {
1700
0
          gchar c;
1701
1702
0
          c = *h;
1703
0
          *h = *t;
1704
0
          h++;
1705
0
          *t = c;
1706
0
          t--;
1707
0
        }
1708
0
    }
1709
1710
0
  return string;
1711
0
}
1712
1713
/**
1714
 * g_ascii_tolower:
1715
 * @c: any character
1716
 *
1717
 * Convert a character to ASCII lower case. If the character is not an
1718
 * ASCII upper case letter, it is returned unchanged.
1719
 *
1720
 * Unlike the standard C library `tolower()` function, this only
1721
 * recognizes standard ASCII letters and ignores the locale, returning
1722
 * all non-ASCII characters unchanged, even if they are lower case
1723
 * letters in a particular character set. Also unlike the standard
1724
 * library function, this takes and returns a char, not an int, so
1725
 * don't call it on `EOF` but no need to worry about casting to `guchar`
1726
 * before passing a possibly non-ASCII character in.
1727
 *
1728
 * Returns: the result of the conversion
1729
 */
1730
gchar
1731
g_ascii_tolower (gchar c)
1732
5.15M
{
1733
5.15M
  return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1734
5.15M
}
1735
1736
/**
1737
 * g_ascii_toupper:
1738
 * @c: any character
1739
 *
1740
 * Convert a character to ASCII upper case. If the character is not an
1741
 * ASCII lower case letter, it is returned unchanged.
1742
 *
1743
 * Unlike the standard C library `toupper()` function, this only
1744
 * recognizes standard ASCII letters and ignores the locale, returning
1745
 * all non-ASCII characters unchanged, even if they are upper case
1746
 * letters in a particular character set. Also unlike the standard
1747
 * library function, this takes and returns a char, not an int, so
1748
 * don't call it on `EOF` but no need to worry about casting to `guchar`
1749
 * before passing a possibly non-ASCII character in.
1750
 *
1751
 * Returns: the result of the conversion
1752
 */
1753
gchar
1754
g_ascii_toupper (gchar c)
1755
45.2k
{
1756
45.2k
  return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1757
45.2k
}
1758
1759
/**
1760
 * g_ascii_digit_value:
1761
 * @c: an ASCII character
1762
 *
1763
 * Determines the numeric value of a character as a decimal digit. If the
1764
 * character is not a decimal digit according to [func@GLib.ascii_isdigit],
1765
 * `-1` is returned.
1766
 *
1767
 * Differs from [func@GLib.unichar_digit_value] because it takes a char, so
1768
 * there's no worry about sign extension if characters are signed.
1769
 *
1770
 * Returns: the numerical value of @c if it is a decimal digit, `-1` otherwise
1771
 */
1772
int
1773
g_ascii_digit_value (gchar c)
1774
12
{
1775
12
  if (g_ascii_isdigit (c))
1776
12
    return c - '0';
1777
0
  return -1;
1778
12
}
1779
1780
/**
1781
 * g_ascii_xdigit_value:
1782
 * @c: an ASCII character
1783
 *
1784
 * Determines the numeric value of a character as a hexadecimal digit. If the
1785
 * character is not a hex digit according to [func@GLib.ascii_isxdigit],
1786
 * `-1` is returned.
1787
 *
1788
 * Differs from [func@GLib.unichar_xdigit_value] because it takes a char, so
1789
 * there's no worry about sign extension if characters are signed.
1790
 *
1791
 * Differs from [func@GLib.unichar_xdigit_value] because it takes a char, so
1792
 * there's no worry about sign extension if characters are signed.
1793
 *
1794
 * Returns: the numerical value of @c if it is a hex digit, `-1` otherwise
1795
 */
1796
int
1797
g_ascii_xdigit_value (gchar c)
1798
0
{
1799
0
  if (c >= 'A' && c <= 'F')
1800
0
    return c - 'A' + 10;
1801
0
  if (c >= 'a' && c <= 'f')
1802
0
    return c - 'a' + 10;
1803
0
  return g_ascii_digit_value (c);
1804
0
}
1805
1806
/**
1807
 * g_ascii_strcasecmp:
1808
 * @s1: string to compare with @s2
1809
 * @s2: string to compare with @s1
1810
 *
1811
 * Compare two strings, ignoring the case of ASCII characters.
1812
 *
1813
 * Unlike the BSD `strcasecmp()` function, this only recognizes standard
1814
 * ASCII letters and ignores the locale, treating all non-ASCII
1815
 * bytes as if they are not letters.
1816
 *
1817
 * This function should be used only on strings that are known to be
1818
 * in encodings where the bytes corresponding to ASCII letters always
1819
 * represent themselves. This includes UTF-8 and the ISO-8859-*
1820
 * charsets, but not for instance double-byte encodings like the
1821
 * Windows Codepage 932, where the trailing bytes of double-byte
1822
 * characters include all ASCII letters. If you compare two CP932
1823
 * strings using this function, you will get false matches.
1824
 *
1825
 * Both @s1 and @s2 must be non-`NULL`.
1826
 *
1827
 * Returns: 0 if the strings match, a negative value if @s1 < @s2,
1828
 *   or a positive value if @s1 > @s2
1829
 */
1830
gint
1831
g_ascii_strcasecmp (const gchar *s1,
1832
                    const gchar *s2)
1833
8.45M
{
1834
8.45M
  gint c1, c2;
1835
1836
8.45M
  g_return_val_if_fail (s1 != NULL, 0);
1837
8.45M
  g_return_val_if_fail (s2 != NULL, 0);
1838
1839
9.15M
  while (*s1 && *s2)
1840
8.93M
    {
1841
8.93M
      c1 = (gint)(guchar) TOLOWER (*s1);
1842
8.93M
      c2 = (gint)(guchar) TOLOWER (*s2);
1843
8.93M
      if (c1 != c2)
1844
8.24M
        return (c1 - c2);
1845
693k
      s1++; s2++;
1846
693k
    }
1847
1848
216k
  return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1849
8.45M
}
1850
1851
/**
1852
 * g_ascii_strncasecmp:
1853
 * @s1: string to compare with @s2
1854
 * @s2: string to compare with @s1
1855
 * @n: number of characters to compare
1856
 *
1857
 * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1858
 * characters after the first @n in each string. If either string is
1859
 * less than @n bytes long, comparison will stop at the first nul byte
1860
 * encountered.
1861
 *
1862
 * Unlike the BSD `strncasecmp()` function, this only recognizes standard
1863
 * ASCII letters and ignores the locale, treating all non-ASCII
1864
 * characters as if they are not letters.
1865
 *
1866
 * The same warning as in [func@GLib.ascii_strcasecmp] applies: Use this
1867
 * function only on strings known to be in encodings where bytes
1868
 * corresponding to ASCII letters always represent themselves.
1869
 *
1870
 * Returns: 0 if the strings match, a negative value if @s1 < @s2,
1871
 *   or a positive value if @s1 > @s2
1872
 */
1873
gint
1874
g_ascii_strncasecmp (const gchar *s1,
1875
                     const gchar *s2,
1876
                     gsize        n)
1877
453k
{
1878
453k
  gint c1, c2;
1879
1880
453k
  g_return_val_if_fail (s1 != NULL, 0);
1881
453k
  g_return_val_if_fail (s2 != NULL, 0);
1882
1883
594k
  while (n && *s1 && *s2)
1884
438k
    {
1885
438k
      n -= 1;
1886
438k
      c1 = (gint)(guchar) TOLOWER (*s1);
1887
438k
      c2 = (gint)(guchar) TOLOWER (*s2);
1888
438k
      if (c1 != c2)
1889
297k
        return (c1 - c2);
1890
141k
      s1++; s2++;
1891
141k
    }
1892
1893
156k
  if (n)
1894
19.2k
    return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1895
137k
  else
1896
137k
    return 0;
1897
156k
}
1898
1899
/**
1900
 * g_strcasecmp:
1901
 * @s1: string to compare with @s2
1902
 * @s2: string to compare with @s1
1903
 *
1904
 * A case-insensitive string comparison, corresponding to the standard
1905
 * `strcasecmp()` function on platforms which support it.
1906
 *
1907
 * Returns: 0 if the strings match, a negative value if @s1 < @s2,
1908
 *   or a positive value if @s1 > @s2
1909
 *
1910
 * Deprecated: 2.2: See [func@GLib.strncasecmp] for a discussion of why this
1911
 *   function is deprecated and how to replace it.
1912
 */
1913
gint
1914
g_strcasecmp (const gchar *s1,
1915
              const gchar *s2)
1916
0
{
1917
0
#ifdef HAVE_STRCASECMP
1918
0
  g_return_val_if_fail (s1 != NULL, 0);
1919
0
  g_return_val_if_fail (s2 != NULL, 0);
1920
1921
0
  return strcasecmp (s1, s2);
1922
#else
1923
  gint c1, c2;
1924
1925
  g_return_val_if_fail (s1 != NULL, 0);
1926
  g_return_val_if_fail (s2 != NULL, 0);
1927
1928
  while (*s1 && *s2)
1929
    {
1930
      /* According to A. Cox, some platforms have islower's that
1931
       * don't work right on non-uppercase
1932
       */
1933
      c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1934
      c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1935
      if (c1 != c2)
1936
        return (c1 - c2);
1937
      s1++; s2++;
1938
    }
1939
1940
  return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1941
#endif
1942
0
}
1943
1944
/**
1945
 * g_strncasecmp:
1946
 * @s1: string to compare with @s2
1947
 * @s2: string to compare with @s1
1948
 * @n: the maximum number of characters to compare
1949
 *
1950
 * A case-insensitive string comparison, corresponding to the standard
1951
 * `strncasecmp()` function on platforms which support it. It is similar
1952
 * to [func@GLib.strcasecmp] except it only compares the first @n characters of
1953
 * the strings.
1954
 *
1955
 * Returns: 0 if the strings match, a negative value if @s1 < @s2,
1956
 *   or a positive value if @s1 > @s2
1957
 *
1958
 * Deprecated: 2.2: The problem with `g_strncasecmp()` is that it does
1959
 *   the comparison by calling `toupper()`/`tolower()`. These functions
1960
 *   are locale-specific and operate on single bytes. However, it is
1961
 *   impossible to handle things correctly from an internationalization
1962
 *   standpoint by operating on bytes, since characters may be multibyte.
1963
 *   Thus `g_strncasecmp()` is broken if your string is guaranteed to be
1964
 *   ASCII, since it is locale-sensitive, and it's broken if your string
1965
 *   is localized, since it doesn't work on many encodings at all,
1966
 *   including UTF-8, EUC-JP, etc.
1967
 *
1968
 *   There are therefore two replacement techniques: [func@GLib.ascii_strncasecmp],
1969
 *   which only works on ASCII and is not locale-sensitive, and
1970
 *   [func@GLib.utf8_casefold] followed by `strcmp()` on the resulting strings,
1971
 *   which is good for case-insensitive sorting of UTF-8.
1972
 */
1973
gint
1974
g_strncasecmp (const gchar *s1,
1975
               const gchar *s2,
1976
               guint n)
1977
0
{
1978
0
#ifdef HAVE_STRNCASECMP
1979
0
  return strncasecmp (s1, s2, n);
1980
#else
1981
  gint c1, c2;
1982
1983
  g_return_val_if_fail (s1 != NULL, 0);
1984
  g_return_val_if_fail (s2 != NULL, 0);
1985
1986
  while (n && *s1 && *s2)
1987
    {
1988
      n -= 1;
1989
      /* According to A. Cox, some platforms have islower's that
1990
       * don't work right on non-uppercase
1991
       */
1992
      c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1993
      c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1994
      if (c1 != c2)
1995
        return (c1 - c2);
1996
      s1++; s2++;
1997
    }
1998
1999
  if (n)
2000
    return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
2001
  else
2002
    return 0;
2003
#endif
2004
0
}
2005
2006
/**
2007
 * g_strdelimit:
2008
 * @string: the string to convert
2009
 * @delimiters: (nullable): a string containing the current delimiters, or
2010
 *   `NULL` to use the standard delimiters defined in [const@GLib.STR_DELIMITERS]
2011
 * @new_delimiter: the new delimiter character
2012
 *
2013
 * Converts any delimiter characters in @string to @new_delimiter.
2014
 *
2015
 * Any characters in @string which are found in @delimiters are
2016
 * changed to the @new_delimiter character. Modifies @string in place,
2017
 * and returns @string itself, not a copy.
2018
 *
2019
 * The return value is to allow nesting such as:
2020
 * ```C
2021
 * g_ascii_strup (g_strdelimit (str, "abc", '?'))
2022
 * ```
2023
 *
2024
 * In order to modify a copy, you may use [func@GLib.strdup]:
2025
 * ```C
2026
 * reformatted = g_strdelimit (g_strdup (const_str), "abc", '?');
2027
 * …
2028
 * g_free (reformatted);
2029
 * ```
2030
 *
2031
 * Returns: the modified @string
2032
 */
2033
gchar *
2034
g_strdelimit (gchar       *string,
2035
              const gchar *delimiters,
2036
              gchar        new_delim)
2037
29.7k
{
2038
29.7k
  gchar *c;
2039
2040
29.7k
  g_return_val_if_fail (string != NULL, NULL);
2041
2042
29.7k
  if (!delimiters)
2043
22
    delimiters = G_STR_DELIMITERS;
2044
2045
588k
  for (c = string; *c; c++)
2046
558k
    {
2047
558k
      if (strchr (delimiters, *c))
2048
39.4k
        *c = new_delim;
2049
558k
    }
2050
2051
29.7k
  return string;
2052
29.7k
}
2053
2054
/**
2055
 * g_strcanon:
2056
 * @string: a nul-terminated array of bytes
2057
 * @valid_chars: bytes permitted in @string
2058
 * @substitutor: replacement character for disallowed bytes
2059
 *
2060
 * For each character in @string, if the character is not in @valid_chars,
2061
 * replaces the character with @substitutor.
2062
 *
2063
 * Modifies @string in place, and return @string itself, not a copy. The
2064
 * return value is to allow nesting such as:
2065
 * ```C
2066
 * g_ascii_strup (g_strcanon (str, "abc", '?'))
2067
 * ```
2068
 *
2069
 * In order to modify a copy, you may use [func@GLib.strdup]:
2070
 * ```C
2071
 * reformatted = g_strcanon (g_strdup (const_str), "abc", '?');
2072
 * …
2073
 * g_free (reformatted);
2074
 * ```
2075
 *
2076
 * Returns: the modified @string
2077
 */
2078
gchar *
2079
g_strcanon (gchar       *string,
2080
            const gchar *valid_chars,
2081
            gchar        substitutor)
2082
0
{
2083
0
  gchar *c;
2084
2085
0
  g_return_val_if_fail (string != NULL, NULL);
2086
0
  g_return_val_if_fail (valid_chars != NULL, NULL);
2087
2088
0
  for (c = string; *c; c++)
2089
0
    {
2090
0
      if (!strchr (valid_chars, *c))
2091
0
        *c = substitutor;
2092
0
    }
2093
2094
0
  return string;
2095
0
}
2096
2097
/**
2098
 * g_strcompress:
2099
 * @source: a string to compress
2100
 *
2101
 * Makes a copy of a string replacing C string-style escape
2102
 * sequences with their one byte equivalent:
2103
 *
2104
 * - `\b` → [U+0008 Backspace](https://en.wikipedia.org/wiki/Backspace)
2105
 * - `\f` → [U+000C Form Feed](https://en.wikipedia.org/wiki/Form_feed)
2106
 * - `\n` → [U+000A Line Feed](https://en.wikipedia.org/wiki/Newline)
2107
 * - `\r` → [U+000D Carriage Return](https://en.wikipedia.org/wiki/Carriage_return)
2108
 * - `\t` → [U+0009 Horizontal Tabulation](https://en.wikipedia.org/wiki/Tab_character)
2109
 * - `\v` → [U+000B Vertical Tabulation](https://en.wikipedia.org/wiki/Vertical_Tab)
2110
 * - `\` followed by one to three octal digits → the numeric value (mod 255)
2111
 * - `\` followed by any other character → the character as is.
2112
 *   For example, `\\` will turn into a backslash (`\`) and `\"` into a double quote (`"`).
2113
 *
2114
 * [func@GLib.strescape] does the reverse conversion.
2115
 *
2116
 * Returns: a newly-allocated copy of @source with all escaped
2117
 *   character compressed
2118
 */
2119
gchar *
2120
g_strcompress (const gchar *source)
2121
0
{
2122
0
  const gchar *p = source, *octal;
2123
0
  gchar *dest;
2124
0
  gchar *q;
2125
2126
0
  g_return_val_if_fail (source != NULL, NULL);
2127
2128
0
  dest = g_malloc (strlen (source) + 1);
2129
0
  q = dest;
2130
2131
0
  while (*p)
2132
0
    {
2133
0
      if (*p == '\\')
2134
0
        {
2135
0
          p++;
2136
0
          switch (*p)
2137
0
            {
2138
0
            case '\0':
2139
0
              g_warning ("g_strcompress: trailing \\");
2140
0
              goto out;
2141
0
            case '0':  case '1':  case '2':  case '3':  case '4':
2142
0
            case '5':  case '6':  case '7':
2143
0
              *q = 0;
2144
0
              octal = p;
2145
0
              while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
2146
0
                {
2147
0
                  *q = (*q * 8) + (*p - '0');
2148
0
                  p++;
2149
0
                }
2150
0
              q++;
2151
0
              p--;
2152
0
              break;
2153
0
            case 'b':
2154
0
              *q++ = '\b';
2155
0
              break;
2156
0
            case 'f':
2157
0
              *q++ = '\f';
2158
0
              break;
2159
0
            case 'n':
2160
0
              *q++ = '\n';
2161
0
              break;
2162
0
            case 'r':
2163
0
              *q++ = '\r';
2164
0
              break;
2165
0
            case 't':
2166
0
              *q++ = '\t';
2167
0
              break;
2168
0
            case 'v':
2169
0
              *q++ = '\v';
2170
0
              break;
2171
0
            default:            /* Also handles \" and \\ */
2172
0
              *q++ = *p;
2173
0
              break;
2174
0
            }
2175
0
        }
2176
0
      else
2177
0
        *q++ = *p;
2178
0
      p++;
2179
0
    }
2180
0
out:
2181
0
  *q = 0;
2182
2183
0
  return dest;
2184
0
}
2185
2186
/**
2187
 * g_strescape:
2188
 * @source: a string to escape
2189
 * @exceptions: (nullable): a string of characters not to escape in @source
2190
 *
2191
 * It replaces the following special characters in the string @source
2192
 * with their corresponding C escape sequence:
2193
 *
2194
 * | Symbol                                                                      | Escape |
2195
 * |-----------------------------------------------------------------------------|--------|
2196
 * | [U+0008 Backspace](https://en.wikipedia.org/wiki/Backspace)                 | `\b`   |
2197
 * | [U+000C Form Feed](https://en.wikipedia.org/wiki/Form_feed)                 | `\f`   |
2198
 * | [U+000A Line Feed](https://en.wikipedia.org/wiki/Newline)                   | `\n`   |
2199
 * | [U+000D Carriage Return](https://en.wikipedia.org/wiki/Carriage_return)     | `\r`   |
2200
 * | [U+0009 Horizontal Tabulation](https://en.wikipedia.org/wiki/Tab_character) | `\t`   |
2201
 * | [U+000B Vertical Tabulation](https://en.wikipedia.org/wiki/Vertical_Tab)    | `\v`   |
2202
 *
2203
 * It also inserts a backslash (`\`) before any backslash or a double quote (`"`).
2204
 * Additionally all characters in the range 0x01-0x1F (everything
2205
 * below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are
2206
 * replaced with a backslash followed by their octal representation.
2207
 * Characters supplied in @exceptions are not escaped.
2208
 *
2209
 * [func@GLib.strcompress] does the reverse conversion.
2210
 *
2211
 * Returns: a newly-allocated copy of @source with special characters escaped
2212
 */
2213
gchar *
2214
g_strescape (const gchar *source,
2215
             const gchar *exceptions)
2216
0
{
2217
0
  size_t len;
2218
0
  const guchar *p;
2219
0
  gchar *dest;
2220
0
  gchar *q;
2221
0
  guchar excmap[256];
2222
2223
0
  g_return_val_if_fail (source != NULL, NULL);
2224
2225
0
  p = (guchar *) source;
2226
  /* Each source byte needs maximally four destination chars (\777) */
2227
0
  if (!g_size_checked_mul (&len, strlen (source), 4) ||
2228
0
      !g_size_checked_add (&len, len, 1))
2229
0
    {
2230
0
      g_error ("%s: overflow allocating %" G_GSIZE_FORMAT "*4+1 bytes",
2231
0
               G_STRLOC, strlen (source));
2232
0
    }
2233
0
  q = dest = g_malloc (len);
2234
2235
0
  memset (excmap, 0, 256);
2236
0
  if (exceptions)
2237
0
    {
2238
0
      guchar *e = (guchar *) exceptions;
2239
2240
0
      while (*e)
2241
0
        {
2242
0
          excmap[*e] = 1;
2243
0
          e++;
2244
0
        }
2245
0
    }
2246
2247
0
  while (*p)
2248
0
    {
2249
0
      if (excmap[*p])
2250
0
        *q++ = *p;
2251
0
      else
2252
0
        {
2253
0
          switch (*p)
2254
0
            {
2255
0
            case '\b':
2256
0
              *q++ = '\\';
2257
0
              *q++ = 'b';
2258
0
              break;
2259
0
            case '\f':
2260
0
              *q++ = '\\';
2261
0
              *q++ = 'f';
2262
0
              break;
2263
0
            case '\n':
2264
0
              *q++ = '\\';
2265
0
              *q++ = 'n';
2266
0
              break;
2267
0
            case '\r':
2268
0
              *q++ = '\\';
2269
0
              *q++ = 'r';
2270
0
              break;
2271
0
            case '\t':
2272
0
              *q++ = '\\';
2273
0
              *q++ = 't';
2274
0
              break;
2275
0
            case '\v':
2276
0
              *q++ = '\\';
2277
0
              *q++ = 'v';
2278
0
              break;
2279
0
            case '\\':
2280
0
              *q++ = '\\';
2281
0
              *q++ = '\\';
2282
0
              break;
2283
0
            case '"':
2284
0
              *q++ = '\\';
2285
0
              *q++ = '"';
2286
0
              break;
2287
0
            default:
2288
0
              if ((*p < ' ') || (*p >= 0177))
2289
0
                {
2290
0
                  *q++ = '\\';
2291
0
                  *q++ = '0' + (((*p) >> 6) & 07);
2292
0
                  *q++ = '0' + (((*p) >> 3) & 07);
2293
0
                  *q++ = '0' + ((*p) & 07);
2294
0
                }
2295
0
              else
2296
0
                *q++ = *p;
2297
0
              break;
2298
0
            }
2299
0
        }
2300
0
      p++;
2301
0
    }
2302
0
  *q = 0;
2303
0
  return dest;
2304
0
}
2305
2306
/**
2307
 * g_strchug:
2308
 * @string: a string to remove the leading whitespace from
2309
 *
2310
 * Removes leading whitespace from a string, by moving the rest
2311
 * of the characters forward.
2312
 *
2313
 * This function doesn't allocate or reallocate any memory;
2314
 * it modifies @string in place. Therefore, it cannot be used on
2315
 * statically allocated strings.
2316
 *
2317
 * The pointer to @string is returned to allow the nesting of functions.
2318
 *
2319
 * Also see [func@GLib.strchomp] and [func@GLib.strstrip].
2320
 *
2321
 * Returns: the modified @string
2322
 */
2323
gchar *
2324
g_strchug (gchar *string)
2325
123k
{
2326
123k
  guchar *start;
2327
2328
123k
  g_return_val_if_fail (string != NULL, NULL);
2329
2330
128k
  for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
2331
5.16k
    ;
2332
2333
123k
  memmove (string, start, strlen ((gchar *) start) + 1);
2334
2335
123k
  return string;
2336
123k
}
2337
2338
/**
2339
 * g_strchomp:
2340
 * @string: a string to remove the trailing whitespace from
2341
 *
2342
 * Removes trailing whitespace from a string.
2343
 *
2344
 * This function doesn't allocate or reallocate any memory;
2345
 * it modifies @string in place. Therefore, it cannot be used
2346
 * on statically allocated strings.
2347
 *
2348
 * The pointer to @string is returned to allow the nesting of functions.
2349
 *
2350
 * Also see [func@GLib.strchug] and [func@GLib.strstrip].
2351
 *
2352
 * Returns: the modified @string
2353
 */
2354
gchar *
2355
g_strchomp (gchar *string)
2356
161k
{
2357
161k
  gsize len;
2358
2359
161k
  g_return_val_if_fail (string != NULL, NULL);
2360
2361
161k
  len = strlen (string);
2362
178k
  while (len--)
2363
163k
    {
2364
163k
      if (g_ascii_isspace ((guchar) string[len]))
2365
16.9k
        string[len] = '\0';
2366
146k
      else
2367
146k
        break;
2368
163k
    }
2369
2370
161k
  return string;
2371
161k
}
2372
2373
/**
2374
 * g_strsplit:
2375
 * @string: a string to split
2376
 * @delimiter: a string which specifies the places at which to split
2377
 *   the string. The delimiter is not included in any of the resulting
2378
 *   strings, unless @max_tokens is reached.
2379
 * @max_tokens: the maximum number of pieces to split @string into
2380
 *   If this is less than 1, the string is split completely
2381
 *
2382
 * Splits a string into a maximum of @max_tokens pieces, using the given
2383
 * @delimiter. If @max_tokens is reached, the remainder of @string is
2384
 * appended to the last token.
2385
 *
2386
 * As an example, the result of `g_strsplit (":a:bc::d:", ":", -1)` is an array
2387
 * containing the six strings "", "a", "bc", "", "d" and "".
2388
 *
2389
 * As a special case, the result of splitting the empty string "" is an empty
2390
 * array, not an array containing a single string. The reason for this
2391
 * special case is that being able to represent an empty array is typically
2392
 * more useful than consistent handling of empty elements. If you do need
2393
 * to represent empty elements, you'll need to check for the empty string
2394
 * before calling `g_strsplit()`.
2395
 *
2396
 * Returns: (transfer full): a newly-allocated array of strings, freed with
2397
 *   [func@GLib.strfreev]
2398
 */
2399
gchar**
2400
g_strsplit (const gchar *string,
2401
            const gchar *delimiter,
2402
            gint         max_tokens)
2403
4.50k
{
2404
4.50k
  char *s;
2405
4.50k
  const gchar *remainder;
2406
4.50k
  GPtrArray *string_list;
2407
2408
4.50k
  g_return_val_if_fail (string != NULL, NULL);
2409
4.50k
  g_return_val_if_fail (delimiter != NULL, NULL);
2410
4.50k
  g_return_val_if_fail (delimiter[0] != '\0', NULL);
2411
2412
4.50k
  if (max_tokens < 1)
2413
4.50k
    {
2414
4.50k
      max_tokens = G_MAXINT;
2415
4.50k
      string_list = g_ptr_array_new ();
2416
4.50k
    }
2417
0
  else
2418
0
    {
2419
0
      string_list = g_ptr_array_new_full (max_tokens + 1, NULL);
2420
0
    }
2421
2422
4.50k
  remainder = string;
2423
4.50k
  s = strstr (remainder, delimiter);
2424
4.50k
  if (s)
2425
1.95k
    {
2426
1.95k
      gsize delimiter_len = strlen (delimiter);
2427
2428
363k
      while (--max_tokens && s)
2429
361k
        {
2430
361k
          gsize len;
2431
2432
361k
          len = s - remainder;
2433
361k
          g_ptr_array_add (string_list, g_strndup (remainder, len));
2434
361k
          remainder = s + delimiter_len;
2435
361k
          s = strstr (remainder, delimiter);
2436
361k
        }
2437
1.95k
    }
2438
4.50k
  if (*string)
2439
3.90k
    g_ptr_array_add (string_list, g_strdup (remainder));
2440
2441
4.50k
  g_ptr_array_add (string_list, NULL);
2442
2443
4.50k
  return (char **) g_ptr_array_free (string_list, FALSE);
2444
4.50k
}
2445
2446
/**
2447
 * g_strsplit_set:
2448
 * @string: a string to split
2449
 * @delimiters: a string containing characters that are used to split the
2450
 *   string. Can be empty, which will result in no string splitting
2451
 * @max_tokens: the maximum number of tokens to split @string into.
2452
 *   If this is less than 1, the string is split completely
2453
 *
2454
 * Splits @string into a number of tokens not containing any of the characters
2455
 * in @delimiters. A token is the (possibly empty) longest string that does not
2456
 * contain any of the characters in @delimiters. If @max_tokens is reached, the
2457
 * remainder is appended to the last token.
2458
 *
2459
 * For example, the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is an
2460
 * array containing the three strings "abc", "def", and "ghi".
2461
 *
2462
 * The result of g_strsplit_set (":def/ghi:", ":/", -1) is an array containing
2463
 * the four strings "", "def", "ghi", and "".
2464
 *
2465
 * As a special case, the result of splitting the empty string "" is an empty
2466
 * array, not an array containing a single string. The reason for this
2467
 * special case is that being able to represent an empty array is typically
2468
 * more useful than consistent handling of empty elements. If you do need
2469
 * to represent empty elements, you'll need to check for the empty string
2470
 * before calling `g_strsplit_set()`.
2471
 *
2472
 * Note that this function works on bytes not characters, so it can't be used
2473
 * to delimit UTF-8 strings for anything but ASCII characters.
2474
 *
2475
 * Returns: (transfer full): a newly-allocated array of strings. Use
2476
 *   [func@GLib.strfreev] to free it.
2477
 *
2478
 * Since: 2.4
2479
 **/
2480
gchar **
2481
g_strsplit_set (const gchar *string,
2482
                const gchar *delimiters,
2483
                gint         max_tokens)
2484
2.05k
{
2485
2.05k
  guint8 delim_table[256]; /* 1 = index is a separator; 0 otherwise */
2486
2.05k
  GSList *tokens, *list;
2487
2.05k
  gint n_tokens;
2488
2.05k
  const gchar *s;
2489
2.05k
  const gchar *current;
2490
2.05k
  gchar *token;
2491
2.05k
  gchar **result;
2492
2493
2.05k
  g_return_val_if_fail (string != NULL, NULL);
2494
2.05k
  g_return_val_if_fail (delimiters != NULL, NULL);
2495
2496
2.05k
  if (max_tokens < 1)
2497
2.03k
    max_tokens = G_MAXINT;
2498
2499
2.05k
  if (*string == '\0')
2500
35
    {
2501
35
      result = g_new (char *, 1);
2502
35
      result[0] = NULL;
2503
35
      return result;
2504
35
    }
2505
2506
  /* Check if each character in @string is a separator, by indexing by the
2507
   * character value into the @delim_table, which has value 1 stored at an index
2508
   * if that index is a separator. */
2509
2.02k
  memset (delim_table, FALSE, sizeof (delim_table));
2510
6.09k
  for (s = delimiters; *s != '\0'; ++s)
2511
4.07k
    delim_table[*(guchar *)s] = TRUE;
2512
2513
2.02k
  tokens = NULL;
2514
2.02k
  n_tokens = 0;
2515
2516
2.02k
  s = current = string;
2517
132k
  while (*s != '\0')
2518
130k
    {
2519
130k
      if (delim_table[*(guchar *)s] && n_tokens + 1 < max_tokens)
2520
22.1k
        {
2521
22.1k
          token = g_strndup (current, s - current);
2522
22.1k
          tokens = g_slist_prepend (tokens, token);
2523
22.1k
          ++n_tokens;
2524
2525
22.1k
          current = s + 1;
2526
22.1k
        }
2527
2528
130k
      ++s;
2529
130k
    }
2530
2531
2.02k
  token = g_strndup (current, s - current);
2532
2.02k
  tokens = g_slist_prepend (tokens, token);
2533
2.02k
  ++n_tokens;
2534
2535
2.02k
  result = g_new (gchar *, n_tokens + 1);
2536
2537
2.02k
  result[n_tokens] = NULL;
2538
26.1k
  for (list = tokens; list != NULL; list = list->next)
2539
24.1k
    result[--n_tokens] = list->data;
2540
2541
2.02k
  g_slist_free (tokens);
2542
2543
2.02k
  return result;
2544
2.05k
}
2545
2546
/**
2547
 * GStrv:
2548
 *
2549
 * A typedef alias for gchar**. This is mostly useful when used together with
2550
 * `g_auto()`.
2551
 */
2552
2553
/**
2554
 * g_strfreev:
2555
 * @str_array: (array zero-terminated=1) (nullable) (transfer full): an
2556
 *   array of strings to free
2557
 *
2558
 * Frees an array of strings, as well as each string it contains.
2559
 *
2560
 * If @str_array is `NULL`, this function simply returns.
2561
 */
2562
void
2563
g_strfreev (gchar **str_array)
2564
38.6k
{
2565
38.6k
  if (str_array)
2566
38.6k
    {
2567
38.6k
      gsize i;
2568
2569
430k
      for (i = 0; str_array[i] != NULL; i++)
2570
391k
        g_free (str_array[i]);
2571
2572
38.6k
      g_free (str_array);
2573
38.6k
    }
2574
38.6k
}
2575
2576
/**
2577
 * g_strdupv:
2578
 * @str_array: (array zero-terminated=1) (nullable): an array of strings to copy
2579
 *
2580
 * Copies an array of strings. The copy is a deep copy; each string is also
2581
 * copied.
2582
 *
2583
 * If called on a `NULL` value, `g_strdupv()` simply returns `NULL`.
2584
 *
2585
 * Returns: (array zero-terminated=1) (nullable) (transfer full): a
2586
 *   newly-allocated array of strings. Use [func@GLib.strfreev] to free it.
2587
 */
2588
gchar**
2589
g_strdupv (gchar **str_array)
2590
445
{
2591
445
  if (str_array)
2592
391
    {
2593
391
      gsize i;
2594
391
      gchar **retval;
2595
2596
391
      i = 0;
2597
998
      while (str_array[i])
2598
607
        ++i;
2599
2600
391
      retval = g_new (gchar*, i + 1);
2601
2602
391
      i = 0;
2603
998
      while (str_array[i])
2604
607
        {
2605
607
          retval[i] = g_strdup (str_array[i]);
2606
607
          ++i;
2607
607
        }
2608
391
      retval[i] = NULL;
2609
2610
391
      return retval;
2611
391
    }
2612
54
  else
2613
54
    return NULL;
2614
445
}
2615
2616
/**
2617
 * g_strjoinv:
2618
 * @separator: (nullable): a string to insert between each of the strings
2619
 * @str_array: (array zero-terminated=1): an array of strings to join
2620
 *
2621
 * Joins an array of strings together to form one long string, with the
2622
 * optional @separator inserted between each of them.
2623
 *
2624
 * If @str_array has no items, the return value will be an
2625
 * empty string. If @str_array contains a single item, @separator will not
2626
 * appear in the resulting string.
2627
 *
2628
 * Returns: a newly-allocated string containing all of the strings joined
2629
 *   together, with @separator between them
2630
 */
2631
gchar*
2632
g_strjoinv (const gchar  *separator,
2633
            gchar       **str_array)
2634
0
{
2635
0
  gchar *string;
2636
0
  gchar *ptr;
2637
2638
0
  g_return_val_if_fail (str_array != NULL, NULL);
2639
2640
0
  if (separator == NULL)
2641
0
    separator = "";
2642
2643
0
  if (*str_array)
2644
0
    {
2645
0
      gsize i;
2646
0
      gsize len;
2647
0
      gsize separator_len;
2648
2649
0
      separator_len = strlen (separator);
2650
      /* First part, getting length */
2651
0
      len = 1 + strlen (str_array[0]);
2652
0
      for (i = 1; str_array[i] != NULL; i++)
2653
0
        len += strlen (str_array[i]);
2654
0
      len += separator_len * (i - 1);
2655
2656
      /* Second part, building string */
2657
0
      string = g_new (gchar, len);
2658
0
      ptr = g_stpcpy (string, *str_array);
2659
0
      for (i = 1; str_array[i] != NULL; i++)
2660
0
        {
2661
0
          ptr = g_stpcpy (ptr, separator);
2662
0
          ptr = g_stpcpy (ptr, str_array[i]);
2663
0
        }
2664
0
      }
2665
0
  else
2666
0
    string = g_strdup ("");
2667
2668
0
  return string;
2669
0
}
2670
2671
/**
2672
 * g_strjoin:
2673
 * @separator: (nullable): a string to insert between each of the strings
2674
 * @...: a `NULL`-terminated list of strings to join
2675
 *
2676
 * Joins a number of strings together to form one long string, with the
2677
 * optional @separator inserted between each of them.
2678
 *
2679
 * Returns: a newly-allocated string containing all of the strings joined
2680
 *   together, with @separator between them
2681
 */
2682
gchar*
2683
g_strjoin (const gchar *separator,
2684
           ...)
2685
208k
{
2686
208k
  gchar *string, *s;
2687
208k
  va_list args;
2688
208k
  gsize len;
2689
208k
  gsize separator_len;
2690
208k
  gchar *ptr;
2691
2692
208k
  if (separator == NULL)
2693
0
    separator = "";
2694
2695
208k
  separator_len = strlen (separator);
2696
2697
208k
  va_start (args, separator);
2698
2699
208k
  s = va_arg (args, gchar*);
2700
2701
208k
  if (s)
2702
208k
    {
2703
      /* First part, getting length */
2704
208k
      len = 1 + strlen (s);
2705
2706
208k
      s = va_arg (args, gchar*);
2707
416k
      while (s)
2708
208k
        {
2709
208k
          len += separator_len + strlen (s);
2710
208k
          s = va_arg (args, gchar*);
2711
208k
        }
2712
208k
      va_end (args);
2713
2714
      /* Second part, building string */
2715
208k
      string = g_new (gchar, len);
2716
2717
208k
      va_start (args, separator);
2718
2719
208k
      s = va_arg (args, gchar*);
2720
208k
      ptr = g_stpcpy (string, s);
2721
2722
208k
      s = va_arg (args, gchar*);
2723
416k
      while (s)
2724
208k
        {
2725
208k
          ptr = g_stpcpy (ptr, separator);
2726
208k
          ptr = g_stpcpy (ptr, s);
2727
208k
          s = va_arg (args, gchar*);
2728
208k
        }
2729
208k
    }
2730
0
  else
2731
0
    string = g_strdup ("");
2732
2733
208k
  va_end (args);
2734
2735
208k
  return string;
2736
208k
}
2737
2738
2739
/**
2740
 * g_strstr_len:
2741
 * @haystack: a string to search in
2742
 * @haystack_len: the maximum length of @haystack in bytes, or `-1` to
2743
 *   search it entirely
2744
 * @needle: the string to search for
2745
 *
2746
 * Searches the string @haystack for the first occurrence
2747
 * of the string @needle, limiting the length of the search
2748
 * to @haystack_len or a nul terminator byte (whichever is reached first).
2749
 *
2750
 * A length of `-1` can be used to mean “search the entire string”, like
2751
 * `strstr()`.
2752
 *
2753
 * The fact that this function returns `gchar *` rather than `const gchar *` is
2754
 * a historical artifact.
2755
 *
2756
 * Returns: (transfer none) (nullable): a pointer to the found occurrence, or
2757
 *    `NULL` if not found
2758
 */
2759
gchar *
2760
g_strstr_len (const gchar *haystack,
2761
              gssize       haystack_len,
2762
              const gchar *needle)
2763
29.4k
{
2764
29.4k
  g_return_val_if_fail (haystack != NULL, NULL);
2765
29.4k
  g_return_val_if_fail (needle != NULL, NULL);
2766
2767
29.4k
  if (haystack_len < 0)
2768
1.61k
    return strstr (haystack, needle);
2769
27.8k
  else
2770
27.8k
    {
2771
27.8k
      const gchar *p = haystack;
2772
27.8k
      gsize needle_len = strlen (needle);
2773
27.8k
      gsize haystack_len_unsigned = haystack_len;
2774
27.8k
      const gchar *end;
2775
27.8k
      gsize i;
2776
2777
27.8k
      if (needle_len == 0)
2778
0
        return (gchar *)haystack;
2779
2780
27.8k
      if (haystack_len_unsigned < needle_len)
2781
601
        return NULL;
2782
2783
27.2k
      end = haystack + haystack_len - needle_len;
2784
2785
1.44M
      while (p <= end && *p)
2786
1.43M
        {
2787
1.49M
          for (i = 0; i < needle_len; i++)
2788
1.47M
            if (p[i] != needle[i])
2789
1.41M
              goto next;
2790
2791
14.9k
          return (gchar *)p;
2792
2793
1.41M
        next:
2794
1.41M
          p++;
2795
1.41M
        }
2796
2797
12.2k
      return NULL;
2798
27.2k
    }
2799
29.4k
}
2800
2801
/**
2802
 * g_strrstr:
2803
 * @haystack: a string to search in
2804
 * @needle: the string to search for
2805
 *
2806
 * Searches the string @haystack for the last occurrence
2807
 * of the string @needle.
2808
 *
2809
 * The fact that this function returns `gchar *` rather than `const gchar *` is
2810
 * a historical artifact.
2811
 *
2812
 * Returns: (transfer none) (nullable): a pointer to the found occurrence, or
2813
 *    `NULL` if not found
2814
 */
2815
gchar *
2816
g_strrstr (const gchar *haystack,
2817
           const gchar *needle)
2818
13.5k
{
2819
13.5k
  gsize i;
2820
13.5k
  gsize needle_len;
2821
13.5k
  gsize haystack_len;
2822
13.5k
  const gchar *p;
2823
2824
13.5k
  g_return_val_if_fail (haystack != NULL, NULL);
2825
13.5k
  g_return_val_if_fail (needle != NULL, NULL);
2826
2827
13.5k
  needle_len = strlen (needle);
2828
13.5k
  haystack_len = strlen (haystack);
2829
2830
13.5k
  if (needle_len == 0)
2831
0
    return (gchar *)haystack;
2832
2833
13.5k
  if (haystack_len < needle_len)
2834
4.64k
    return NULL;
2835
2836
8.90k
  p = haystack + haystack_len - needle_len;
2837
2838
40.6k
  while (p >= haystack)
2839
33.5k
    {
2840
53.5k
      for (i = 0; i < needle_len; i++)
2841
51.7k
        if (p[i] != needle[i])
2842
31.7k
          goto next;
2843
2844
1.81k
      return (gchar *)p;
2845
2846
31.7k
    next:
2847
31.7k
      p--;
2848
31.7k
    }
2849
2850
7.09k
  return NULL;
2851
8.90k
}
2852
2853
/**
2854
 * g_strrstr_len:
2855
 * @haystack: a string to search in
2856
 * @haystack_len: the maximum length of @haystack in bytes. A length of `-1`
2857
 *   can be used to mean "search the entire string", like [func@GLib.strrstr]
2858
 * @needle: the string to search for
2859
 *
2860
 * Searches the string @haystack for the last occurrence
2861
 * of the string @needle, limiting the length of the search
2862
 * to @haystack_len.
2863
 *
2864
 * The fact that this function returns `gchar *` rather than `const gchar *` is
2865
 * a historical artifact.
2866
 *
2867
 * Returns: (transfer none) (nullable): a pointer to the found occurrence, or
2868
 *    `NULL` if not found
2869
 */
2870
gchar *
2871
g_strrstr_len (const gchar *haystack,
2872
               gssize        haystack_len,
2873
               const gchar *needle)
2874
0
{
2875
0
  g_return_val_if_fail (haystack != NULL, NULL);
2876
0
  g_return_val_if_fail (needle != NULL, NULL);
2877
2878
0
  if (haystack_len < 0)
2879
0
    return g_strrstr (haystack, needle);
2880
0
  else
2881
0
    {
2882
0
      gsize needle_len = strlen (needle);
2883
0
      const gchar *haystack_max = haystack + haystack_len;
2884
0
      const gchar *p = haystack;
2885
0
      gsize i;
2886
2887
0
      while (p < haystack_max && *p)
2888
0
        p++;
2889
2890
0
      if (p < haystack + needle_len)
2891
0
        return NULL;
2892
2893
0
      p -= needle_len;
2894
2895
0
      while (p >= haystack)
2896
0
        {
2897
0
          for (i = 0; i < needle_len; i++)
2898
0
            if (p[i] != needle[i])
2899
0
              goto next;
2900
2901
0
          return (gchar *)p;
2902
2903
0
        next:
2904
0
          p--;
2905
0
        }
2906
2907
0
      return NULL;
2908
0
    }
2909
0
}
2910
2911
2912
/**
2913
 * g_str_has_suffix:
2914
 * @str: a string to look in
2915
 * @suffix: the suffix to look for
2916
 *
2917
 * Looks whether a string ends with @suffix.
2918
 *
2919
 * Returns: true if @str ends with @suffix, false otherwise
2920
 *
2921
 * Since: 2.2
2922
 */
2923
gboolean (g_str_has_suffix) (const gchar *str,
2924
                             const gchar *suffix)
2925
686
{
2926
686
  gsize str_len;
2927
686
  gsize suffix_len;
2928
2929
686
  g_return_val_if_fail (str != NULL, FALSE);
2930
686
  g_return_val_if_fail (suffix != NULL, FALSE);
2931
2932
686
  str_len = strlen (str);
2933
686
  suffix_len = strlen (suffix);
2934
2935
686
  if (str_len < suffix_len)
2936
654
    return FALSE;
2937
2938
32
  return strcmp (str + str_len - suffix_len, suffix) == 0;
2939
686
}
2940
2941
/**
2942
 * g_str_has_prefix:
2943
 * @str: a string to look in
2944
 * @prefix: the prefix to look for
2945
 *
2946
 * Looks whether the string @str begins with @prefix.
2947
 *
2948
 * Returns: true if @str begins with @prefix, false otherwise
2949
 *
2950
 * Since: 2.2
2951
 */
2952
gboolean (g_str_has_prefix) (const gchar *str,
2953
                             const gchar *prefix)
2954
4.43k
{
2955
4.43k
  g_return_val_if_fail (str != NULL, FALSE);
2956
4.43k
  g_return_val_if_fail (prefix != NULL, FALSE);
2957
2958
4.43k
  return strncmp (str, prefix, strlen (prefix)) == 0;
2959
4.43k
}
2960
2961
/**
2962
 * g_strv_length:
2963
 * @str_array: (array zero-terminated=1): an array of strings
2964
 *
2965
 * Returns the length of an array of strings. @str_array must not be `NULL`.
2966
 *
2967
 * Returns: length of @str_array
2968
 *
2969
 * Since: 2.6
2970
 */
2971
guint
2972
g_strv_length (gchar **str_array)
2973
2.34k
{
2974
2.34k
  guint i = 0;
2975
2976
2.34k
  g_return_val_if_fail (str_array != NULL, 0);
2977
2978
360k
  while (str_array[i])
2979
358k
    ++i;
2980
2981
2.34k
  return i;
2982
2.34k
}
2983
2984
static void
2985
index_add_folded (GPtrArray   *array,
2986
                  const gchar *start,
2987
                  const gchar *end)
2988
0
{
2989
0
  gchar *normal;
2990
2991
0
  normal = g_utf8_normalize (start, end - start, G_NORMALIZE_ALL_COMPOSE);
2992
2993
  /* TODO: Invent time machine.  Converse with Mustafa Ataturk... */
2994
0
  if (strstr (normal, "ı") || strstr (normal, "İ"))
2995
0
    {
2996
0
      gchar *s = normal;
2997
0
      GString *tmp;
2998
2999
0
      tmp = g_string_new (NULL);
3000
3001
0
      while (*s)
3002
0
        {
3003
0
          gchar *i, *I, *e;
3004
3005
0
          i = strstr (s, "ı");
3006
0
          I = strstr (s, "İ");
3007
3008
0
          if (!i && !I)
3009
0
            break;
3010
0
          else if (i && !I)
3011
0
            e = i;
3012
0
          else if (I && !i)
3013
0
            e = I;
3014
0
          else if (i < I)
3015
0
            e = i;
3016
0
          else
3017
0
            e = I;
3018
3019
0
          g_string_append_len (tmp, s, e - s);
3020
0
          g_string_append_c (tmp, 'i');
3021
0
          s = g_utf8_next_char (e);
3022
0
        }
3023
3024
0
      g_string_append (tmp, s);
3025
0
      g_free (normal);
3026
0
      normal = g_string_free (tmp, FALSE);
3027
0
    }
3028
3029
0
  g_ptr_array_add (array, g_utf8_casefold (normal, -1));
3030
0
  g_free (normal);
3031
0
}
3032
3033
static gchar **
3034
split_words (const gchar *value)
3035
0
{
3036
0
  const gchar *start = NULL;
3037
0
  GPtrArray *result;
3038
0
  const gchar *s;
3039
3040
0
  result = g_ptr_array_new ();
3041
3042
0
  for (s = value; *s; s = g_utf8_next_char (s))
3043
0
    {
3044
0
      gunichar c = g_utf8_get_char (s);
3045
3046
0
      if (start == NULL)
3047
0
        {
3048
0
          if (g_unichar_isalnum (c) || g_unichar_ismark (c))
3049
0
            start = s;
3050
0
        }
3051
0
      else
3052
0
        {
3053
0
          if (!g_unichar_isalnum (c) && !g_unichar_ismark (c))
3054
0
            {
3055
0
              index_add_folded (result, start, s);
3056
0
              start = NULL;
3057
0
            }
3058
0
        }
3059
0
    }
3060
3061
0
  if (start)
3062
0
    index_add_folded (result, start, s);
3063
3064
0
  g_ptr_array_add (result, NULL);
3065
3066
0
  return (gchar **) g_ptr_array_free (result, FALSE);
3067
0
}
3068
3069
/**
3070
 * g_str_tokenize_and_fold:
3071
 * @string: a string to tokenize
3072
 * @translit_locale: (nullable): the language code (like 'de' or
3073
 *   'en_GB') from which @string originates
3074
 * @ascii_alternates: (out) (optional) (transfer full) (array zero-terminated=1):
3075
 *   a return location for ASCII alternates
3076
 *
3077
 * Tokenizes @string and performs folding on each token.
3078
 *
3079
 * A token is a non-empty sequence of alphanumeric characters in the
3080
 * source string, separated by non-alphanumeric characters.  An
3081
 * "alphanumeric" character for this purpose is one that matches
3082
 * [func@GLib.unichar_isalnum] or [func@GLib.unichar_ismark].
3083
 *
3084
 * Each token is then (Unicode) normalised and case-folded.  If
3085
 * @ascii_alternates is non-`NULL` and some of the returned tokens
3086
 * contain non-ASCII characters, ASCII alternatives will be generated.
3087
 *
3088
 * The number of ASCII alternatives that are generated and the method
3089
 * for doing so is unspecified, but @translit_locale (if specified) may
3090
 * improve the transliteration if the language of the source string is
3091
 * known.
3092
 *
3093
 * Returns: (transfer full) (array zero-terminated=1): the folded tokens
3094
 *
3095
 * Since: 2.40
3096
 **/
3097
gchar **
3098
g_str_tokenize_and_fold (const gchar   *string,
3099
                         const gchar   *translit_locale,
3100
                         gchar       ***ascii_alternates)
3101
0
{
3102
0
  gchar **result;
3103
3104
0
  g_return_val_if_fail (string != NULL, NULL);
3105
3106
0
  if (ascii_alternates && g_str_is_ascii (string))
3107
0
    {
3108
0
      *ascii_alternates = g_new0 (gchar *, 0 + 1);
3109
0
      ascii_alternates = NULL;
3110
0
    }
3111
3112
0
  result = split_words (string);
3113
3114
0
  if (ascii_alternates)
3115
0
    {
3116
0
      gint i, j, n;
3117
3118
0
      n = g_strv_length (result);
3119
0
      *ascii_alternates = g_new (gchar *, n + 1);
3120
0
      j = 0;
3121
3122
0
      for (i = 0; i < n; i++)
3123
0
        {
3124
0
          if (!g_str_is_ascii (result[i]))
3125
0
            {
3126
0
              gchar *composed;
3127
0
              gchar *ascii;
3128
0
              gint k;
3129
3130
0
              composed = g_utf8_normalize (result[i], -1, G_NORMALIZE_ALL_COMPOSE);
3131
3132
0
              ascii = g_str_to_ascii (composed, translit_locale);
3133
3134
              /* Only accept strings that are now entirely alnums */
3135
0
              for (k = 0; ascii[k]; k++)
3136
0
                if (!g_ascii_isalnum (ascii[k]))
3137
0
                  break;
3138
3139
0
              if (ascii[k] == '\0')
3140
                /* Made it to the end... */
3141
0
                (*ascii_alternates)[j++] = ascii;
3142
0
              else
3143
0
                g_free (ascii);
3144
3145
0
              g_free (composed);
3146
0
            }
3147
0
        }
3148
3149
0
      (*ascii_alternates)[j] = NULL;
3150
0
    }
3151
3152
0
  return result;
3153
0
}
3154
3155
/**
3156
 * g_str_match_string:
3157
 * @search_term: the search term from the user
3158
 * @potential_hit: the text that may be a hit
3159
 * @accept_alternates: if true, ASCII alternates are accepted
3160
 *
3161
 * Checks if a search conducted for @search_term should match
3162
 * @potential_hit.
3163
 *
3164
 * This function calls [func@GLib.str_tokenize_and_fold] on both
3165
 * @search_term and @potential_hit. ASCII alternates are never taken
3166
 * for @search_term but will be taken for @potential_hit according to
3167
 * the value of @accept_alternates.
3168
 *
3169
 * A hit occurs when each folded token in @search_term is a prefix of a
3170
 * folded token from @potential_hit.
3171
 *
3172
 * Depending on how you're performing the search, it will typically be
3173
 * faster to call `g_str_tokenize_and_fold()` on each string in
3174
 * your corpus and build an index on the returned folded tokens, then
3175
 * call `g_str_tokenize_and_fold()` on the search term and
3176
 * perform lookups into that index.
3177
 *
3178
 * As some examples, searching for ‘fred’ would match the potential hit
3179
 * ‘Smith, Fred’ and also ‘Frédéric’.  Searching for ‘Fréd’ would match
3180
 * ‘Frédéric’ but not ‘Frederic’ (due to the one-directional nature of
3181
 * accent matching).  Searching ‘fo’ would match ‘Foo’ and ‘Bar Foo
3182
 * Baz’, but not ‘SFO’ (because no word has ‘fo’ as a prefix).
3183
 *
3184
 * Returns: true if @potential_hit is a hit
3185
 *
3186
 * Since: 2.40
3187
 **/
3188
gboolean
3189
g_str_match_string (const gchar *search_term,
3190
                    const gchar *potential_hit,
3191
                    gboolean     accept_alternates)
3192
0
{
3193
0
  gchar **alternates = NULL;
3194
0
  gchar **term_tokens;
3195
0
  gchar **hit_tokens;
3196
0
  gboolean matched;
3197
0
  gint i, j;
3198
3199
0
  g_return_val_if_fail (search_term != NULL, FALSE);
3200
0
  g_return_val_if_fail (potential_hit != NULL, FALSE);
3201
3202
0
  term_tokens = g_str_tokenize_and_fold (search_term, NULL, NULL);
3203
0
  hit_tokens = g_str_tokenize_and_fold (potential_hit, NULL, accept_alternates ? &alternates : NULL);
3204
3205
0
  matched = TRUE;
3206
3207
0
  for (i = 0; term_tokens[i]; i++)
3208
0
    {
3209
0
      for (j = 0; hit_tokens[j]; j++)
3210
0
        if (g_str_has_prefix (hit_tokens[j], term_tokens[i]))
3211
0
          goto one_matched;
3212
3213
0
      if (accept_alternates)
3214
0
        for (j = 0; alternates[j]; j++)
3215
0
          if (g_str_has_prefix (alternates[j], term_tokens[i]))
3216
0
            goto one_matched;
3217
3218
0
      matched = FALSE;
3219
0
      break;
3220
3221
0
one_matched:
3222
0
      continue;
3223
0
    }
3224
3225
0
  g_strfreev (term_tokens);
3226
0
  g_strfreev (hit_tokens);
3227
0
  g_strfreev (alternates);
3228
3229
0
  return matched;
3230
0
}
3231
3232
/**
3233
 * g_strv_contains:
3234
 * @strv: (array zero-terminated=1): an array of strings to search in
3235
 * @str: the string to search for
3236
 *
3237
 * Checks if an array of strings contains the string @str according to
3238
 * [func@GLib.str_equal]. @strv must not be `NULL`.
3239
 *
3240
 * Returns: true if @str is an element of @strv
3241
 *
3242
 * Since: 2.44
3243
 */
3244
gboolean
3245
g_strv_contains (const gchar * const *strv,
3246
                 const gchar         *str)
3247
10
{
3248
10
  g_return_val_if_fail (strv != NULL, FALSE);
3249
10
  g_return_val_if_fail (str != NULL, FALSE);
3250
3251
14
  for (; *strv != NULL; strv++)
3252
12
    {
3253
12
      if (g_str_equal (str, *strv))
3254
8
        return TRUE;
3255
12
    }
3256
3257
2
  return FALSE;
3258
10
}
3259
3260
/**
3261
 * g_strv_equal:
3262
 * @strv1: (array zero-terminated=1): an array of strings to compare to @strv2
3263
 * @strv2: (array zero-terminated=1): an array of strings to compare to @strv1
3264
 *
3265
 * Checks if two arrays of strings contain exactly the same elements in
3266
 * exactly the same order.
3267
 *
3268
 * Elements are compared using [func@GLib.str_equal]. To match independently
3269
 * of order, sort the arrays first (using [func@GLib.qsort_with_data]
3270
 * or similar).
3271
 *
3272
 * Two empty arrays are considered equal. Neither @strv1 nor @strv2 may be
3273
 * `NULL`.
3274
 *
3275
 * Returns: true if @strv1 and @strv2 are equal
3276
 * Since: 2.60
3277
 */
3278
gboolean
3279
g_strv_equal (const gchar * const *strv1,
3280
              const gchar * const *strv2)
3281
0
{
3282
0
  g_return_val_if_fail (strv1 != NULL, FALSE);
3283
0
  g_return_val_if_fail (strv2 != NULL, FALSE);
3284
3285
0
  if (strv1 == strv2)
3286
0
    return TRUE;
3287
3288
0
  for (; *strv1 != NULL && *strv2 != NULL; strv1++, strv2++)
3289
0
    {
3290
0
      if (!g_str_equal (*strv1, *strv2))
3291
0
        return FALSE;
3292
0
    }
3293
3294
0
  return (*strv1 == NULL && *strv2 == NULL);
3295
0
}
3296
3297
static gboolean
3298
str_has_sign (const gchar *str)
3299
329
{
3300
329
  return str[0] == '-' || str[0] == '+';
3301
329
}
3302
3303
static gboolean
3304
str_has_hex_prefix (const gchar *str)
3305
0
{
3306
0
  return str[0] == '0' && g_ascii_tolower (str[1]) == 'x';
3307
0
}
3308
3309
/**
3310
 * g_ascii_string_to_signed:
3311
 * @str: a string to convert
3312
 * @base: base of a parsed number
3313
 * @min: a lower bound (inclusive)
3314
 * @max: an upper bound (inclusive)
3315
 * @out_num: (out) (optional): a return location for a number
3316
 * @error: a return location for #GError
3317
 *
3318
 * A convenience function for converting a string to a signed number.
3319
 *
3320
 * This function assumes that @str contains only a number of the given
3321
 * @base that is within inclusive bounds limited by @min and @max. If
3322
 * this is true, then the converted number is stored in @out_num. An
3323
 * empty string is not a valid input. A string with leading or
3324
 * trailing whitespace is also an invalid input.
3325
 *
3326
 * @base can be between 2 and 36 inclusive. Hexadecimal numbers must
3327
 * not be prefixed with "0x" or "0X". Such a problem does not exist
3328
 * for octal numbers, since they were usually prefixed with a zero
3329
 * which does not change the value of the parsed number.
3330
 *
3331
 * Parsing failures result in an error with the `G_NUMBER_PARSER_ERROR`
3332
 * domain. If the input is invalid, the error code will be
3333
 * [error@GLib.NumberParserError.INVALID]. If the parsed number is out of
3334
 * bounds - [error@GLib.NumberParserError.OUT_OF_BOUNDS].
3335
 *
3336
 * See [func@GLib.ascii_strtoll] if you have more complex needs such as
3337
 * parsing a string which starts with a number, but then has other
3338
 * characters.
3339
 *
3340
 * Returns: true if @str was a number, false otherwise
3341
 *
3342
 * Since: 2.54
3343
 */
3344
gboolean
3345
g_ascii_string_to_signed (const gchar  *str,
3346
                          guint         base,
3347
                          gint64        min,
3348
                          gint64        max,
3349
                          gint64       *out_num,
3350
                          GError      **error)
3351
0
{
3352
0
  gint64 number;
3353
0
  const gchar *end_ptr = NULL;
3354
0
  gint saved_errno = 0;
3355
3356
0
  g_return_val_if_fail (str != NULL, FALSE);
3357
0
  g_return_val_if_fail (base >= 2 && base <= 36, FALSE);
3358
0
  g_return_val_if_fail (min <= max, FALSE);
3359
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
3360
3361
0
  if (str[0] == '\0')
3362
0
    {
3363
0
      g_set_error_literal (error,
3364
0
                           G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_INVALID,
3365
0
                           _("Empty string is not a number"));
3366
0
      return FALSE;
3367
0
    }
3368
3369
0
  errno = 0;
3370
0
  number = g_ascii_strtoll (str, (gchar **)&end_ptr, base);
3371
0
  saved_errno = errno;
3372
3373
0
  if (/* We do not allow leading whitespace, but g_ascii_strtoll
3374
       * accepts it and just skips it, so we need to check for it
3375
       * ourselves.
3376
       */
3377
0
      g_ascii_isspace (str[0]) ||
3378
      /* We don't support hexadecimal numbers prefixed with 0x or
3379
       * 0X.
3380
       */
3381
0
      (base == 16 &&
3382
0
       (str_has_sign (str) ? str_has_hex_prefix (str + 1) : str_has_hex_prefix (str))) ||
3383
0
      (saved_errno != 0 && saved_errno != ERANGE) ||
3384
0
      end_ptr == NULL ||
3385
0
      *end_ptr != '\0')
3386
0
    {
3387
0
      g_set_error (error,
3388
0
                   G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_INVALID,
3389
0
                   _("“%s” is not a signed number"), str);
3390
0
      return FALSE;
3391
0
    }
3392
0
  if (saved_errno == ERANGE || number < min || number > max)
3393
0
    {
3394
0
      gchar *min_str = g_strdup_printf ("%" G_GINT64_FORMAT, min);
3395
0
      gchar *max_str = g_strdup_printf ("%" G_GINT64_FORMAT, max);
3396
3397
0
      g_set_error (error,
3398
0
                   G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_OUT_OF_BOUNDS,
3399
0
                   _("Number “%s” is out of bounds [%s, %s]"),
3400
0
                   str, min_str, max_str);
3401
0
      g_free (min_str);
3402
0
      g_free (max_str);
3403
0
      return FALSE;
3404
0
    }
3405
0
  if (out_num != NULL)
3406
0
    *out_num = number;
3407
0
  return TRUE;
3408
0
}
3409
3410
/**
3411
 * g_ascii_string_to_unsigned:
3412
 * @str: a string
3413
 * @base: base of a parsed number
3414
 * @min: a lower bound (inclusive)
3415
 * @max: an upper bound (inclusive)
3416
 * @out_num: (out) (optional): a return location for a number
3417
 * @error: a return location for #GError
3418
 *
3419
 * A convenience function for converting a string to an unsigned number.
3420
 *
3421
 * This function assumes that @str contains only a number of the given
3422
 * @base that is within inclusive bounds limited by @min and @max. If
3423
 * this is true, then the converted number is stored in @out_num. An
3424
 * empty string is not a valid input. A string with leading or
3425
 * trailing whitespace is also an invalid input. A string with a leading sign
3426
 * (`-` or `+`) is not a valid input for the unsigned parser.
3427
 *
3428
 * @base can be between 2 and 36 inclusive. Hexadecimal numbers must
3429
 * not be prefixed with "0x" or "0X". Such a problem does not exist
3430
 * for octal numbers, since they were usually prefixed with a zero
3431
 * which does not change the value of the parsed number.
3432
 *
3433
 * Parsing failures result in an error with the `G_NUMBER_PARSER_ERROR`
3434
 * domain. If the input is invalid, the error code will be
3435
 * [error@GLib.NumberParserError.INVALID]. If the parsed number is out of
3436
 * bounds - [error@GLib.NumberParserError.OUT_OF_BOUNDS].
3437
 *
3438
 * See [func@GLib.ascii_strtoull] if you have more complex needs such as
3439
 * parsing a string which starts with a number, but then has other
3440
 * characters.
3441
 *
3442
 * Returns: true if @str was a number, false otherwise
3443
 *
3444
 * Since: 2.54
3445
 */
3446
gboolean
3447
g_ascii_string_to_unsigned (const gchar  *str,
3448
                            guint         base,
3449
                            guint64       min,
3450
                            guint64       max,
3451
                            guint64      *out_num,
3452
                            GError      **error)
3453
350
{
3454
350
  guint64 number;
3455
350
  const gchar *end_ptr = NULL;
3456
350
  gint saved_errno = 0;
3457
3458
350
  g_return_val_if_fail (str != NULL, FALSE);
3459
350
  g_return_val_if_fail (base >= 2 && base <= 36, FALSE);
3460
350
  g_return_val_if_fail (min <= max, FALSE);
3461
350
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
3462
3463
350
  if (str[0] == '\0')
3464
18
    {
3465
18
      g_set_error_literal (error,
3466
18
                           G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_INVALID,
3467
18
                           _("Empty string is not a number"));
3468
18
      return FALSE;
3469
18
    }
3470
3471
350
  errno = 0;
3472
332
  number = g_ascii_strtoull (str, (gchar **)&end_ptr, base);
3473
332
  saved_errno = errno;
3474
3475
332
  if (/* We do not allow leading whitespace, but g_ascii_strtoull
3476
       * accepts it and just skips it, so we need to check for it
3477
       * ourselves.
3478
       */
3479
332
      g_ascii_isspace (str[0]) ||
3480
      /* Unsigned number should have no sign.
3481
       */
3482
329
      str_has_sign (str) ||
3483
      /* We don't support hexadecimal numbers prefixed with 0x or
3484
       * 0X.
3485
       */
3486
328
      (base == 16 && str_has_hex_prefix (str)) ||
3487
328
      (saved_errno != 0 && saved_errno != ERANGE) ||
3488
328
      end_ptr == NULL ||
3489
328
      *end_ptr != '\0')
3490
135
    {
3491
135
      g_set_error (error,
3492
135
                   G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_INVALID,
3493
135
                   _("“%s” is not an unsigned number"), str);
3494
135
      return FALSE;
3495
135
    }
3496
197
  if (saved_errno == ERANGE || number < min || number > max)
3497
113
    {
3498
113
      gchar *min_str = g_strdup_printf ("%" G_GUINT64_FORMAT, min);
3499
113
      gchar *max_str = g_strdup_printf ("%" G_GUINT64_FORMAT, max);
3500
3501
113
      g_set_error (error,
3502
113
                   G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_OUT_OF_BOUNDS,
3503
113
                   _("Number “%s” is out of bounds [%s, %s]"),
3504
113
                   str, min_str, max_str);
3505
113
      g_free (min_str);
3506
113
      g_free (max_str);
3507
113
      return FALSE;
3508
113
    }
3509
84
  if (out_num != NULL)
3510
84
    *out_num = number;
3511
84
  return TRUE;
3512
197
}
3513
3514
G_DEFINE_QUARK (g-number-parser-error-quark, g_number_parser_error)