Coverage Report

Created: 2026-10-14 08:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib-2.88.3/glib/gstrfuncs.c
Line
Count
Source
1
/* GLIB - Library of useful routines for C programming
2
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3
 *
4
 * SPDX-License-Identifier: LGPL-2.1-or-later
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
/*
21
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22
 * file for a list of people on the GLib Team.  See the ChangeLog
23
 * files for a list of changes.  These files are distributed with
24
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
25
 */
26
27
/*
28
 * MT safe
29
 */
30
31
#include "config.h"
32
33
#include <stdarg.h>
34
#include <stdio.h>
35
#include <stdlib.h>
36
#include <locale.h>
37
#include <string.h>
38
#include <locale.h>
39
#include <errno.h>
40
#include <garray.h>
41
#include <ctype.h>              /* For tolower() */
42
43
#ifdef HAVE_XLOCALE_H
44
/* Needed on BSD/OS X for e.g. strtod_l */
45
#include <xlocale.h>
46
#endif
47
48
#ifdef G_OS_WIN32
49
#include <windows.h>
50
#endif
51
52
/* do not include <unistd.h> here, it may interfere with g_strsignal() */
53
54
#include "gstrfuncs.h"
55
56
#include "gprintf.h"
57
#include "gprintfint.h"
58
#include "glibintl.h"
59
60
/**
61
 * g_ascii_isalnum:
62
 * @c: any character
63
 *
64
 * Determines whether a character is alphanumeric.
65
 *
66
 * Unlike the standard C library `isalnum()` function, this only
67
 * recognizes standard ASCII letters and ignores the locale,
68
 * returning false for all non-ASCII characters. Also, unlike
69
 * the standard library function, this takes a `char`, not an `int`,
70
 * so don't call it on `EOF`, but no need to cast to `guchar` before
71
 * passing a possibly non-ASCII character in.
72
 *
73
 * Returns: true if @c is an ASCII alphanumeric character
74
 */
75
76
/**
77
 * g_ascii_isalpha:
78
 * @c: any character
79
 *
80
 * Determines whether a character is alphabetic (i.e. a letter).
81
 *
82
 * Unlike the standard C library `isalpha()` function, this only
83
 * recognizes standard ASCII letters and ignores the locale,
84
 * returning false for all non-ASCII characters. Also, unlike
85
 * the standard library function, this takes a `char`, not an `int`,
86
 * so don't call it on `EOF`, but no need to cast to `guchar` before
87
 * passing a possibly non-ASCII character in.
88
 *
89
 * Returns: true if @c is an ASCII alphabetic character
90
 */
91
92
/**
93
 * g_ascii_iscntrl:
94
 * @c: any character
95
 *
96
 * Determines whether a character is a control character.
97
 *
98
 * Unlike the standard C library `iscntrl()` function, this only
99
 * recognizes standard ASCII control characters and ignores the
100
 * locale, returning false for all non-ASCII characters. Also,
101
 * unlike the standard library function, this takes a `char`, not
102
 * an `int`, so don't call it on `EOF`, but no need to cast to `guchar`
103
 * before passing a possibly non-ASCII character in.
104
 *
105
 * Returns: true if @c is an ASCII control character
106
 */
107
108
/**
109
 * g_ascii_isdigit:
110
 * @c: any character
111
 *
112
 * Determines whether a character is digit (0-9).
113
 *
114
 * Unlike the standard C library `isdigit()` function, this takes
115
 * a `char`, not an `int`, so don't call it  on `EOF`, but no need to
116
 * cast to `guchar` before passing a possibly non-ASCII character in.
117
 *
118
 * Returns: true if @c is an ASCII digit
119
 */
120
121
/**
122
 * g_ascii_isgraph:
123
 * @c: any character
124
 *
125
 * Determines whether a character is a printing character and not a space.
126
 *
127
 * Unlike the standard C library `isgraph()` function, this only
128
 * recognizes standard ASCII characters and ignores the locale,
129
 * returning false for all non-ASCII characters. Also, unlike
130
 * the standard library function, this takes a `char`, not an `int`,
131
 * so don't call it on `EOF`, but no need to cast to `guchar` before
132
 * passing a possibly non-ASCII character in.
133
 *
134
 * Returns: true if @c is an ASCII printing character other than space
135
 */
136
137
/**
138
 * g_ascii_islower:
139
 * @c: any character
140
 *
141
 * Determines whether a character is an ASCII lower case letter.
142
 *
143
 * Unlike the standard C library `islower()` function, this only
144
 * recognizes standard ASCII letters and ignores the locale,
145
 * returning false for all non-ASCII characters. Also, unlike
146
 * the standard library function, this takes a `char`, not an `int`,
147
 * so don't call it on `EOF`, but no need to worry about casting
148
 * to `guchar` before passing a possibly non-ASCII character in.
149
 *
150
 * Returns: true if @c is an ASCII lower case letter
151
 */
152
153
/**
154
 * g_ascii_isprint:
155
 * @c: any character
156
 *
157
 * Determines whether a character is a printing character.
158
 *
159
 * Unlike the standard C library `isprint()` function, this only
160
 * recognizes standard ASCII characters and ignores the locale,
161
 * returning false for all non-ASCII characters. Also, unlike
162
 * the standard library function, this takes a `char`, not an `int`,
163
 * so don't call it on `EOF`, but no need to cast to `guchar` before
164
 * passing a possibly non-ASCII character in.
165
 *
166
 * Returns: true if @c is an ASCII printing character
167
 */
168
169
/**
170
 * g_ascii_ispunct:
171
 * @c: any character
172
 *
173
 * Determines whether a character is a punctuation character.
174
 *
175
 * Unlike the standard C library `ispunct()` function, this only
176
 * recognizes standard ASCII letters and ignores the locale,
177
 * returning false for all non-ASCII characters. Also, unlike
178
 * the standard library function, this takes a `char`, not an `int`,
179
 * so don't call it on `EOF`, but no need to cast to `guchar` before
180
 * passing a possibly non-ASCII character in.
181
 *
182
 * Returns: true if @c is an ASCII punctuation character
183
 */
184
185
/**
186
 * g_ascii_isspace:
187
 * @c: any character
188
 *
189
 * Determines whether a character is a white-space character.
190
 *
191
 * Unlike the standard C library `isspace()` function, this only
192
 * recognizes standard ASCII white-space and ignores the locale,
193
 * returning false for all non-ASCII characters. Also, unlike
194
 * the standard library function, this takes a `char`, not an `int`,
195
 * so don't call it on `EOF`, but no need to cast to `guchar` before
196
 * passing a possibly non-ASCII character in.
197
 *
198
 * Returns: true if @c is an ASCII white-space character
199
 */
200
201
/**
202
 * g_ascii_isupper:
203
 * @c: any character
204
 *
205
 * Determines whether a character is an ASCII upper case letter.
206
 *
207
 * Unlike the standard C library `isupper()` function, this only
208
 * recognizes standard ASCII letters and ignores the locale,
209
 * returning false for all non-ASCII characters. Also, unlike
210
 * the standard library function, this takes a `char`, not an `int`,
211
 * so don't call it on `EOF`, but no need to worry about casting
212
 * to `guchar` before passing a possibly non-ASCII character in.
213
 *
214
 * Returns: true if @c is an ASCII upper case letter
215
 */
216
217
/**
218
 * g_ascii_isxdigit:
219
 * @c: any character
220
 *
221
 * Determines whether a character is a hexadecimal-digit character.
222
 *
223
 * Unlike the standard C library `isxdigit()` function, this takes
224
 * a `char`, not an `int`, so don't call it on `EOF`, but no need to
225
 * cast to `guchar` before passing a possibly non-ASCII character in.
226
 *
227
 * Returns: true if @c is an ASCII hexadecimal-digit character
228
 */
229
230
/**
231
 * G_ASCII_DTOSTR_BUF_SIZE:
232
 *
233
 * A good size for a buffer to be passed into [func@GLib.ascii_dtostr].
234
 * It is guaranteed to be enough for all output of that function
235
 * on systems with 64bit IEEE-compatible doubles.
236
 *
237
 * The typical usage would be something like:
238
 * ```C
239
 * char buf[G_ASCII_DTOSTR_BUF_SIZE];
240
 *
241
 * fprintf (out, "value=%s\n", g_ascii_dtostr (buf, sizeof (buf), value));
242
 * ```
243
 */
244
245
/**
246
 * g_strstrip:
247
 * @string: a string to remove the leading and trailing whitespace from
248
 *
249
 * Removes leading and trailing whitespace from a string.
250
 *
251
 * See [func@GLib.strchomp] and [func@GLib.strchug].
252
 *
253
 * Returns: @string
254
 */
255
256
/**
257
 * G_STR_DELIMITERS:
258
 *
259
 * The standard delimiters, used in [func@GLib.strdelimit].
260
 */
261
262
static const guint16 ascii_table_data[256] = {
263
  0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
264
  0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004,
265
  0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
266
  0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
267
  0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
268
  0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
269
  0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459,
270
  0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
271
  0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253,
272
  0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
273
  0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
274
  0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
275
  0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073,
276
  0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
277
  0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
278
  0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004
279
  /* the upper 128 are all zeroes */
280
};
281
282
const guint16 * const g_ascii_table = ascii_table_data;
283
284
#if defined(HAVE_NEWLOCALE) && \
285
    defined(HAVE_USELOCALE)
286
#define USE_XLOCALE 1
287
#endif
288
289
#ifdef USE_XLOCALE
290
static locale_t
291
get_C_locale (void)
292
0
{
293
0
  static gsize initialized = FALSE;
294
0
  static locale_t C_locale = NULL;
295
296
0
  if (g_once_init_enter (&initialized))
297
0
    {
298
0
      C_locale = newlocale (LC_ALL_MASK, "C", NULL);
299
0
      g_once_init_leave (&initialized, TRUE);
300
0
    }
301
302
0
  return C_locale;
303
0
}
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
348
{
317
348
  gchar *new_str;
318
348
  gsize length;
319
320
348
  if G_LIKELY (str)
321
284
    {
322
284
      length = strlen (str) + 1;
323
284
      new_str = g_new (char, length);
324
284
      memcpy (new_str, str, length);
325
284
    }
326
64
  else
327
64
    new_str = NULL;
328
329
348
  return new_str;
330
348
}
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
34
{
382
34
  gpointer new_mem;
383
384
34
  if (mem && byte_size != 0)
385
34
    {
386
34
      new_mem = g_malloc (byte_size);
387
34
      memcpy (new_mem, mem, byte_size);
388
34
    }
389
0
  else
390
0
    new_mem = NULL;
391
392
34
  return new_mem;
393
34
}
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
0
{
415
0
  gchar *new_str;
416
417
0
  if (str)
418
0
    {
419
0
      g_return_val_if_fail (n < G_MAXSIZE, NULL);
420
421
0
      new_str = g_new (gchar, n + 1);
422
0
      strncpy (new_str, str, n);
423
0
      new_str[n] = '\0';
424
0
    }
425
0
  else
426
0
    new_str = NULL;
427
428
0
  return new_str;
429
0
}
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
156M
{
513
156M
  gchar *string = NULL;
514
515
156M
  g_vasprintf (&string, format, args);
516
517
156M
  return string;
518
156M
}
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
0
#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
0
#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
0
{
1185
0
#if defined(USE_XLOCALE) && defined(HAVE_STRTOULL_L)
1186
0
  locale_t c_locale = get_C_locale ();
1187
1188
0
  errno = 0;
1189
0
  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
0
}
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
0
{
1566
0
  gchar *result, *s;
1567
1568
0
  g_return_val_if_fail (str != NULL, NULL);
1569
1570
0
  if (len < 0)
1571
0
    result = g_strdup (str);
1572
0
  else
1573
0
    result = g_strndup (str, (gsize) len);
1574
1575
0
  for (s = result; *s; s++)
1576
0
    *s = g_ascii_tolower (*s);
1577
1578
0
  return result;
1579
0
}
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
0
{
1734
0
  return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1735
0
}
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
0
{
1835
0
  gint c1, c2;
1836
1837
0
  g_return_val_if_fail (s1 != NULL, 0);
1838
0
  g_return_val_if_fail (s2 != NULL, 0);
1839
1840
0
  while (*s1 && *s2)
1841
0
    {
1842
0
      c1 = (gint)(guchar) TOLOWER (*s1);
1843
0
      c2 = (gint)(guchar) TOLOWER (*s2);
1844
0
      if (c1 != c2)
1845
0
        return (c1 - c2);
1846
0
      s1++; s2++;
1847
0
    }
1848
1849
0
  return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1850
0
}
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
0
{
1879
0
  gint c1, c2;
1880
1881
0
  g_return_val_if_fail (s1 != NULL, 0);
1882
0
  g_return_val_if_fail (s2 != NULL, 0);
1883
1884
0
  while (n && *s1 && *s2)
1885
0
    {
1886
0
      n -= 1;
1887
0
      c1 = (gint)(guchar) TOLOWER (*s1);
1888
0
      c2 = (gint)(guchar) TOLOWER (*s2);
1889
0
      if (c1 != c2)
1890
0
        return (c1 - c2);
1891
0
      s1++; s2++;
1892
0
    }
1893
1894
0
  if (n)
1895
0
    return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1896
0
  else
1897
0
    return 0;
1898
0
}
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
0
{
2327
0
  guchar *start;
2328
2329
0
  g_return_val_if_fail (string != NULL, NULL);
2330
2331
0
  for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
2332
0
    ;
2333
2334
0
  memmove (string, start, strlen ((gchar *) start) + 1);
2335
2336
0
  return string;
2337
0
}
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
0
{
2358
0
  gsize len;
2359
2360
0
  g_return_val_if_fail (string != NULL, NULL);
2361
2362
0
  len = strlen (string);
2363
0
  while (len--)
2364
0
    {
2365
0
      if (g_ascii_isspace ((guchar) string[len]))
2366
0
        string[len] = '\0';
2367
0
      else
2368
0
        break;
2369
0
    }
2370
2371
0
  return string;
2372
0
}
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
  const 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: (array zero-terminated=1) (element-type guint8): a
2451
 *   nul-terminated byte array containing bytes that are used to
2452
 *   split the string; can be empty (just a nul byte), which will result in no
2453
 *   string splitting
2454
 * @max_tokens: the maximum number of tokens to split @string into.
2455
 *   If this is less than 1, the string is split completely
2456
 *
2457
 * Splits @string into a number of tokens not containing any of the
2458
 * bytes in @delimiters.
2459
 *
2460
 * A token is the (possibly empty) longest string that does not
2461
 * contain any of the bytes in @delimiters. Note that separators
2462
 * will only be single bytes from @delimiters. If @max_tokens is reached,
2463
 * the remainder is appended to the last token.
2464
 *
2465
 * For example, the result of `g_strsplit_set ("abc:def/ghi", ":/", -1)`
2466
 * is an array containing the three strings `"abc"`, `"def"`, and `"ghi"`.
2467
 *
2468
 * The result of `g_strsplit_set (":def/ghi:/x", ":/", -1)` is an array
2469
 * containing the five strings `""`, `"def"`, `"ghi"`, `""`, `"x"`.
2470
 *
2471
 * As a special case, the result of splitting the empty string `""` is an empty
2472
 * array, not an array containing a single string. The reason for this
2473
 * special case is that being able to represent an empty array is typically
2474
 * more useful than consistent handling of empty elements. If you do need
2475
 * to represent empty elements, you'll need to check for the empty string
2476
 * before calling `g_strsplit_set()`.
2477
 *
2478
 * Note that this function works on bytes not characters, so it can't be used
2479
 * to delimit UTF-8 strings for anything but ASCII characters.
2480
 *
2481
 * Returns: (transfer full): a newly-allocated array of strings. Use
2482
 *   [func@GLib.strfreev] to free it.
2483
 *
2484
 * Since: 2.4
2485
 **/
2486
gchar **
2487
g_strsplit_set (const gchar *string,
2488
                const gchar *delimiters,
2489
                gint         max_tokens)
2490
0
{
2491
0
  guint8 delim_table[256]; /* 1 = index is a separator; 0 otherwise */
2492
0
  GSList *tokens, *list;
2493
0
  gint n_tokens;
2494
0
  const gchar *s;
2495
0
  const gchar *current;
2496
0
  gchar *token;
2497
0
  gchar **result;
2498
2499
0
  g_return_val_if_fail (string != NULL, NULL);
2500
0
  g_return_val_if_fail (delimiters != NULL, NULL);
2501
2502
0
  if (max_tokens < 1)
2503
0
    max_tokens = G_MAXINT;
2504
2505
0
  if (*string == '\0')
2506
0
    {
2507
0
      result = g_new (char *, 1);
2508
0
      result[0] = NULL;
2509
0
      return result;
2510
0
    }
2511
2512
  /* Check if each character in @string is a separator, by indexing by the
2513
   * character value into the @delim_table, which has value 1 stored at an index
2514
   * if that index is a separator. */
2515
0
  memset (delim_table, FALSE, sizeof (delim_table));
2516
0
  for (s = delimiters; *s != '\0'; ++s)
2517
0
    delim_table[*(guchar *)s] = TRUE;
2518
2519
0
  tokens = NULL;
2520
0
  n_tokens = 0;
2521
2522
0
  s = current = string;
2523
0
  while (*s != '\0')
2524
0
    {
2525
0
      if (delim_table[*(guchar *)s] && n_tokens + 1 < max_tokens)
2526
0
        {
2527
0
          token = g_strndup (current, s - current);
2528
0
          tokens = g_slist_prepend (tokens, token);
2529
0
          ++n_tokens;
2530
2531
0
          current = s + 1;
2532
0
        }
2533
2534
0
      ++s;
2535
0
    }
2536
2537
0
  token = g_strndup (current, s - current);
2538
0
  tokens = g_slist_prepend (tokens, token);
2539
0
  ++n_tokens;
2540
2541
0
  result = g_new (gchar *, n_tokens + 1);
2542
2543
0
  result[n_tokens] = NULL;
2544
0
  for (list = tokens; list != NULL; list = list->next)
2545
0
    result[--n_tokens] = list->data;
2546
2547
0
  g_slist_free (tokens);
2548
2549
0
  return result;
2550
0
}
2551
2552
/**
2553
 * GStrv:
2554
 *
2555
 * A typedef alias for gchar**. This is mostly useful when used together with
2556
 * `g_auto()`.
2557
 */
2558
2559
/**
2560
 * g_strfreev:
2561
 * @str_array: (array zero-terminated=1) (nullable) (transfer full): an
2562
 *   array of strings to free
2563
 *
2564
 * Frees an array of strings, as well as each string it contains.
2565
 *
2566
 * If @str_array is `NULL`, this function simply returns.
2567
 */
2568
void
2569
g_strfreev (gchar **str_array)
2570
0
{
2571
0
  if (str_array)
2572
0
    {
2573
0
      gsize i;
2574
2575
0
      for (i = 0; str_array[i] != NULL; i++)
2576
0
        g_free (str_array[i]);
2577
2578
0
      g_free (str_array);
2579
0
    }
2580
0
}
2581
2582
/**
2583
 * g_strdupv:
2584
 * @str_array: (array zero-terminated=1) (nullable): an array of strings to copy
2585
 *
2586
 * Copies an array of strings. The copy is a deep copy; each string is also
2587
 * copied.
2588
 *
2589
 * If called on a `NULL` value, `g_strdupv()` simply returns `NULL`.
2590
 *
2591
 * Returns: (array zero-terminated=1) (nullable) (transfer full): a
2592
 *   newly-allocated array of strings. Use [func@GLib.strfreev] to free it.
2593
 */
2594
gchar**
2595
g_strdupv (gchar **str_array)
2596
0
{
2597
0
  if (str_array)
2598
0
    {
2599
0
      gsize i;
2600
0
      gchar **retval;
2601
2602
0
      i = 0;
2603
0
      while (str_array[i])
2604
0
        ++i;
2605
2606
0
      retval = g_new (gchar*, i + 1);
2607
2608
0
      i = 0;
2609
0
      while (str_array[i])
2610
0
        {
2611
0
          retval[i] = g_strdup (str_array[i]);
2612
0
          ++i;
2613
0
        }
2614
0
      retval[i] = NULL;
2615
2616
0
      return retval;
2617
0
    }
2618
0
  else
2619
0
    return NULL;
2620
0
}
2621
2622
/**
2623
 * g_strjoinv:
2624
 * @separator: (nullable): a string to insert between each of the strings
2625
 * @str_array: (array zero-terminated=1): an array of strings to join
2626
 *
2627
 * Joins an array of strings together to form one long string, with the
2628
 * optional @separator inserted between each of them.
2629
 *
2630
 * If @str_array has no items, the return value will be an
2631
 * empty string. If @str_array contains a single item, @separator will not
2632
 * appear in the resulting string.
2633
 *
2634
 * Returns: a newly-allocated string containing all of the strings joined
2635
 *   together, with @separator between them
2636
 */
2637
gchar*
2638
g_strjoinv (const gchar  *separator,
2639
            gchar       **str_array)
2640
0
{
2641
0
  gchar *string;
2642
0
  gchar *ptr;
2643
2644
0
  g_return_val_if_fail (str_array != NULL, NULL);
2645
2646
0
  if (separator == NULL)
2647
0
    separator = "";
2648
2649
0
  if (*str_array)
2650
0
    {
2651
0
      gsize i;
2652
0
      gsize len;
2653
0
      gsize separator_len;
2654
0
      gsize separators_len;
2655
2656
0
      separator_len = strlen (separator);
2657
      /* First part, getting length */
2658
0
      len = 1 + strlen (str_array[0]);
2659
0
      for (i = 1; str_array[i] != NULL; i++)
2660
0
        if (!g_size_checked_add (&len, len, strlen (str_array[i])))
2661
0
          g_error ("%s: overflow joining strings", G_STRLOC);
2662
2663
0
      if (!g_size_checked_mul (&separators_len, separator_len, (i - 1)) ||
2664
0
          !g_size_checked_add (&len, len, separators_len))
2665
0
        g_error ("%s: overflow joining strings", G_STRLOC);
2666
2667
      /* Second part, building string */
2668
0
      string = g_new (gchar, len);
2669
0
      ptr = g_stpcpy (string, *str_array);
2670
0
      for (i = 1; str_array[i] != NULL; i++)
2671
0
        {
2672
0
          ptr = g_stpcpy (ptr, separator);
2673
0
          ptr = g_stpcpy (ptr, str_array[i]);
2674
0
        }
2675
0
      }
2676
0
  else
2677
0
    string = g_strdup ("");
2678
2679
0
  return string;
2680
0
}
2681
2682
/**
2683
 * g_strjoin:
2684
 * @separator: (nullable): a string to insert between each of the strings
2685
 * @...: a `NULL`-terminated list of strings to join
2686
 *
2687
 * Joins a number of strings together to form one long string, with the
2688
 * optional @separator inserted between each of them.
2689
 *
2690
 * Returns: a newly-allocated string containing all of the strings joined
2691
 *   together, with @separator between them
2692
 */
2693
gchar*
2694
g_strjoin (const gchar *separator,
2695
           ...)
2696
0
{
2697
0
  gchar *string, *s;
2698
0
  va_list args;
2699
0
  gsize len;
2700
0
  gsize separator_len;
2701
0
  gchar *ptr;
2702
2703
0
  if (separator == NULL)
2704
0
    separator = "";
2705
2706
0
  separator_len = strlen (separator);
2707
2708
0
  va_start (args, separator);
2709
2710
0
  s = va_arg (args, gchar*);
2711
2712
0
  if (s)
2713
0
    {
2714
      /* First part, getting length */
2715
0
      len = 1 + strlen (s);
2716
2717
0
      s = va_arg (args, gchar*);
2718
0
      while (s)
2719
0
        {
2720
0
          if (!g_size_checked_add (&len, len, separator_len) ||
2721
0
              !g_size_checked_add (&len, len, strlen (s)))
2722
0
            g_error ("%s: overflow joining strings", G_STRLOC);
2723
0
          s = va_arg (args, gchar*);
2724
0
        }
2725
0
      va_end (args);
2726
2727
      /* Second part, building string */
2728
0
      string = g_new (gchar, len);
2729
2730
0
      va_start (args, separator);
2731
2732
0
      s = va_arg (args, gchar*);
2733
0
      ptr = g_stpcpy (string, s);
2734
2735
0
      s = va_arg (args, gchar*);
2736
0
      while (s)
2737
0
        {
2738
0
          ptr = g_stpcpy (ptr, separator);
2739
0
          ptr = g_stpcpy (ptr, s);
2740
0
          s = va_arg (args, gchar*);
2741
0
        }
2742
0
    }
2743
0
  else
2744
0
    string = g_strdup ("");
2745
2746
0
  va_end (args);
2747
2748
0
  return string;
2749
0
}
2750
2751
2752
/**
2753
 * g_strstr_len:
2754
 * @haystack: a string to search in
2755
 * @haystack_len: the maximum length of @haystack in bytes, or `-1` to
2756
 *   search it entirely
2757
 * @needle: the string to search for
2758
 *
2759
 * Searches the string @haystack for the first occurrence
2760
 * of the string @needle, limiting the length of the search
2761
 * to @haystack_len or a nul terminator byte (whichever is reached first).
2762
 *
2763
 * A length of `-1` can be used to mean “search the entire string”, like
2764
 * `strstr()`.
2765
 *
2766
 * The fact that this function returns `gchar *` rather than `const gchar *` is
2767
 * a historical artifact.
2768
 *
2769
 * Returns: (transfer none) (nullable): a pointer to the found occurrence, or
2770
 *    `NULL` if not found
2771
 */
2772
gchar *
2773
g_strstr_len (const gchar *haystack,
2774
              gssize       haystack_len,
2775
              const gchar *needle)
2776
0
{
2777
0
  g_return_val_if_fail (haystack != NULL, NULL);
2778
0
  g_return_val_if_fail (needle != NULL, NULL);
2779
2780
0
  if (haystack_len < 0)
2781
0
    return (gchar *)strstr (haystack, needle);
2782
0
  else
2783
0
    {
2784
0
      const gchar *p = haystack;
2785
0
      gsize needle_len = strlen (needle);
2786
0
      gsize haystack_len_unsigned = haystack_len;
2787
0
      const gchar *end;
2788
0
      gsize i;
2789
2790
0
      if (needle_len == 0)
2791
0
        return (gchar *)haystack;
2792
2793
0
      if (haystack_len_unsigned < needle_len)
2794
0
        return NULL;
2795
2796
0
      end = haystack + haystack_len - needle_len;
2797
2798
0
      while (p <= end && *p)
2799
0
        {
2800
0
          for (i = 0; i < needle_len; i++)
2801
0
            if (p[i] != needle[i])
2802
0
              goto next;
2803
2804
0
          return (gchar *)p;
2805
2806
0
        next:
2807
0
          p++;
2808
0
        }
2809
2810
0
      return NULL;
2811
0
    }
2812
0
}
2813
2814
/**
2815
 * g_strrstr:
2816
 * @haystack: a string to search in
2817
 * @needle: the string to search for
2818
 *
2819
 * Searches the string @haystack for the last occurrence
2820
 * of the string @needle.
2821
 *
2822
 * The fact that this function returns `gchar *` rather than `const gchar *` is
2823
 * a historical artifact.
2824
 *
2825
 * Returns: (transfer none) (nullable): a pointer to the found occurrence, or
2826
 *    `NULL` if not found
2827
 */
2828
gchar *
2829
g_strrstr (const gchar *haystack,
2830
           const gchar *needle)
2831
0
{
2832
0
  gsize i;
2833
0
  gsize needle_len;
2834
0
  gsize haystack_len;
2835
0
  const gchar *p;
2836
2837
0
  g_return_val_if_fail (haystack != NULL, NULL);
2838
0
  g_return_val_if_fail (needle != NULL, NULL);
2839
2840
0
  needle_len = strlen (needle);
2841
0
  haystack_len = strlen (haystack);
2842
2843
0
  if (needle_len == 0)
2844
0
    return (gchar *)haystack;
2845
2846
0
  if (haystack_len < needle_len)
2847
0
    return NULL;
2848
2849
0
  p = haystack + haystack_len - needle_len;
2850
2851
0
  while (p >= haystack)
2852
0
    {
2853
0
      for (i = 0; i < needle_len; i++)
2854
0
        if (p[i] != needle[i])
2855
0
          goto next;
2856
2857
0
      return (gchar *)p;
2858
2859
0
    next:
2860
0
      p--;
2861
0
    }
2862
2863
0
  return NULL;
2864
0
}
2865
2866
/**
2867
 * g_strrstr_len:
2868
 * @haystack: a string to search in
2869
 * @haystack_len: the maximum length of @haystack in bytes. A length of `-1`
2870
 *   can be used to mean "search the entire string", like [func@GLib.strrstr]
2871
 * @needle: the string to search for
2872
 *
2873
 * Searches the string @haystack for the last occurrence
2874
 * of the string @needle, limiting the length of the search
2875
 * to @haystack_len.
2876
 *
2877
 * The fact that this function returns `gchar *` rather than `const gchar *` is
2878
 * a historical artifact.
2879
 *
2880
 * Returns: (transfer none) (nullable): a pointer to the found occurrence, or
2881
 *    `NULL` if not found
2882
 */
2883
gchar *
2884
g_strrstr_len (const gchar *haystack,
2885
               gssize        haystack_len,
2886
               const gchar *needle)
2887
0
{
2888
0
  g_return_val_if_fail (haystack != NULL, NULL);
2889
0
  g_return_val_if_fail (needle != NULL, NULL);
2890
2891
0
  if (haystack_len < 0)
2892
0
    return g_strrstr (haystack, needle);
2893
0
  else
2894
0
    {
2895
0
      gsize needle_len = strlen (needle);
2896
0
      const gchar *haystack_max = haystack + haystack_len;
2897
0
      const gchar *p = haystack;
2898
0
      gsize i;
2899
2900
0
      while (p < haystack_max && *p)
2901
0
        p++;
2902
2903
0
      if (p < haystack + needle_len)
2904
0
        return NULL;
2905
2906
0
      p -= needle_len;
2907
2908
0
      while (p >= haystack)
2909
0
        {
2910
0
          for (i = 0; i < needle_len; i++)
2911
0
            if (p[i] != needle[i])
2912
0
              goto next;
2913
2914
0
          return (gchar *)p;
2915
2916
0
        next:
2917
0
          p--;
2918
0
        }
2919
2920
0
      return NULL;
2921
0
    }
2922
0
}
2923
2924
2925
/**
2926
 * g_str_has_suffix:
2927
 * @str: a string to look in
2928
 * @suffix: the suffix to look for
2929
 *
2930
 * Looks whether a string ends with @suffix.
2931
 *
2932
 * Returns: true if @str ends with @suffix, false otherwise
2933
 *
2934
 * Since: 2.2
2935
 */
2936
gboolean (g_str_has_suffix) (const gchar *str,
2937
                             const gchar *suffix)
2938
0
{
2939
0
  gsize str_len;
2940
0
  gsize suffix_len;
2941
2942
0
  g_return_val_if_fail (str != NULL, FALSE);
2943
0
  g_return_val_if_fail (suffix != NULL, FALSE);
2944
2945
0
  str_len = strlen (str);
2946
0
  suffix_len = strlen (suffix);
2947
2948
0
  if (str_len < suffix_len)
2949
0
    return FALSE;
2950
2951
0
  return strcmp (str + str_len - suffix_len, suffix) == 0;
2952
0
}
2953
2954
/**
2955
 * g_str_has_prefix:
2956
 * @str: a string to look in
2957
 * @prefix: the prefix to look for
2958
 *
2959
 * Looks whether the string @str begins with @prefix.
2960
 *
2961
 * Returns: true if @str begins with @prefix, false otherwise
2962
 *
2963
 * Since: 2.2
2964
 */
2965
gboolean (g_str_has_prefix) (const gchar *str,
2966
                             const gchar *prefix)
2967
0
{
2968
0
  g_return_val_if_fail (str != NULL, FALSE);
2969
0
  g_return_val_if_fail (prefix != NULL, FALSE);
2970
2971
0
  return strncmp (str, prefix, strlen (prefix)) == 0;
2972
0
}
2973
2974
/**
2975
 * g_strv_length:
2976
 * @str_array: (array zero-terminated=1): an array of strings
2977
 *
2978
 * Returns the length of an array of strings. @str_array must not be `NULL`.
2979
 *
2980
 * Returns: length of @str_array
2981
 *
2982
 * Since: 2.6
2983
 */
2984
guint
2985
g_strv_length (gchar **str_array)
2986
0
{
2987
0
  guint i = 0;
2988
2989
0
  g_return_val_if_fail (str_array != NULL, 0);
2990
2991
0
  while (str_array[i])
2992
0
    ++i;
2993
2994
0
  return i;
2995
0
}
2996
2997
static void
2998
index_add_folded (GPtrArray   *array,
2999
                  const gchar *start,
3000
                  const gchar *end)
3001
0
{
3002
0
  gchar *normal;
3003
3004
0
  normal = g_utf8_normalize (start, end - start, G_NORMALIZE_ALL_COMPOSE);
3005
3006
  /* TODO: Invent time machine.  Converse with Mustafa Ataturk... */
3007
0
  if (strstr (normal, "ı") || strstr (normal, "İ"))
3008
0
    {
3009
0
      gchar *s = normal;
3010
0
      GString *tmp;
3011
3012
0
      tmp = g_string_new (NULL);
3013
3014
0
      while (*s)
3015
0
        {
3016
0
          gchar *i, *I, *e;
3017
3018
0
          i = strstr (s, "ı");
3019
0
          I = strstr (s, "İ");
3020
3021
0
          if (!i && !I)
3022
0
            break;
3023
0
          else if (i && !I)
3024
0
            e = i;
3025
0
          else if (I && !i)
3026
0
            e = I;
3027
0
          else if (i < I)
3028
0
            e = i;
3029
0
          else
3030
0
            e = I;
3031
3032
0
          g_string_append_len (tmp, s, e - s);
3033
0
          g_string_append_c (tmp, 'i');
3034
0
          s = g_utf8_next_char (e);
3035
0
        }
3036
3037
0
      g_string_append (tmp, s);
3038
0
      g_free (normal);
3039
0
      normal = g_string_free (tmp, FALSE);
3040
0
    }
3041
3042
0
  g_ptr_array_add (array, g_utf8_casefold (normal, -1));
3043
0
  g_free (normal);
3044
0
}
3045
3046
static gchar **
3047
split_words (const gchar *value)
3048
0
{
3049
0
  const gchar *start = NULL;
3050
0
  GPtrArray *result;
3051
0
  const gchar *s;
3052
3053
0
  result = g_ptr_array_new ();
3054
3055
0
  for (s = value; *s; s = g_utf8_next_char (s))
3056
0
    {
3057
0
      gunichar c = g_utf8_get_char (s);
3058
3059
0
      if (start == NULL)
3060
0
        {
3061
0
          if (g_unichar_isalnum (c) || g_unichar_ismark (c))
3062
0
            start = s;
3063
0
        }
3064
0
      else
3065
0
        {
3066
0
          if (!g_unichar_isalnum (c) && !g_unichar_ismark (c))
3067
0
            {
3068
0
              index_add_folded (result, start, s);
3069
0
              start = NULL;
3070
0
            }
3071
0
        }
3072
0
    }
3073
3074
0
  if (start)
3075
0
    index_add_folded (result, start, s);
3076
3077
0
  g_ptr_array_add (result, NULL);
3078
3079
0
  return (gchar **) g_ptr_array_free (result, FALSE);
3080
0
}
3081
3082
/**
3083
 * g_str_tokenize_and_fold:
3084
 * @string: a string to tokenize
3085
 * @translit_locale: (nullable): the language code (like 'de' or
3086
 *   'en_GB') from which @string originates
3087
 * @ascii_alternates: (out) (optional) (transfer full) (array zero-terminated=1):
3088
 *   a return location for ASCII alternates
3089
 *
3090
 * Tokenizes @string and performs folding on each token.
3091
 *
3092
 * A token is a non-empty sequence of alphanumeric characters in the
3093
 * source string, separated by non-alphanumeric characters.  An
3094
 * "alphanumeric" character for this purpose is one that matches
3095
 * [func@GLib.unichar_isalnum] or [func@GLib.unichar_ismark].
3096
 *
3097
 * Each token is then (Unicode) normalised and case-folded.  If
3098
 * @ascii_alternates is non-`NULL` and some of the returned tokens
3099
 * contain non-ASCII characters, ASCII alternatives will be generated.
3100
 *
3101
 * The number of ASCII alternatives that are generated and the method
3102
 * for doing so is unspecified, but @translit_locale (if specified) may
3103
 * improve the transliteration if the language of the source string is
3104
 * known.
3105
 *
3106
 * Returns: (transfer full) (array zero-terminated=1): the folded tokens
3107
 *
3108
 * Since: 2.40
3109
 **/
3110
gchar **
3111
g_str_tokenize_and_fold (const gchar   *string,
3112
                         const gchar   *translit_locale,
3113
                         gchar       ***ascii_alternates)
3114
0
{
3115
0
  gchar **result;
3116
3117
0
  g_return_val_if_fail (string != NULL, NULL);
3118
3119
0
  if (ascii_alternates && g_str_is_ascii (string))
3120
0
    {
3121
0
      *ascii_alternates = g_new0 (gchar *, 0 + 1);
3122
0
      ascii_alternates = NULL;
3123
0
    }
3124
3125
0
  result = split_words (string);
3126
3127
0
  if (ascii_alternates)
3128
0
    {
3129
0
      gint i, j, n;
3130
3131
0
      n = g_strv_length (result);
3132
0
      *ascii_alternates = g_new (gchar *, n + 1);
3133
0
      j = 0;
3134
3135
0
      for (i = 0; i < n; i++)
3136
0
        {
3137
0
          if (!g_str_is_ascii (result[i]))
3138
0
            {
3139
0
              gchar *composed;
3140
0
              gchar *ascii;
3141
0
              gint k;
3142
3143
0
              composed = g_utf8_normalize (result[i], -1, G_NORMALIZE_ALL_COMPOSE);
3144
3145
0
              ascii = g_str_to_ascii (composed, translit_locale);
3146
3147
              /* Only accept strings that are now entirely alnums */
3148
0
              for (k = 0; ascii[k]; k++)
3149
0
                if (!g_ascii_isalnum (ascii[k]))
3150
0
                  break;
3151
3152
0
              if (ascii[k] == '\0')
3153
                /* Made it to the end... */
3154
0
                (*ascii_alternates)[j++] = ascii;
3155
0
              else
3156
0
                g_free (ascii);
3157
3158
0
              g_free (composed);
3159
0
            }
3160
0
        }
3161
3162
0
      (*ascii_alternates)[j] = NULL;
3163
0
    }
3164
3165
0
  return result;
3166
0
}
3167
3168
/**
3169
 * g_str_match_string:
3170
 * @search_term: the search term from the user
3171
 * @potential_hit: the text that may be a hit
3172
 * @accept_alternates: if true, ASCII alternates are accepted
3173
 *
3174
 * Checks if a search conducted for @search_term should match
3175
 * @potential_hit.
3176
 *
3177
 * This function calls [func@GLib.str_tokenize_and_fold] on both
3178
 * @search_term and @potential_hit. ASCII alternates are never taken
3179
 * for @search_term but will be taken for @potential_hit according to
3180
 * the value of @accept_alternates.
3181
 *
3182
 * A hit occurs when each folded token in @search_term is a prefix of a
3183
 * folded token from @potential_hit.
3184
 *
3185
 * Depending on how you're performing the search, it will typically be
3186
 * faster to call `g_str_tokenize_and_fold()` on each string in
3187
 * your corpus and build an index on the returned folded tokens, then
3188
 * call `g_str_tokenize_and_fold()` on the search term and
3189
 * perform lookups into that index.
3190
 *
3191
 * As some examples, searching for ‘fred’ would match the potential hit
3192
 * ‘Smith, Fred’ and also ‘Frédéric’.  Searching for ‘Fréd’ would match
3193
 * ‘Frédéric’ but not ‘Frederic’ (due to the one-directional nature of
3194
 * accent matching).  Searching ‘fo’ would match ‘Foo’ and ‘Bar Foo
3195
 * Baz’, but not ‘SFO’ (because no word has ‘fo’ as a prefix).
3196
 *
3197
 * Returns: true if @potential_hit is a hit
3198
 *
3199
 * Since: 2.40
3200
 **/
3201
gboolean
3202
g_str_match_string (const gchar *search_term,
3203
                    const gchar *potential_hit,
3204
                    gboolean     accept_alternates)
3205
0
{
3206
0
  gchar **alternates = NULL;
3207
0
  gchar **term_tokens;
3208
0
  gchar **hit_tokens;
3209
0
  gboolean matched;
3210
0
  gint i, j;
3211
3212
0
  g_return_val_if_fail (search_term != NULL, FALSE);
3213
0
  g_return_val_if_fail (potential_hit != NULL, FALSE);
3214
3215
0
  term_tokens = g_str_tokenize_and_fold (search_term, NULL, NULL);
3216
0
  hit_tokens = g_str_tokenize_and_fold (potential_hit, NULL, accept_alternates ? &alternates : NULL);
3217
3218
0
  matched = TRUE;
3219
3220
0
  for (i = 0; term_tokens[i]; i++)
3221
0
    {
3222
0
      for (j = 0; hit_tokens[j]; j++)
3223
0
        if (g_str_has_prefix (hit_tokens[j], term_tokens[i]))
3224
0
          goto one_matched;
3225
3226
0
      if (accept_alternates)
3227
0
        for (j = 0; alternates[j]; j++)
3228
0
          if (g_str_has_prefix (alternates[j], term_tokens[i]))
3229
0
            goto one_matched;
3230
3231
0
      matched = FALSE;
3232
0
      break;
3233
3234
0
one_matched:
3235
0
      continue;
3236
0
    }
3237
3238
0
  g_strfreev (term_tokens);
3239
0
  g_strfreev (hit_tokens);
3240
0
  g_strfreev (alternates);
3241
3242
0
  return matched;
3243
0
}
3244
3245
/**
3246
 * g_strv_contains:
3247
 * @strv: (array zero-terminated=1): an array of strings to search in
3248
 * @str: the string to search for
3249
 *
3250
 * Checks if an array of strings contains the string @str according to
3251
 * [func@GLib.str_equal]. @strv must not be `NULL`.
3252
 *
3253
 * Returns: true if @str is an element of @strv
3254
 *
3255
 * Since: 2.44
3256
 */
3257
gboolean
3258
g_strv_contains (const gchar * const *strv,
3259
                 const gchar         *str)
3260
0
{
3261
0
  g_return_val_if_fail (strv != NULL, FALSE);
3262
0
  g_return_val_if_fail (str != NULL, FALSE);
3263
3264
0
  for (; *strv != NULL; strv++)
3265
0
    {
3266
0
      if (g_str_equal (str, *strv))
3267
0
        return TRUE;
3268
0
    }
3269
3270
0
  return FALSE;
3271
0
}
3272
3273
/**
3274
 * g_strv_equal:
3275
 * @strv1: (array zero-terminated=1): an array of strings to compare to @strv2
3276
 * @strv2: (array zero-terminated=1): an array of strings to compare to @strv1
3277
 *
3278
 * Checks if two arrays of strings contain exactly the same elements in
3279
 * exactly the same order.
3280
 *
3281
 * Elements are compared using [func@GLib.str_equal]. To match independently
3282
 * of order, sort the arrays first (using [func@GLib.qsort_with_data]
3283
 * or similar).
3284
 *
3285
 * Two empty arrays are considered equal. Neither @strv1 nor @strv2 may be
3286
 * `NULL`.
3287
 *
3288
 * Returns: true if @strv1 and @strv2 are equal
3289
 * Since: 2.60
3290
 */
3291
gboolean
3292
g_strv_equal (const gchar * const *strv1,
3293
              const gchar * const *strv2)
3294
0
{
3295
0
  g_return_val_if_fail (strv1 != NULL, FALSE);
3296
0
  g_return_val_if_fail (strv2 != NULL, FALSE);
3297
3298
0
  if (strv1 == strv2)
3299
0
    return TRUE;
3300
3301
0
  for (; *strv1 != NULL && *strv2 != NULL; strv1++, strv2++)
3302
0
    {
3303
0
      if (!g_str_equal (*strv1, *strv2))
3304
0
        return FALSE;
3305
0
    }
3306
3307
0
  return (*strv1 == NULL && *strv2 == NULL);
3308
0
}
3309
3310
static gboolean
3311
str_has_sign (const gchar *str)
3312
0
{
3313
0
  return str[0] == '-' || str[0] == '+';
3314
0
}
3315
3316
static gboolean
3317
str_has_hex_prefix (const gchar *str)
3318
0
{
3319
0
  return str[0] == '0' && g_ascii_tolower (str[1]) == 'x';
3320
0
}
3321
3322
/**
3323
 * g_ascii_string_to_signed:
3324
 * @str: a string to convert
3325
 * @base: base of a parsed number
3326
 * @min: a lower bound (inclusive)
3327
 * @max: an upper bound (inclusive)
3328
 * @out_num: (out) (optional): a return location for a number
3329
 * @error: a return location for #GError
3330
 *
3331
 * A convenience function for converting a string to a signed number.
3332
 *
3333
 * This function assumes that @str contains only a number of the given
3334
 * @base that is within inclusive bounds limited by @min and @max. If
3335
 * this is true, then the converted number is stored in @out_num. An
3336
 * empty string is not a valid input. A string with leading or
3337
 * trailing whitespace is also an invalid input.
3338
 *
3339
 * @base can be between 2 and 36 inclusive. Hexadecimal numbers must
3340
 * not be prefixed with "0x" or "0X". Such a problem does not exist
3341
 * for octal numbers, since they were usually prefixed with a zero
3342
 * which does not change the value of the parsed number.
3343
 *
3344
 * Parsing failures result in an error with the `G_NUMBER_PARSER_ERROR`
3345
 * domain. If the input is invalid, the error code will be
3346
 * [error@GLib.NumberParserError.INVALID]. If the parsed number is out of
3347
 * bounds - [error@GLib.NumberParserError.OUT_OF_BOUNDS].
3348
 *
3349
 * See [func@GLib.ascii_strtoll] if you have more complex needs such as
3350
 * parsing a string which starts with a number, but then has other
3351
 * characters.
3352
 *
3353
 * Returns: true if @str was a number, false otherwise
3354
 *
3355
 * Since: 2.54
3356
 */
3357
gboolean
3358
g_ascii_string_to_signed (const gchar  *str,
3359
                          guint         base,
3360
                          gint64        min,
3361
                          gint64        max,
3362
                          gint64       *out_num,
3363
                          GError      **error)
3364
0
{
3365
0
  gint64 number;
3366
0
  const gchar *end_ptr = NULL;
3367
0
  gint saved_errno = 0;
3368
3369
0
  g_return_val_if_fail (str != NULL, FALSE);
3370
0
  g_return_val_if_fail (base >= 2 && base <= 36, FALSE);
3371
0
  g_return_val_if_fail (min <= max, FALSE);
3372
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
3373
3374
0
  if (str[0] == '\0')
3375
0
    {
3376
0
      g_set_error_literal (error,
3377
0
                           G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_INVALID,
3378
0
                           _("Empty string is not a number"));
3379
0
      return FALSE;
3380
0
    }
3381
3382
0
  errno = 0;
3383
0
  number = g_ascii_strtoll (str, (gchar **)&end_ptr, base);
3384
0
  saved_errno = errno;
3385
3386
0
  if (/* We do not allow leading whitespace, but g_ascii_strtoll
3387
       * accepts it and just skips it, so we need to check for it
3388
       * ourselves.
3389
       */
3390
0
      g_ascii_isspace (str[0]) ||
3391
      /* We don't support hexadecimal numbers prefixed with 0x or
3392
       * 0X.
3393
       */
3394
0
      (base == 16 &&
3395
0
       (str_has_sign (str) ? str_has_hex_prefix (str + 1) : str_has_hex_prefix (str))) ||
3396
0
      (saved_errno != 0 && saved_errno != ERANGE) ||
3397
0
      end_ptr == NULL ||
3398
0
      *end_ptr != '\0')
3399
0
    {
3400
0
      g_set_error (error,
3401
0
                   G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_INVALID,
3402
0
                   _("“%s” is not a signed number"), str);
3403
0
      return FALSE;
3404
0
    }
3405
0
  if (saved_errno == ERANGE || number < min || number > max)
3406
0
    {
3407
0
      gchar *min_str = g_strdup_printf ("%" G_GINT64_FORMAT, min);
3408
0
      gchar *max_str = g_strdup_printf ("%" G_GINT64_FORMAT, max);
3409
3410
0
      g_set_error (error,
3411
0
                   G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_OUT_OF_BOUNDS,
3412
0
                   _("Number “%s” is out of bounds [%s, %s]"),
3413
0
                   str, min_str, max_str);
3414
0
      g_free (min_str);
3415
0
      g_free (max_str);
3416
0
      return FALSE;
3417
0
    }
3418
0
  if (out_num != NULL)
3419
0
    *out_num = number;
3420
0
  return TRUE;
3421
0
}
3422
3423
/**
3424
 * g_ascii_string_to_unsigned:
3425
 * @str: a string
3426
 * @base: base of a parsed number
3427
 * @min: a lower bound (inclusive)
3428
 * @max: an upper bound (inclusive)
3429
 * @out_num: (out) (optional): a return location for a number
3430
 * @error: a return location for #GError
3431
 *
3432
 * A convenience function for converting a string to an unsigned number.
3433
 *
3434
 * This function assumes that @str contains only a number of the given
3435
 * @base that is within inclusive bounds limited by @min and @max. If
3436
 * this is true, then the converted number is stored in @out_num. An
3437
 * empty string is not a valid input. A string with leading or
3438
 * trailing whitespace is also an invalid input. A string with a leading sign
3439
 * (`-` or `+`) is not a valid input for the unsigned parser.
3440
 *
3441
 * @base can be between 2 and 36 inclusive. Hexadecimal numbers must
3442
 * not be prefixed with "0x" or "0X". Such a problem does not exist
3443
 * for octal numbers, since they were usually prefixed with a zero
3444
 * which does not change the value of the parsed number.
3445
 *
3446
 * Parsing failures result in an error with the `G_NUMBER_PARSER_ERROR`
3447
 * domain. If the input is invalid, the error code will be
3448
 * [error@GLib.NumberParserError.INVALID]. If the parsed number is out of
3449
 * bounds - [error@GLib.NumberParserError.OUT_OF_BOUNDS].
3450
 *
3451
 * See [func@GLib.ascii_strtoull] if you have more complex needs such as
3452
 * parsing a string which starts with a number, but then has other
3453
 * characters.
3454
 *
3455
 * Returns: true if @str was a number, false otherwise
3456
 *
3457
 * Since: 2.54
3458
 */
3459
gboolean
3460
g_ascii_string_to_unsigned (const gchar  *str,
3461
                            guint         base,
3462
                            guint64       min,
3463
                            guint64       max,
3464
                            guint64      *out_num,
3465
                            GError      **error)
3466
0
{
3467
0
  guint64 number;
3468
0
  const gchar *end_ptr = NULL;
3469
0
  gint saved_errno = 0;
3470
3471
0
  g_return_val_if_fail (str != NULL, FALSE);
3472
0
  g_return_val_if_fail (base >= 2 && base <= 36, FALSE);
3473
0
  g_return_val_if_fail (min <= max, FALSE);
3474
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
3475
3476
0
  if (str[0] == '\0')
3477
0
    {
3478
0
      g_set_error_literal (error,
3479
0
                           G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_INVALID,
3480
0
                           _("Empty string is not a number"));
3481
0
      return FALSE;
3482
0
    }
3483
3484
0
  errno = 0;
3485
0
  number = g_ascii_strtoull (str, (gchar **)&end_ptr, base);
3486
0
  saved_errno = errno;
3487
3488
0
  if (/* We do not allow leading whitespace, but g_ascii_strtoull
3489
       * accepts it and just skips it, so we need to check for it
3490
       * ourselves.
3491
       */
3492
0
      g_ascii_isspace (str[0]) ||
3493
      /* Unsigned number should have no sign.
3494
       */
3495
0
      str_has_sign (str) ||
3496
      /* We don't support hexadecimal numbers prefixed with 0x or
3497
       * 0X.
3498
       */
3499
0
      (base == 16 && str_has_hex_prefix (str)) ||
3500
0
      (saved_errno != 0 && saved_errno != ERANGE) ||
3501
0
      end_ptr == NULL ||
3502
0
      *end_ptr != '\0')
3503
0
    {
3504
0
      g_set_error (error,
3505
0
                   G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_INVALID,
3506
0
                   _("“%s” is not an unsigned number"), str);
3507
0
      return FALSE;
3508
0
    }
3509
0
  if (saved_errno == ERANGE || number < min || number > max)
3510
0
    {
3511
0
      gchar *min_str = g_strdup_printf ("%" G_GUINT64_FORMAT, min);
3512
0
      gchar *max_str = g_strdup_printf ("%" G_GUINT64_FORMAT, max);
3513
3514
0
      g_set_error (error,
3515
0
                   G_NUMBER_PARSER_ERROR, G_NUMBER_PARSER_ERROR_OUT_OF_BOUNDS,
3516
0
                   _("Number “%s” is out of bounds [%s, %s]"),
3517
0
                   str, min_str, max_str);
3518
0
      g_free (min_str);
3519
0
      g_free (max_str);
3520
0
      return FALSE;
3521
0
    }
3522
0
  if (out_num != NULL)
3523
0
    *out_num = number;
3524
0
  return TRUE;
3525
0
}
3526
3527
G_DEFINE_QUARK (g-number-parser-error-quark, g_number_parser_error)