Coverage Report

Created: 2025-12-31 06:32

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