Coverage Report

Created: 2025-12-31 06:46

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