Coverage Report

Created: 2026-08-25 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gstreamer/subprojects/glib-2.86.3/glib/gutf8.c
Line
Count
Source
1
/* gutf8.c - Operations on UTF-8 strings.
2
 *
3
 * Copyright (C) 1999 Tom Tromey
4
 * Copyright (C) 2000, 2015-2022 Red Hat, Inc.
5
 * Copyright (C) 2022-2023 David Rheinsberg
6
 *
7
 * SPDX-License-Identifier: LGPL-2.1-or-later
8
 *
9
 * This library is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU Lesser General Public
11
 * License as published by the Free Software Foundation; either
12
 * version 2.1 of the License, or (at your option) any later version.
13
 *
14
 * This library is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Lesser General Public
20
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21
 */
22
23
#include "config.h"
24
25
#include <stdlib.h>
26
#ifdef HAVE_CODESET
27
#include <langinfo.h>
28
#endif
29
#include <string.h>
30
#include <stdbool.h>
31
32
#ifdef G_PLATFORM_WIN32
33
#include <stdio.h>
34
#include <windows.h>
35
#endif
36
37
#include "gconvert.h"
38
#include "ghash.h"
39
#include "gstrfuncs.h"
40
#include "gtestutils.h"
41
#include "gtypes.h"
42
#include "gthread.h"
43
#include "glibintl.h"
44
#include "gvalgrind.h"
45
#include "gunicodeprivate.h"
46
47
#define UTF8_COMPUTE(Char, Mask, Len)               \
48
34.0k
  if (Char < 128)                   \
49
34.0k
    {                       \
50
0
      Len = 1;                      \
51
0
      Mask = 0x7f;                    \
52
0
    }                        \
53
34.0k
  else if ((Char & 0xe0) == 0xc0)               \
54
34.0k
    {                       \
55
34.0k
      Len = 2;                      \
56
34.0k
      Mask = 0x1f;                    \
57
34.0k
    }                        \
58
34.0k
  else if ((Char & 0xf0) == 0xe0)               \
59
0
    {                       \
60
0
      Len = 3;                      \
61
0
      Mask = 0x0f;                    \
62
0
    }                        \
63
0
  else if ((Char & 0xf8) == 0xf0)               \
64
0
    {                       \
65
0
      Len = 4;                      \
66
0
      Mask = 0x07;                    \
67
0
    }                        \
68
0
  else if ((Char & 0xfc) == 0xf8)               \
69
0
    {                       \
70
0
      Len = 5;                      \
71
0
      Mask = 0x03;                    \
72
0
    }                        \
73
0
  else if ((Char & 0xfe) == 0xfc)               \
74
0
    {                       \
75
0
      Len = 6;                      \
76
0
      Mask = 0x01;                    \
77
0
    }                        \
78
0
  else                        \
79
0
    Len = -1;
80
81
#define UTF8_LENGTH(Char)              \
82
93.3k
  ((Char) < 0x80 ? 1 :                 \
83
93.3k
   ((Char) < 0x800 ? 2 :               \
84
79.6k
    ((Char) < 0x10000 ? 3 :            \
85
71.0k
     ((Char) < 0x200000 ? 4 :          \
86
3.39k
      ((Char) < 0x4000000 ? 5 : 6)))))
87
   
88
89
#define UTF8_GET(Result, Chars, Count, Mask, Len)           \
90
34.0k
  (Result) = (Chars)[0] & (Mask);               \
91
68.0k
  for ((Count) = 1; (Count) < (Len); ++(Count))             \
92
34.0k
    {                       \
93
34.0k
      if (((Chars)[(Count)] & 0xc0) != 0x80)             \
94
34.0k
  {                     \
95
0
    (Result) = -1;                  \
96
0
    break;                    \
97
0
  }                      \
98
34.0k
      (Result) <<= 6;                   \
99
34.0k
      (Result) |= ((Chars)[(Count)] & 0x3f);              \
100
34.0k
    }
101
    
102
/*
103
 * Check whether a Unicode (5.2) char is in a valid range.
104
 *
105
 * The first check comes from the Unicode guarantee to never encode
106
 * a point above 0x0010ffff, since UTF-16 couldn't represent it.
107
 * 
108
 * The second check covers surrogate pairs (category Cs).
109
 *
110
 * @param Char the character
111
 */
112
#define UNICODE_VALID(Char)                   \
113
0
    ((Char) < 0x110000 &&                     \
114
0
     (((Char) & 0xFFFFF800) != 0xD800))
115
116
    
117
static const gchar utf8_skip_data[256] = {
118
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
119
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
120
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
121
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
122
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
123
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
124
  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
125
  3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1
126
};
127
128
const gchar * const g_utf8_skip = utf8_skip_data;
129
130
/**
131
 * g_utf8_find_prev_char:
132
 * @str: pointer to the beginning of a UTF-8 encoded string
133
 * @p: pointer to some position within @str
134
 * 
135
 * Given a position @p with a UTF-8 encoded string @str, find the start
136
 * of the previous UTF-8 character starting before @p. Returns `NULL` if no
137
 * UTF-8 characters are present in @str before @p.
138
 *
139
 * @p does not have to be at the beginning of a UTF-8 character. No check
140
 * is made to see if the character found is actually valid other than
141
 * it starts with an appropriate byte.
142
 *
143
 * Returns: (transfer none) (nullable): a pointer to the found character
144
 */
145
gchar *
146
g_utf8_find_prev_char (const gchar *str,
147
           const gchar *p)
148
0
{
149
0
  while (p > str)
150
0
    {
151
0
      --p;
152
0
      if ((*p & 0xc0) != 0x80)
153
0
  return (gchar *)p;
154
0
    }
155
0
  return NULL;
156
0
}
157
158
/**
159
 * g_utf8_find_next_char:
160
 * @p: a pointer to a position within a UTF-8 encoded string
161
 * @end: (nullable): a pointer to the byte following the end of the string,
162
 *     or `NULL` to indicate that the string is nul-terminated
163
 *
164
 * Finds the start of the next UTF-8 character in the string after @p.
165
 *
166
 * @p does not have to be at the beginning of a UTF-8 character. No check
167
 * is made to see if the character found is actually valid other than
168
 * it starts with an appropriate byte.
169
 * 
170
 * If @end is `NULL`, the return value will never be `NULL`: if the end of the
171
 * string is reached, a pointer to the terminating nul byte is returned. If
172
 * @end is non-`NULL`, the return value will be `NULL` if the end of the string
173
 * is reached.
174
 *
175
 * Returns: (transfer none) (nullable): a pointer to the found character or `NULL` if @end is
176
 *    set and is reached
177
 */
178
gchar *
179
g_utf8_find_next_char (const gchar *p,
180
           const gchar *end)
181
0
{
182
0
  if (end)
183
0
    {
184
0
      for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
185
0
        ;
186
0
      return (p >= end) ? NULL : (gchar *)p;
187
0
    }
188
0
  else
189
0
    {
190
0
      for (++p; (*p & 0xc0) == 0x80; ++p)
191
0
        ;
192
0
      return (gchar *)p;
193
0
    }
194
0
}
195
196
/**
197
 * g_utf8_prev_char:
198
 * @p: a pointer to a position within a UTF-8 encoded string
199
 *
200
 * Finds the previous UTF-8 character in the string before @p.
201
 *
202
 * @p does not have to be at the beginning of a UTF-8 character. No check
203
 * is made to see if the character found is actually valid other than
204
 * it starts with an appropriate byte. If @p might be the first
205
 * character of the string, you must use [func@GLib.utf8_find_prev_char]
206
 * instead.
207
 * 
208
 * Returns: (transfer none) (not nullable): a pointer to the found character
209
 */
210
gchar *
211
g_utf8_prev_char (const gchar *p)
212
0
{
213
0
  while (TRUE)
214
0
    {
215
0
      p--;
216
0
      if ((*p & 0xc0) != 0x80)
217
0
  return (gchar *)p;
218
0
    }
219
0
}
220
 
221
/**
222
 * g_utf8_strlen:
223
 * @p: pointer to the start of a UTF-8 encoded string
224
 * @max: the maximum number of bytes to examine. If @max
225
 *   is less than 0, then the string is assumed to be
226
 *   nul-terminated. If @max is 0, @p will not be examined and
227
 *   may be `NULL`. If @max is greater than 0, up to @max
228
 *   bytes are examined
229
 *
230
 * Computes the length of the string in characters, not including
231
 * the terminating nul character. If the @max’th byte falls in the
232
 * middle of a character, the last (partial) character is not counted.
233
 *
234
 * Returns: the length of the string in characters
235
 */
236
glong
237
g_utf8_strlen (const gchar *p,
238
               gssize       max)
239
0
{
240
0
  glong len = 0;
241
0
  const gchar *start = p;
242
0
  g_return_val_if_fail (p != NULL || max == 0, 0);
243
244
0
  if (max < 0)
245
0
    {
246
0
      while (*p)
247
0
        {
248
0
          p = g_utf8_next_char (p);
249
0
          ++len;
250
0
        }
251
0
    }
252
0
  else
253
0
    {
254
0
      if (max == 0 || !*p)
255
0
        return 0;
256
257
0
      p = g_utf8_next_char (p);
258
259
0
      while (p - start < max && *p)
260
0
        {
261
0
          ++len;
262
0
          p = g_utf8_next_char (p);
263
0
        }
264
265
      /* only do the last len increment if we got a complete
266
       * char (don't count partial chars)
267
       */
268
0
      if (p - start <= max)
269
0
        ++len;
270
0
    }
271
272
0
  return len;
273
0
}
274
275
/**
276
 * g_utf8_substring:
277
 * @str: a UTF-8 encoded string
278
 * @start_pos: a character offset within @str
279
 * @end_pos: another character offset within @str,
280
 *   or `-1` to indicate the end of the string
281
 *
282
 * Copies a substring out of a UTF-8 encoded string.
283
 * The substring will contain @end_pos - @start_pos characters.
284
 *
285
 * Since GLib 2.72, `-1` can be passed to @end_pos to indicate the
286
 * end of the string.
287
 *
288
 * Returns: (transfer full): a newly allocated copy of the requested
289
 *   substring. Free with [func@GLib.free] when no longer needed.
290
 *
291
 * Since: 2.30
292
 */
293
gchar *
294
g_utf8_substring (const gchar *str,
295
                  glong        start_pos,
296
                  glong        end_pos)
297
0
{
298
0
  gchar *start, *end, *out;
299
300
0
  g_return_val_if_fail (end_pos >= start_pos || end_pos == -1, NULL);
301
302
0
  start = g_utf8_offset_to_pointer (str, start_pos);
303
304
0
  if (end_pos == -1)
305
0
    {
306
0
      glong length = g_utf8_strlen (start, -1);
307
0
      end = g_utf8_offset_to_pointer (start, length);
308
0
    }
309
0
  else
310
0
    {
311
0
      end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
312
0
    }
313
314
0
  out = g_malloc (end - start + 1);
315
0
  memcpy (out, start, end - start);
316
0
  out[end - start] = 0;
317
318
0
  return out;
319
0
}
320
321
/**
322
 * g_utf8_get_char:
323
 * @p: a pointer to Unicode character encoded as UTF-8
324
 * 
325
 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
326
 *
327
 * If @p does not point to a valid UTF-8 encoded character, results
328
 * are undefined. If you are not sure that the bytes are complete
329
 * valid Unicode characters, you should use [func@GLib.utf8_get_char_validated]
330
 * instead.
331
 * 
332
 * Returns: the resulting character
333
 */
334
gunichar
335
g_utf8_get_char (const gchar *p)
336
34.0k
{
337
34.0k
  int i, mask = 0, len;
338
34.0k
  gunichar result;
339
34.0k
  unsigned char c = (unsigned char) *p;
340
341
34.0k
  UTF8_COMPUTE (c, mask, len);
342
34.0k
  if (len == -1)
343
0
    return (gunichar)-1;
344
34.0k
  UTF8_GET (result, p, i, mask, len);
345
346
34.0k
  return result;
347
34.0k
}
348
349
/**
350
 * g_utf8_offset_to_pointer:
351
 * @str: a UTF-8 encoded string
352
 * @offset: a character offset within @str
353
 *
354
 * Converts from an integer character offset to a pointer to a position
355
 * within the string.
356
 *
357
 * Since 2.10, this function allows to pass a negative @offset to
358
 * step backwards. It is usually worth stepping backwards from the end
359
 * instead of forwards if @offset is in the last fourth of the string,
360
 * since moving forward is about 3 times faster than moving backward.
361
 *
362
 * Note that this function doesn’t abort when reaching the end of @str.
363
 * Therefore you should be sure that @offset is within string boundaries
364
 * before calling that function. Call [func@GLib.utf8_strlen] when unsure.
365
 * This limitation exists as this function is called frequently during
366
 * text rendering and therefore has to be as fast as possible.
367
 *
368
 * Returns: (transfer none): the resulting pointer
369
 */
370
gchar *
371
g_utf8_offset_to_pointer  (const gchar *str,
372
         glong        offset)
373
0
{
374
0
  const gchar *s = str;
375
376
0
  if (offset > 0) 
377
0
    while (offset--)
378
0
      s = g_utf8_next_char (s);
379
0
  else
380
0
    {
381
0
      const char *s1;
382
383
      /* This nice technique for fast backwards stepping 
384
       * through a UTF-8 string was dubbed "stutter stepping" 
385
       * by its inventor, Larry Ewing.
386
       */
387
0
      while (offset)
388
0
  {
389
0
    s1 = s;
390
0
    s += offset;
391
0
    while ((*s & 0xc0) == 0x80)
392
0
      s--;
393
394
0
    offset += g_utf8_pointer_to_offset (s, s1);
395
0
  }
396
0
    }
397
398
0
  return (gchar *)s;
399
0
}
400
401
/**
402
 * g_utf8_pointer_to_offset:
403
 * @str: a UTF-8 encoded string
404
 * @pos: a pointer to a position within @str
405
 * 
406
 * Converts from a pointer to position within a string to an integer
407
 * character offset.
408
 *
409
 * Since 2.10, this function allows @pos to be before @str, and returns
410
 * a negative offset in this case.
411
 * 
412
 * Returns: the resulting character offset
413
 */
414
glong    
415
g_utf8_pointer_to_offset (const gchar *str,
416
        const gchar *pos)
417
0
{
418
0
  const gchar *s = str;
419
0
  glong offset = 0;    
420
421
0
  if (pos < str) 
422
0
    offset = - g_utf8_pointer_to_offset (pos, str);
423
0
  else
424
0
    while (s < pos)
425
0
      {
426
0
  s = g_utf8_next_char (s);
427
0
  offset++;
428
0
      }
429
  
430
0
  return offset;
431
0
}
432
433
434
/**
435
 * g_utf8_strncpy:
436
 * @dest: (transfer none): buffer to fill with characters from @src
437
 * @src: UTF-8 encoded string
438
 * @n: character count
439
 * 
440
 * Like the standard C [`strncpy()`](man:strncpy) function, but copies a given
441
 * number of characters instead of a given number of bytes.
442
 *
443
 * The @src string must be valid UTF-8 encoded text. (Use
444
 * [func@GLib.utf8_validate] on all text before trying to use UTF-8 utility
445
 * functions with it.)
446
 * 
447
 * Note you must ensure @dest is at least 4 * @n + 1 to fit the
448
 * largest possible UTF-8 characters
449
 *
450
 * Returns: (transfer none): @dest
451
 */
452
gchar *
453
g_utf8_strncpy (gchar       *dest,
454
    const gchar *src,
455
    gsize        n)
456
0
{
457
0
  const gchar *s = src;
458
0
  while (n && *s)
459
0
    {
460
0
      s = g_utf8_next_char(s);
461
0
      n--;
462
0
    }
463
0
  strncpy(dest, src, s - src);
464
0
  dest[s - src] = 0;
465
0
  return dest;
466
0
}
467
468
/**
469
 * g_utf8_truncate_middle:
470
 * @string: (transfer none): a nul-terminated UTF-8 encoded string
471
 * @truncate_length: the new size of @string, in characters, including the ellipsis character
472
 *
473
 * Cuts off the middle of the string, preserving half of @truncate_length
474
 * characters at the beginning and half at the end.
475
 * 
476
 * If @string is already short enough, this returns a copy of @string.
477
 * If @truncate_length is `0`, an empty string is returned.
478
 *
479
 * Returns: (transfer full): a newly-allocated copy of @string ellipsized in the middle
480
 *
481
 * Since: 2.78
482
 */
483
gchar *
484
g_utf8_truncate_middle (const gchar *string,
485
                        gsize        truncate_length)
486
0
{
487
0
  const gchar *ellipsis = "…";
488
0
  const gsize ellipsis_bytes = strlen (ellipsis);
489
490
0
  gsize length;
491
0
  gsize left_substring_length;
492
0
  gchar *left_substring_end;
493
0
  gchar *right_substring_begin;
494
0
  gchar *right_substring_end;
495
0
  gsize left_bytes;
496
0
  gsize right_bytes;
497
0
  gchar *result;
498
499
0
  g_return_val_if_fail (string != NULL, NULL);
500
501
0
  length = g_utf8_strlen (string, -1);
502
  /* Current string already smaller than requested length */
503
0
  if (length <= truncate_length)
504
0
    return g_strdup (string);
505
0
  if (truncate_length == 0)
506
0
    return g_strdup ("");
507
508
  /* Find substrings to keep, ignore ellipsis character for that */
509
0
  truncate_length -= 1;
510
511
0
  left_substring_length = truncate_length / 2;
512
513
0
  left_substring_end = g_utf8_offset_to_pointer (string, left_substring_length);
514
0
  right_substring_begin = g_utf8_offset_to_pointer (left_substring_end,
515
0
                                                    length - truncate_length);
516
0
  right_substring_end = g_utf8_offset_to_pointer (right_substring_begin,
517
0
                                                  truncate_length - left_substring_length);
518
519
0
  g_assert (*right_substring_end == '\0');
520
521
0
  left_bytes = left_substring_end - string;
522
0
  right_bytes = right_substring_end - right_substring_begin;
523
524
0
  result = g_malloc (left_bytes + ellipsis_bytes + right_bytes + 1);
525
526
0
  strncpy (result, string, left_bytes);
527
0
  memcpy (result + left_bytes, ellipsis, ellipsis_bytes);
528
0
  strncpy (result + left_bytes + ellipsis_bytes, right_substring_begin, right_bytes);
529
0
  result[left_bytes + ellipsis_bytes + right_bytes] = '\0';
530
531
0
  return result;
532
0
}
533
534
/* unicode_strchr */
535
536
/**
537
 * g_unichar_to_utf8:
538
 * @c: a Unicode character code
539
 * @outbuf: (out caller-allocates) (optional): output buffer, must have at
540
 *   least 6 bytes of space. If `NULL`, the length will be computed and
541
 *   returned and nothing will be written to @outbuf.
542
 * 
543
 * Converts a single character to UTF-8.
544
 * 
545
 * Returns: number of bytes written
546
 */
547
int
548
g_unichar_to_utf8 (gunichar c,
549
       gchar   *outbuf)
550
86.1k
{
551
  /* If this gets modified, also update the copy in g_string_insert_unichar() */
552
86.1k
  guint len = 0;    
553
86.1k
  int first;
554
86.1k
  int i;
555
556
86.1k
  if (c < 0x80)
557
15.0k
    {
558
15.0k
      first = 0;
559
15.0k
      len = 1;
560
15.0k
    }
561
71.1k
  else if (c < 0x800)
562
7.94k
    {
563
7.94k
      first = 0xc0;
564
7.94k
      len = 2;
565
7.94k
    }
566
63.1k
  else if (c < 0x10000)
567
60.2k
    {
568
60.2k
      first = 0xe0;
569
60.2k
      len = 3;
570
60.2k
    }
571
2.97k
   else if (c < 0x200000)
572
2.97k
    {
573
2.97k
      first = 0xf0;
574
2.97k
      len = 4;
575
2.97k
    }
576
0
  else if (c < 0x4000000)
577
0
    {
578
0
      first = 0xf8;
579
0
      len = 5;
580
0
    }
581
0
  else
582
0
    {
583
0
      first = 0xfc;
584
0
      len = 6;
585
0
    }
586
587
86.1k
  if (outbuf)
588
86.1k
    {
589
223k
      for (i = len - 1; i > 0; --i)
590
137k
  {
591
137k
    outbuf[i] = (c & 0x3f) | 0x80;
592
137k
    c >>= 6;
593
137k
  }
594
86.1k
      outbuf[0] = c | first;
595
86.1k
    }
596
597
86.1k
  return len;
598
86.1k
}
599
600
/**
601
 * g_utf8_strchr:
602
 * @p: a nul-terminated UTF-8 encoded string
603
 * @len: the maximum length of @p
604
 * @c: a Unicode character
605
 * 
606
 * Finds the leftmost occurrence of the given Unicode character
607
 * in a UTF-8 encoded string, while limiting the search to @len bytes.
608
 * 
609
 * If @len is `-1`, allow unbounded search.
610
 *
611
 * Returns: (transfer none) (nullable): `NULL` if the string does not contain
612
 *   the character, otherwise, a pointer to the start of the leftmost occurrence
613
 *   of the character in the string.
614
 */
615
gchar *
616
g_utf8_strchr (const char *p,
617
         gssize      len,
618
         gunichar    c)
619
1.59k
{
620
1.59k
  gchar ch[10];
621
622
1.59k
  gint charlen = g_unichar_to_utf8 (c, ch);
623
1.59k
  ch[charlen] = '\0';
624
  
625
1.59k
  return g_strstr_len (p, len, ch);
626
1.59k
}
627
628
629
/**
630
 * g_utf8_strrchr:
631
 * @p: a nul-terminated UTF-8 encoded string
632
 * @len: the maximum length of @p
633
 * @c: a Unicode character
634
 * 
635
 * Find the rightmost occurrence of the given Unicode character
636
 * in a UTF-8 encoded string, while limiting the search to @len bytes.
637
 * 
638
 * If @len is `-1`, allow unbounded search.
639
 *
640
 * Returns: (transfer none) (nullable): `NULL` if the string does not contain
641
 *   the character, otherwise, a pointer to the start of the rightmost
642
 *   occurrence of the character in the string.
643
 */
644
gchar *
645
g_utf8_strrchr (const char *p,
646
    gssize      len,
647
    gunichar    c)
648
0
{
649
0
  gchar ch[10];
650
651
0
  gint charlen = g_unichar_to_utf8 (c, ch);
652
0
  ch[charlen] = '\0';
653
  
654
0
  return g_strrstr_len (p, len, ch);
655
0
}
656
657
658
/* Like g_utf8_get_char, but take a maximum length
659
 * and return (gunichar)-2 on incomplete trailing character;
660
 * also check for malformed or overlong sequences
661
 * and return (gunichar)-1 in this case.
662
 */
663
static inline gunichar
664
g_utf8_get_char_extended (const  gchar *p,
665
        gssize max_len)
666
0
{
667
0
  gsize i, len;
668
0
  gunichar min_code;
669
0
  gunichar wc = (guchar) *p;
670
0
  const gunichar partial_sequence = (gunichar) -2;
671
0
  const gunichar malformed_sequence = (gunichar) -1;
672
673
0
  if (wc < 0x80)
674
0
    {
675
0
      return wc;
676
0
    }
677
0
  else if (G_UNLIKELY (wc < 0xc0))
678
0
    {
679
0
      return malformed_sequence;
680
0
    }
681
0
  else if (wc < 0xe0)
682
0
    {
683
0
      len = 2;
684
0
      wc &= 0x1f;
685
0
      min_code = 1 << 7;
686
0
    }
687
0
  else if (wc < 0xf0)
688
0
    {
689
0
      len = 3;
690
0
      wc &= 0x0f;
691
0
      min_code = 1 << 11;
692
0
    }
693
0
  else if (wc < 0xf8)
694
0
    {
695
0
      len = 4;
696
0
      wc &= 0x07;
697
0
      min_code = 1 << 16;
698
0
    }
699
0
  else if (wc < 0xfc)
700
0
    {
701
0
      len = 5;
702
0
      wc &= 0x03;
703
0
      min_code = 1 << 21;
704
0
    }
705
0
  else if (wc < 0xfe)
706
0
    {
707
0
      len = 6;
708
0
      wc &= 0x01;
709
0
      min_code = 1 << 26;
710
0
    }
711
0
  else
712
0
    {
713
0
      return malformed_sequence;
714
0
    }
715
716
0
  if (G_UNLIKELY (max_len >= 0 && len > (gsize) max_len))
717
0
    {
718
0
      for (i = 1; i < (gsize) max_len; i++)
719
0
  {
720
0
    if ((((guchar *)p)[i] & 0xc0) != 0x80)
721
0
      return malformed_sequence;
722
0
  }
723
0
      return partial_sequence;
724
0
    }
725
726
0
  for (i = 1; i < len; ++i)
727
0
    {
728
0
      gunichar ch = ((guchar *)p)[i];
729
730
0
      if (G_UNLIKELY ((ch & 0xc0) != 0x80))
731
0
  {
732
0
    if (ch)
733
0
      return malformed_sequence;
734
0
    else
735
0
      return partial_sequence;
736
0
  }
737
738
0
      wc <<= 6;
739
0
      wc |= (ch & 0x3f);
740
0
    }
741
742
0
  if (G_UNLIKELY (wc < min_code))
743
0
    return malformed_sequence;
744
745
0
  return wc;
746
0
}
747
748
/**
749
 * g_utf8_get_char_validated:
750
 * @p: a pointer to Unicode character encoded as UTF-8
751
 * @max_len: the maximum number of bytes to read, or `-1` if @p is nul-terminated
752
 *
753
 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
754
 *
755
 * This function checks for incomplete characters, for invalid characters
756
 * such as characters that are out of the range of Unicode, and for
757
 * overlong encodings of valid characters.
758
 *
759
 * Note that [func@GLib.utf8_get_char_validated] returns `(gunichar)-2` if
760
 * @max_len is positive and any of the bytes in the first UTF-8 character
761
 * sequence are nul.
762
 * 
763
 * Returns: the resulting character. If @p points to a partial
764
 *   sequence at the end of a string that could begin a valid
765
 *   character (or if @max_len is zero), returns `(gunichar)-2`;
766
 *   otherwise, if @p does not point to a valid UTF-8 encoded
767
 *   Unicode character, returns `(gunichar)-1`.
768
 */
769
gunichar
770
g_utf8_get_char_validated (const gchar *p,
771
         gssize       max_len)
772
0
{
773
0
  gunichar result;
774
775
0
  if (max_len == 0)
776
0
    return (gunichar)-2;
777
778
0
  result = g_utf8_get_char_extended (p, max_len);
779
780
  /* Disallow codepoint U+0000 as it’s a nul byte,
781
   * and all string handling in GLib is nul-terminated */
782
0
  if (result == 0 && max_len > 0)
783
0
    return (gunichar) -2;
784
785
0
  if (result & 0x80000000)
786
0
    return result;
787
0
  else if (!UNICODE_VALID (result))
788
0
    return (gunichar)-1;
789
0
  else
790
0
    return result;
791
0
}
792
793
0
#define CONT_BYTE_FAST(p) ((guchar)*p++ & 0x3f)
794
795
/**
796
 * g_utf8_to_ucs4_fast:
797
 * @str: a UTF-8 encoded string
798
 * @len: the maximum length of @str to use, in bytes. If @len is negative,
799
 *   then the string is nul-terminated.
800
 * @items_written: (out) (optional): location to store the
801
 *   number of characters in the result, or `NULL`.
802
 *
803
 * Convert a string from UTF-8 to a 32-bit fixed width
804
 * representation as UCS-4, assuming valid UTF-8 input.
805
 *
806
 * This function is roughly twice as fast as [func@GLib.utf8_to_ucs4]
807
 * but does no error checking on the input. A trailing nul character (U+0000)
808
 * will be added to the string after the converted text.
809
 * 
810
 * Returns: (transfer full): a pointer to a newly allocated UCS-4 string.
811
 *   This value must be freed with [func@GLib.free].
812
 */
813
gunichar *
814
g_utf8_to_ucs4_fast (const gchar *str,
815
         glong        len,              
816
         glong       *items_written)    
817
0
{
818
0
  gunichar *result;
819
0
  gint n_chars, i;
820
0
  const gchar *p;
821
822
0
  g_return_val_if_fail (str != NULL, NULL);
823
824
0
  p = str;
825
0
  n_chars = 0;
826
0
  if (len < 0)
827
0
    {
828
0
      while (*p)
829
0
  {
830
0
    p = g_utf8_next_char (p);
831
0
    ++n_chars;
832
0
  }
833
0
    }
834
0
  else
835
0
    {
836
0
      while (p < str + len && *p)
837
0
  {
838
0
    p = g_utf8_next_char (p);
839
0
    ++n_chars;
840
0
  }
841
0
    }
842
  
843
0
  result = g_new (gunichar, n_chars + 1);
844
  
845
0
  p = str;
846
0
  for (i=0; i < n_chars; i++)
847
0
    {
848
0
      guchar first = (guchar)*p++;
849
0
      gunichar wc;
850
851
0
      if (first < 0xc0)
852
0
  {
853
          /* We really hope first < 0x80, but we don't want to test an
854
           * extra branch for invalid input, which this function
855
           * does not care about. Handling unexpected continuation bytes
856
           * here will do the least damage. */
857
0
    wc = first;
858
0
  }
859
0
      else
860
0
  {
861
0
          gunichar c1 = CONT_BYTE_FAST(p);
862
0
          if (first < 0xe0)
863
0
            {
864
0
              wc = ((first & 0x1f) << 6) | c1;
865
0
            }
866
0
          else
867
0
            {
868
0
              gunichar c2 = CONT_BYTE_FAST(p);
869
0
              if (first < 0xf0)
870
0
                {
871
0
                  wc = ((first & 0x0f) << 12) | (c1 << 6) | c2;
872
0
                }
873
0
              else
874
0
                {
875
0
                  gunichar c3 = CONT_BYTE_FAST(p);
876
0
                  wc = ((first & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
877
0
                  if (G_UNLIKELY (first >= 0xf8))
878
0
                    {
879
                      /* This can't be valid UTF-8, but g_utf8_next_char()
880
                       * and company allow out-of-range sequences */
881
0
                      gunichar mask = 1 << 20;
882
0
                      while ((wc & mask) != 0)
883
0
                        {
884
0
                          wc <<= 6;
885
0
                          wc |= CONT_BYTE_FAST(p);
886
0
                          mask <<= 5;
887
0
                        }
888
0
                      wc &= mask - 1;
889
0
                    }
890
0
                }
891
0
            }
892
0
  }
893
0
      result[i] = wc;
894
0
    }
895
0
  result[i] = 0;
896
897
0
  if (items_written)
898
0
    *items_written = i;
899
900
0
  return result;
901
0
}
902
903
static gpointer
904
try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
905
5.74k
{
906
5.74k
    gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
907
5.74k
    if (ptr == NULL)
908
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
909
0
                           _("Failed to allocate memory"));
910
5.74k
    return ptr;
911
5.74k
}
912
913
/**
914
 * g_utf8_to_ucs4:
915
 * @str: a UTF-8 encoded string
916
 * @len: the maximum length of @str to use, in bytes. If @len is negative,
917
 *   then the string is nul-terminated.
918
 * @items_read: (out) (optional): location to store number of
919
  *  bytes read, or `NULL`.
920
 *   If `NULL`, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
921
 *   returned in case @str contains a trailing partial
922
 *   character. If an error occurs then the index of the
923
 *   invalid input is stored here.
924
 * @items_written: (out) (optional): location to store number
925
 *   of characters written or `NULL`. The value here stored does not include
926
 *   the trailing nul character.
927
 * @error: location to store the error occurring, or `NULL` to ignore
928
 *   errors. Any of the errors in [error@GLib.ConvertError] other than
929
 *   [error@GLib.ConvertError.NO_CONVERSION] may occur.
930
 *
931
 * Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4.
932
 *
933
 * A trailing nul character (U+0000) will be added to the string after the
934
 * converted text.
935
 * 
936
 * Returns: (transfer full): a pointer to a newly allocated UCS-4 string.
937
 *   This value must be freed with [func@GLib.free].
938
 */
939
gunichar *
940
g_utf8_to_ucs4 (const gchar *str,
941
    glong        len,             
942
    glong       *items_read,      
943
    glong       *items_written,   
944
    GError     **error)
945
0
{
946
0
  gunichar *result = NULL;
947
0
  gint n_chars, i;
948
0
  const gchar *in;
949
  
950
0
  in = str;
951
0
  n_chars = 0;
952
0
  while ((len < 0 || str + len - in > 0) && *in)
953
0
    {
954
0
      gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
955
0
      if (wc & 0x80000000)
956
0
  {
957
0
    if (wc == (gunichar)-2)
958
0
      {
959
0
        if (items_read)
960
0
    break;
961
0
        else
962
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
963
0
                                     _("Partial character sequence at end of input"));
964
0
      }
965
0
    else
966
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
967
0
                                 _("Invalid byte sequence in conversion input"));
968
969
0
    goto err_out;
970
0
  }
971
972
0
      n_chars++;
973
974
0
      in = g_utf8_next_char (in);
975
0
    }
976
977
0
  result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
978
0
  if (result == NULL)
979
0
      goto err_out;
980
981
0
  in = str;
982
0
  for (i=0; i < n_chars; i++)
983
0
    {
984
0
      result[i] = g_utf8_get_char (in);
985
0
      in = g_utf8_next_char (in);
986
0
    }
987
0
  result[i] = 0;
988
989
0
  if (items_written)
990
0
    *items_written = n_chars;
991
992
0
 err_out:
993
0
  if (items_read)
994
0
    *items_read = in - str;
995
996
0
  return result;
997
0
}
998
999
/**
1000
 * g_ucs4_to_utf8:
1001
 * @str: (array length=len) (element-type gunichar): a UCS-4 encoded string
1002
 * @len: the maximum length (number of characters) of @str to use. 
1003
 *   If @len is negative, then the string is nul-terminated.
1004
 * @items_read: (out) (optional): location to store number of
1005
 *   characters read, or `NULL`.
1006
 * @items_written: (out) (optional): location to store number
1007
 *   of bytes written or `NULL`. The value here stored does not include the
1008
 *   trailing nul byte.
1009
 * @error: location to store the error occurring, or %NULL to ignore
1010
 *   errors. Any of the errors in #GConvertError other than
1011
 *   %G_CONVERT_ERROR_NO_CONVERSION may occur.
1012
 *
1013
 * Convert a string from a 32-bit fixed width representation as UCS-4.
1014
 * to UTF-8.
1015
 *
1016
 * The result will be terminated with a nul byte.
1017
 * 
1018
 * Returns: (transfer full): a pointer to a newly allocated UTF-8 string.
1019
 *   This value must be freed with [func@GLib.free]. If an error occurs,
1020
 *   @items_read will be set to the position of the first invalid input
1021
 *   character.
1022
 */
1023
gchar *
1024
g_ucs4_to_utf8 (const gunichar *str,
1025
    glong           len,              
1026
    glong          *items_read,       
1027
    glong          *items_written,    
1028
    GError        **error)
1029
0
{
1030
0
  gint result_length;
1031
0
  gchar *result = NULL;
1032
0
  gchar *p;
1033
0
  gint i;
1034
1035
0
  result_length = 0;
1036
0
  for (i = 0; len < 0 || i < len ; i++)
1037
0
    {
1038
0
      if (!str[i])
1039
0
  break;
1040
1041
0
      if (str[i] >= 0x80000000)
1042
0
  {
1043
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1044
0
                               _("Character out of range for UTF-8"));
1045
0
    goto err_out;
1046
0
  }
1047
      
1048
0
      result_length += UTF8_LENGTH (str[i]);
1049
0
    }
1050
1051
0
  result = try_malloc_n (result_length + 1, 1, error);
1052
0
  if (result == NULL)
1053
0
      goto err_out;
1054
1055
0
  p = result;
1056
1057
0
  i = 0;
1058
0
  while (p < result + result_length)
1059
0
    p += g_unichar_to_utf8 (str[i++], p);
1060
  
1061
0
  *p = '\0';
1062
1063
0
  if (items_written)
1064
0
    *items_written = p - result;
1065
1066
0
 err_out:
1067
0
  if (items_read)
1068
0
    *items_read = i;
1069
1070
0
  return result;
1071
0
}
1072
1073
6.37k
#define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
1074
1075
/**
1076
 * g_utf16_to_utf8:
1077
 * @str: (array length=len) (element-type guint16): a UTF-16 encoded string
1078
 * @len: the maximum length (number of #gunichar2) of @str to use. 
1079
 *   If @len is negative, then the string is nul-terminated.
1080
 * @items_read: (out) (optional): location to store number of words read, or
1081
 *   `NULL`. If `NULL`, then [error@GLib.ConvertError.PARTIAL_INPUT] will
1082
 *   be returned in case @str contains a trailing partial character. If
1083
 *   an error occurs then the index of the invalid input is stored here.
1084
 *   It’s guaranteed to be non-negative.
1085
 * @items_written: (out) (optional): location to store number
1086
 *   of bytes written, or `NULL`. The value stored here does not include the
1087
 *   trailing nul byte. It’s guaranteed to be non-negative.
1088
 * @error: location to store the error occurring, or `NULL` to ignore
1089
 *   errors. Any of the errors in [error@GLib.ConvertError] other than
1090
 *   [error@GLib.ConvertError.NO_CONVERSION] may occur.
1091
 *
1092
 * Convert a string from UTF-16 to UTF-8.
1093
 *
1094
 * The result will be terminated with a nul byte.
1095
 *
1096
 * Note that the input is expected to be already in native endianness,
1097
 * an initial byte-order-mark character is not handled specially.
1098
 * [func@GLib.convert] can be used to convert a byte buffer of UTF-16 data of
1099
 * ambiguous endianness.
1100
 *
1101
 * Further note that this function does not validate the result
1102
 * string; it may (for example) include embedded nul characters. The only
1103
 * validation done by this function is to ensure that the input can
1104
 * be correctly interpreted as UTF-16, i.e. it doesn’t contain
1105
 * unpaired surrogates or partial character sequences.
1106
 *
1107
 * Returns: (transfer full): a pointer to a newly allocated UTF-8 string.
1108
 *   This value must be freed with [func@GLib.free].
1109
 **/
1110
gchar *
1111
g_utf16_to_utf8 (const gunichar2  *str,
1112
     glong             len,
1113
     glong            *items_read,
1114
     glong            *items_written,
1115
     GError          **error)
1116
6.51k
{
1117
  /* This function and g_utf16_to_ucs4 are almost exactly identical -
1118
   * The lines that differ are marked.
1119
   */
1120
6.51k
  const gunichar2 *in;
1121
6.51k
  gchar *out;
1122
6.51k
  gchar *result = NULL;
1123
6.51k
  gint n_bytes;
1124
6.51k
  gunichar high_surrogate;
1125
1126
6.51k
  g_return_val_if_fail (str != NULL, NULL);
1127
1128
6.51k
  n_bytes = 0;
1129
6.51k
  in = str;
1130
6.51k
  high_surrogate = 0;
1131
104k
  while ((len < 0 || in - str < len) && *in)
1132
98.2k
    {
1133
98.2k
      gunichar2 c = *in;
1134
98.2k
      gunichar wc;
1135
1136
98.2k
      if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1137
3.67k
  {
1138
3.67k
    if (high_surrogate)
1139
3.39k
      {
1140
3.39k
        wc = SURROGATE_VALUE (high_surrogate, c);
1141
3.39k
        high_surrogate = 0;
1142
3.39k
      }
1143
284
    else
1144
284
      {
1145
284
        g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1146
284
                                   _("Invalid sequence in conversion input"));
1147
284
        goto err_out;
1148
284
      }
1149
3.67k
  }
1150
94.6k
      else
1151
94.6k
  {
1152
94.6k
    if (high_surrogate)
1153
493
      {
1154
493
        g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1155
493
                                   _("Invalid sequence in conversion input"));
1156
493
        goto err_out;
1157
493
      }
1158
1159
94.1k
    if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1160
4.12k
      {
1161
4.12k
        high_surrogate = c;
1162
4.12k
        goto next1;
1163
4.12k
      }
1164
90.0k
    else
1165
90.0k
      wc = c;
1166
94.1k
  }
1167
1168
      /********** DIFFERENT for UTF8/UCS4 **********/
1169
93.3k
      n_bytes += UTF8_LENGTH (wc);
1170
1171
97.5k
    next1:
1172
97.5k
      in++;
1173
97.5k
    }
1174
1175
5.74k
  if (high_surrogate && !items_read)
1176
0
    {
1177
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1178
0
                           _("Partial character sequence at end of input"));
1179
0
      goto err_out;
1180
0
    }
1181
  
1182
  /* At this point, everything is valid, and we just need to convert
1183
   */
1184
  /********** DIFFERENT for UTF8/UCS4 **********/
1185
5.74k
  result = try_malloc_n (n_bytes + 1, 1, error);
1186
5.74k
  if (result == NULL)
1187
0
      goto err_out;
1188
1189
5.74k
  high_surrogate = 0;
1190
5.74k
  out = result;
1191
5.74k
  in = str;
1192
93.2k
  while (out < result + n_bytes)
1193
87.5k
    {
1194
87.5k
      gunichar2 c = *in;
1195
87.5k
      gunichar wc;
1196
1197
87.5k
      if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1198
2.97k
  {
1199
2.97k
    wc = SURROGATE_VALUE (high_surrogate, c);
1200
2.97k
    high_surrogate = 0;
1201
2.97k
  }
1202
84.5k
      else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1203
2.97k
  {
1204
2.97k
    high_surrogate = c;
1205
2.97k
    goto next2;
1206
2.97k
  }
1207
81.5k
      else
1208
81.5k
  wc = c;
1209
1210
      /********** DIFFERENT for UTF8/UCS4 **********/
1211
84.5k
      out += g_unichar_to_utf8 (wc, out);
1212
1213
87.5k
    next2:
1214
87.5k
      in++;
1215
87.5k
    }
1216
  
1217
  /********** DIFFERENT for UTF8/UCS4 **********/
1218
5.74k
  *out = '\0';
1219
1220
5.74k
  if (items_written)
1221
    /********** DIFFERENT for UTF8/UCS4 **********/
1222
5.74k
    *items_written = out - result;
1223
1224
6.51k
 err_out:
1225
6.51k
  if (items_read)
1226
6.51k
    *items_read = in - str;
1227
1228
6.51k
  return result;
1229
5.74k
}
1230
1231
/**
1232
 * g_utf16_to_ucs4:
1233
 * @str: (array length=len) (element-type guint16): a UTF-16 encoded string
1234
 * @len: the maximum length (number of #gunichar2) of @str to use. 
1235
 *   If @len is negative, then the string is nul-terminated.
1236
 * @items_read: (out) (optional): location to store number of words read, or
1237
 *   `NULL`. If `NULL`, then [error@GLib.ConvertError.PARTIAL_INPUT] will be
1238
 *   returned in case @str contains a trailing partial character. If
1239
 *   an error occurs then the index of the invalid input is stored here.
1240
 * @items_written: (out) (optional): location to store number
1241
 *   of characters written, or `NULL`. The value stored here does not include
1242
 *   the trailing nul character.
1243
 * @error: location to store the error occurring, or `NULL` to ignore
1244
 *   errors. Any of the errors in [error@GLib.ConvertError] other than
1245
 *   [error@GLib.ConvertError.NO_CONVERSION] may occur.
1246
 *
1247
 * Convert a string from UTF-16 to UCS-4.
1248
 *
1249
 * The result will be nul-terminated.
1250
 * 
1251
 * Returns: (transfer full): a pointer to a newly allocated UCS-4 string.
1252
 *   This value must be freed with [func@GLib.free].
1253
 */
1254
gunichar *
1255
g_utf16_to_ucs4 (const gunichar2  *str,
1256
     glong             len,              
1257
     glong            *items_read,       
1258
     glong            *items_written,    
1259
     GError          **error)
1260
0
{
1261
0
  const gunichar2 *in;
1262
0
  gchar *out;
1263
0
  gchar *result = NULL;
1264
0
  size_t n_bytes;
1265
0
  gunichar high_surrogate;
1266
1267
0
  g_return_val_if_fail (str != NULL, NULL);
1268
1269
0
  n_bytes = 0;
1270
0
  in = str;
1271
0
  high_surrogate = 0;
1272
0
  while ((len < 0 || in - str < len) && *in)
1273
0
    {
1274
0
      gunichar2 c = *in;
1275
1276
0
      if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1277
0
  {
1278
0
    if (high_surrogate)
1279
0
      {
1280
0
        high_surrogate = 0;
1281
0
      }
1282
0
    else
1283
0
      {
1284
0
        g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1285
0
                                   _("Invalid sequence in conversion input"));
1286
0
        goto err_out;
1287
0
      }
1288
0
  }
1289
0
      else
1290
0
  {
1291
0
    if (high_surrogate)
1292
0
      {
1293
0
        g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1294
0
                                   _("Invalid sequence in conversion input"));
1295
0
        goto err_out;
1296
0
      }
1297
1298
0
    if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1299
0
      {
1300
0
        high_surrogate = c;
1301
0
        goto next1;
1302
0
      }
1303
0
  }
1304
1305
      /********** DIFFERENT for UTF8/UCS4 **********/
1306
0
      n_bytes += sizeof (gunichar);
1307
1308
0
    next1:
1309
0
      in++;
1310
0
    }
1311
1312
0
  if (high_surrogate && !items_read)
1313
0
    {
1314
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1315
0
                           _("Partial character sequence at end of input"));
1316
0
      goto err_out;
1317
0
    }
1318
  
1319
  /* At this point, everything is valid, and we just need to convert
1320
   */
1321
  /********** DIFFERENT for UTF8/UCS4 **********/
1322
0
  result = try_malloc_n (n_bytes + 4, 1, error);
1323
0
  if (result == NULL)
1324
0
      goto err_out;
1325
1326
0
  high_surrogate = 0;
1327
0
  out = result;
1328
0
  in = str;
1329
0
  while (out < result + n_bytes)
1330
0
    {
1331
0
      gunichar2 c = *in;
1332
0
      gunichar wc;
1333
1334
0
      if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1335
0
  {
1336
0
    wc = SURROGATE_VALUE (high_surrogate, c);
1337
0
    high_surrogate = 0;
1338
0
  }
1339
0
      else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1340
0
  {
1341
0
    high_surrogate = c;
1342
0
    goto next2;
1343
0
  }
1344
0
      else
1345
0
  wc = c;
1346
1347
      /********** DIFFERENT for UTF8/UCS4 **********/
1348
0
      *(gunichar *)out = wc;
1349
0
      out += sizeof (gunichar);
1350
1351
0
    next2:
1352
0
      in++;
1353
0
    }
1354
1355
  /********** DIFFERENT for UTF8/UCS4 **********/
1356
0
  *(gunichar *)out = 0;
1357
1358
0
  if (items_written)
1359
    /********** DIFFERENT for UTF8/UCS4 **********/
1360
0
    *items_written = (out - result) / sizeof (gunichar);
1361
1362
0
 err_out:
1363
0
  if (items_read)
1364
0
    *items_read = in - str;
1365
1366
0
  return (gunichar *)result;
1367
0
}
1368
1369
/**
1370
 * g_utf8_to_utf16:
1371
 * @str: a UTF-8 encoded string
1372
 * @len: the maximum length (number of bytes) of @str to use.
1373
 *   If @len is negative, then the string is nul-terminated.
1374
 * @items_read: (out) (optional): location to store number of bytes read, or
1375
 *   `NULL`. If `NULL`, then [error@GLib.ConvertError.PARTIAL_INPUT] will
1376
 *   be returned in case @str contains a trailing partial character. If
1377
 *   an error occurs then the index of the invalid input is stored here.
1378
 * @items_written: (out) (optional): location to store number
1379
 *   of `gunichar2` written, or `NULL`. The value stored here does not include
1380
 *   the trailing nul.
1381
 * @error: location to store the error occurring, or `NULL` to ignore
1382
 *   errors. Any of the errors in [error@GLib.ConvertError] other than
1383
 *   [error@GLib.ConvertError.NO_CONVERSION] may occur.
1384
 *
1385
 * Convert a string from UTF-8 to UTF-16.
1386
 *
1387
 * A nul character (U+0000) will be added to the result after the converted text.
1388
 *
1389
 * Returns: (transfer full): a pointer to a newly allocated UTF-16 string.
1390
 *   This value must be freed with [func@GLib.free].
1391
 */
1392
gunichar2 *
1393
g_utf8_to_utf16 (const gchar *str,
1394
     glong        len,
1395
     glong       *items_read,
1396
     glong       *items_written,
1397
     GError     **error)
1398
0
{
1399
0
  gunichar2 *result = NULL;
1400
0
  gint n16;
1401
0
  const gchar *in;
1402
0
  gint i;
1403
1404
0
  g_return_val_if_fail (str != NULL, NULL);
1405
1406
0
  in = str;
1407
0
  n16 = 0;
1408
0
  while ((len < 0 || str + len - in > 0) && *in)
1409
0
    {
1410
0
      gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1411
0
      if (wc & 0x80000000)
1412
0
  {
1413
0
    if (wc == (gunichar)-2)
1414
0
      {
1415
0
        if (items_read)
1416
0
    break;
1417
0
        else
1418
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1419
0
                                     _("Partial character sequence at end of input"));
1420
0
      }
1421
0
    else
1422
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1423
0
                                 _("Invalid byte sequence in conversion input"));
1424
1425
0
    goto err_out;
1426
0
  }
1427
1428
0
      if (wc < 0xd800)
1429
0
  n16 += 1;
1430
0
      else if (wc < 0xe000)
1431
0
  {
1432
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1433
0
                               _("Invalid sequence in conversion input"));
1434
1435
0
    goto err_out;
1436
0
  }
1437
0
      else if (wc < 0x10000)
1438
0
  n16 += 1;
1439
0
      else if (wc < 0x110000)
1440
0
  n16 += 2;
1441
0
      else
1442
0
  {
1443
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1444
0
                               _("Character out of range for UTF-16"));
1445
1446
0
    goto err_out;
1447
0
  }
1448
      
1449
0
      in = g_utf8_next_char (in);
1450
0
    }
1451
1452
0
  result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1453
0
  if (result == NULL)
1454
0
      goto err_out;
1455
1456
0
  in = str;
1457
0
  for (i = 0; i < n16;)
1458
0
    {
1459
0
      gunichar wc = g_utf8_get_char (in);
1460
1461
0
      if (wc < 0x10000)
1462
0
  {
1463
0
    result[i++] = wc;
1464
0
  }
1465
0
      else
1466
0
  {
1467
0
    result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1468
0
    result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1469
0
  }
1470
      
1471
0
      in = g_utf8_next_char (in);
1472
0
    }
1473
1474
0
  result[i] = 0;
1475
1476
0
  if (items_written)
1477
0
    *items_written = n16;
1478
1479
0
 err_out:
1480
0
  if (items_read)
1481
0
    *items_read = in - str;
1482
  
1483
0
  return result;
1484
0
}
1485
1486
/**
1487
 * g_ucs4_to_utf16:
1488
 * @str: (array length=len) (element-type gunichar): a UCS-4 encoded string
1489
 * @len: the maximum length (number of characters) of @str to use. 
1490
 *   If @len is negative, then the string is nul-terminated.
1491
 * @items_read: (out) (optional): location to store number of
1492
 *   bytes read, or `NULL`. If an error occurs then the index of the invalid
1493
 *   input is stored here.
1494
 * @items_written: (out) (optional): location to store number
1495
 *   of `gunichar2` written, or `NULL`. The value stored here does not include
1496
 *   the trailing nul.
1497
 * @error: location to store the error occurring, or `NULL` to ignore
1498
 *   errors. Any of the errors in [error@GLib.ConvertError] other than
1499
 *   [error@GLib.ConvertError.NO_CONVERSION] may occur.
1500
 *
1501
 * Convert a string from UCS-4 to UTF-16.
1502
 *
1503
 * A nul character (U+0000) will be added to the result after the converted text.
1504
 * 
1505
 * Returns: (transfer full): a pointer to a newly allocated UTF-16 string.
1506
 *   This value must be freed with [func@GLib.free].
1507
 */
1508
gunichar2 *
1509
g_ucs4_to_utf16 (const gunichar  *str,
1510
     glong            len,              
1511
     glong           *items_read,       
1512
     glong           *items_written,    
1513
     GError         **error)
1514
0
{
1515
0
  gunichar2 *result = NULL;
1516
0
  gint n16;
1517
0
  gint i, j;
1518
1519
0
  n16 = 0;
1520
0
  i = 0;
1521
0
  while ((len < 0 || i < len) && str[i])
1522
0
    {
1523
0
      gunichar wc = str[i];
1524
1525
0
      if (wc < 0xd800)
1526
0
  n16 += 1;
1527
0
      else if (wc < 0xe000)
1528
0
  {
1529
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1530
0
                               _("Invalid sequence in conversion input"));
1531
1532
0
    goto err_out;
1533
0
  }
1534
0
      else if (wc < 0x10000)
1535
0
  n16 += 1;
1536
0
      else if (wc < 0x110000)
1537
0
  n16 += 2;
1538
0
      else
1539
0
  {
1540
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1541
0
                               _("Character out of range for UTF-16"));
1542
1543
0
    goto err_out;
1544
0
  }
1545
1546
0
      i++;
1547
0
    }
1548
1549
0
  result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1550
0
  if (result == NULL)
1551
0
      goto err_out;
1552
1553
0
  for (i = 0, j = 0; j < n16; i++)
1554
0
    {
1555
0
      gunichar wc = str[i];
1556
1557
0
      if (wc < 0x10000)
1558
0
  {
1559
0
    result[j++] = wc;
1560
0
  }
1561
0
      else
1562
0
  {
1563
0
    result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1564
0
    result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1565
0
  }
1566
0
    }
1567
0
  result[j] = 0;
1568
1569
0
  if (items_written)
1570
0
    *items_written = n16;
1571
  
1572
0
 err_out:
1573
0
  if (items_read)
1574
0
    *items_read = i;
1575
  
1576
0
  return result;
1577
0
}
1578
1579
/**< private >
1580
 * find_invalid_or_incomplete_utf8_sequence:
1581
 *
1582
 * @string: the source string.
1583
 *
1584
 * Returns the first byte of a sequence that is either invalid
1585
 * UTF-8 or incomplete UTF-8, or a pointer to the NULL terminator
1586
 * if all of @string is valid UTF-8.
1587
 */
1588
static const char *
1589
find_invalid_or_incomplete_utf8_sequence (const char *string)
1590
0
{
1591
0
  const char *end = string;
1592
1593
0
  g_utf8_validate (string, -1, &end);
1594
1595
0
  return end;
1596
0
}
1597
1598
/**< private >
1599
 * find_valid_and_complete_utf8_sequence:
1600
 *
1601
 * @string: a NULL-terminated source string.
1602
 *
1603
 * Returns the first byte of a sequence that is valid (and complete)
1604
 * UTF-8, or a pointer to the NULL terminator if no such sequence
1605
 * could be found.
1606
 */
1607
static const char *
1608
find_valid_and_complete_utf8_sequence (const char *string)
1609
0
{
1610
0
  const unsigned char *iter = (const unsigned char *)string;
1611
1612
0
  for (;; iter++)
1613
0
    {
1614
0
      if (*iter < 128 ||
1615
0
          ((*iter & 0xC0) == 0xC0 &&
1616
0
           g_utf8_get_char_validated ((const char*)iter, -1) < (gunichar2)-2))
1617
0
        {
1618
0
          break;
1619
0
        }
1620
0
    }
1621
1622
0
  return (const char *) iter;
1623
0
}
1624
1625
1626
/**< private >
1627
 * invalidly_encoded_string_to_utf16_get_output_length:
1628
 *
1629
 * @start: start of the source string.
1630
 * @end: end of the source string (excluded).
1631
 *
1632
 * Returns the output length, as a count of gunichar2, that is necessary
1633
 * for the generic translation of an invalidly-encoded string to UTF-16.
1634
 */
1635
static size_t
1636
invalidly_encoded_string_to_utf16_get_output_length (const char *start,
1637
                                                     const char *end)
1638
0
{
1639
0
  size_t count;
1640
1641
0
  g_assert ((uintptr_t)end >= (uintptr_t)start);
1642
1643
  /* We output one gunichar2 for each input byte */
1644
0
  count = (uintptr_t)end - (uintptr_t)start;
1645
1646
0
  return count;
1647
0
}
1648
1649
/**< private >
1650
 * invalidly_encoded_string_to_utf16:
1651
 *
1652
 * @start: start of the string.
1653
 * @end: end of the string (excluded).
1654
 * @output: the output buffer. Must be long enough to hold
1655
 *          the entire output.
1656
 *
1657
 * Performs a generic conversion of an invalidly-encoded string
1658
 * to UTF-16. Note: the current implementation simply outputs
1659
 * Unicode Replacement Characters "�" (U+FFFD) for each byte in
1660
 * the source string.
1661
 */
1662
static size_t
1663
invalidly_encoded_string_to_utf16 (const char *start,
1664
                                   const char *end,
1665
                                   gunichar2  *output)
1666
0
{
1667
0
  size_t count;
1668
1669
0
  g_assert ((uintptr_t)end >= (uintptr_t)start);
1670
0
  count = (uintptr_t)end - (uintptr_t)start;
1671
1672
0
  for (size_t i = 0; i < count; i++)
1673
0
    output[i] = 0xFFFD;
1674
1675
0
  return count;
1676
0
}
1677
1678
/**< private >
1679
 * invalidly_encoded_string_to_utf16_backtrack:
1680
 *
1681
 * @start: start of the source string.
1682
 * @output_length: length within the output UTF-16 string
1683
 *                 expressed as a count of gunichar2.
1684
 *
1685
 * Backtracks an output-length in count of gunichar2 to the
1686
 * corresponding length, in bytes, of the source string.
1687
 */
1688
static size_t
1689
invalidly_encoded_string_to_utf16_backtrack (const char *start,
1690
                                             size_t      output_length)
1691
0
{
1692
  /* The conversion process outputs one gunichar2 (a complete
1693
   * character) for each input byte, so the mapping is very
1694
   * simple.
1695
   */
1696
0
  return output_length;
1697
0
}
1698
1699
1700
/**< private >
1701
 * valid_utf8_to_utf16_get_output_length:
1702
 *
1703
 * @start: start of the source string. Must be valid UTF-8.
1704
 * @end: end of the source string (excluded).
1705
 *
1706
 * Returns the output-length, in count of gunichar2, necessary for the
1707
 * translation of a valid UTF-8 string to UTF-16.
1708
 */
1709
static size_t
1710
valid_utf8_to_utf16_get_output_length (const char *start,
1711
                                       const char *end)
1712
0
{
1713
0
  size_t count = 0;
1714
1715
0
  while (start < end)
1716
0
    {
1717
0
      gunichar codepoint = g_utf8_get_char (start);
1718
1719
0
      if (codepoint <= 0xFFFF)
1720
0
        count += 1;
1721
0
      else
1722
0
        count += 2;
1723
1724
0
      start = g_utf8_next_char (start);
1725
0
    }
1726
1727
0
  g_assert (start == end);
1728
1729
0
  return count;
1730
0
}
1731
1732
/**< private >
1733
 * valid_utf8_to_utf16:
1734
 *
1735
 * @start: start of the source string. Must be valid UTF-8
1736
 * @end: end of the source string (excluded).
1737
 * @output: the output buffer. Must be long enough to hold
1738
 *          the entire output.
1739
 *
1740
 * Performs the conversion of a valid UTF-8 string to UTF-16.
1741
 */
1742
static size_t
1743
valid_utf8_to_utf16 (const char *start,
1744
                     const char *end,
1745
                     gunichar2  *output)
1746
0
{
1747
0
  size_t count = 0;
1748
1749
0
  while (start < end)
1750
0
    {
1751
0
      gunichar codepoint = g_utf8_get_char (start);
1752
1753
0
      if (codepoint <= 0xFFFF)
1754
0
        {
1755
0
          output[count++] = (gunichar2) codepoint;
1756
0
        }
1757
0
      else
1758
0
        {
1759
0
          gunichar subtract = codepoint - 0x010000;
1760
0
          output[count++] = 0xD800 + ((subtract >> 10) & 0x3FF);
1761
0
          output[count++] = 0xDC00 + (subtract & 0x3FF);
1762
0
        }
1763
1764
0
      start = g_utf8_next_char (start);
1765
0
    }
1766
1767
0
  g_assert (start == end);
1768
1769
0
  return count;
1770
0
}
1771
1772
/**< private >
1773
 * valid_utf8_to_utf16_backtrack:
1774
 *
1775
 * @start: start of the source string. Must be valid UTF-8.
1776
 * @output_length: length within the output UTF-16 string expressed
1777
 *                 as a count of gunichar2.
1778
 *
1779
 * Backtracks an output-length in count of gunichar2 to the
1780
 * corresponding length, in bytes, of the source string.
1781
 */
1782
static size_t
1783
valid_utf8_to_utf16_backtrack (const char *start,
1784
                               size_t      output_length)
1785
0
{
1786
0
  const char *iter = start;
1787
0
  size_t count = 0;
1788
1789
0
  for (; *iter != '\0'; iter = g_utf8_next_char (iter))
1790
0
    {
1791
0
      if (output_length <= count)
1792
0
        break;
1793
1794
0
      if (g_utf8_get_char (iter) <= 0xFFFF)
1795
0
        count += 1;
1796
0
      else
1797
0
        count += 2;
1798
0
    }
1799
1800
0
  return (uintptr_t)iter - (uintptr_t)start;
1801
0
}
1802
1803
1804
static size_t
1805
utf8_to_utf16_make_valid_get_output_length (const char *string)
1806
0
{
1807
0
  const char *start = string;
1808
0
  size_t count = 0;
1809
1810
0
  while (true)
1811
0
    {
1812
0
      const char *end = NULL;
1813
1814
0
      end = find_invalid_or_incomplete_utf8_sequence (start);
1815
0
      count += valid_utf8_to_utf16_get_output_length (start, end);
1816
0
      start = end;
1817
1818
0
      if (start[0] == '\0')
1819
0
        break;
1820
1821
0
      end = find_valid_and_complete_utf8_sequence (start);
1822
0
      g_assert ((uintptr_t)end > (uintptr_t)start);
1823
0
      count += invalidly_encoded_string_to_utf16_get_output_length (start, end);
1824
0
      start = end;
1825
1826
0
      if (start[0] == '\0')
1827
0
        break;
1828
0
    }
1829
1830
0
  return count;
1831
0
}
1832
1833
static size_t
1834
utf8_to_utf16_make_valid_backtrack (const char *string,
1835
                                    size_t      output_length)
1836
0
{
1837
0
  const char *start = string;
1838
0
  size_t count = 0;
1839
0
  size_t l;
1840
1841
0
  while (true)
1842
0
    {
1843
0
      const char *end = NULL;
1844
1845
0
      end = find_invalid_or_incomplete_utf8_sequence (start);
1846
0
      l = valid_utf8_to_utf16_get_output_length (start, end);
1847
0
      if (output_length < count + l)
1848
0
        return count + valid_utf8_to_utf16_backtrack (start, output_length);
1849
0
      count += (uintptr_t)end - (uintptr_t)start;
1850
0
      output_length -= l;
1851
0
      start = end;
1852
1853
0
      if (start[0] == '\0')
1854
0
        return (uintptr_t)start - (uintptr_t)string;
1855
1856
0
      end = find_valid_and_complete_utf8_sequence (start);
1857
0
      g_assert ((uintptr_t)end > (uintptr_t)start);
1858
0
      l = invalidly_encoded_string_to_utf16_get_output_length (start, end);
1859
0
      if (output_length < l)
1860
0
        return count + invalidly_encoded_string_to_utf16_backtrack (start, output_length);
1861
0
      count += (uintptr_t)end - (uintptr_t)start;
1862
0
      output_length -= l;
1863
0
      start = end;
1864
1865
0
      if (start[0] == '\0')
1866
0
        return (uintptr_t)start - (uintptr_t)string;
1867
0
    }
1868
1869
0
  return count;
1870
0
}
1871
1872
1873
static size_t
1874
utf8_to_utf16_make_valid (const char *string,
1875
                          gunichar2  *output)
1876
0
{
1877
0
  const char *start = string;
1878
0
  size_t count = 0;
1879
1880
0
  while (true)
1881
0
    {
1882
0
      const char *end = NULL;
1883
1884
0
      end = find_invalid_or_incomplete_utf8_sequence (start);
1885
0
      count += valid_utf8_to_utf16 (start, end, &output[count]);
1886
0
      start = end;
1887
1888
0
      if (start[0] == '\0')
1889
0
        break;
1890
1891
0
      end = find_valid_and_complete_utf8_sequence (start);
1892
0
      g_assert ((uintptr_t)end > (uintptr_t)start);
1893
0
      count += invalidly_encoded_string_to_utf16 (start, end, &output[count]);
1894
0
      start = end;
1895
1896
0
      if (start[0] == '\0')
1897
0
        break;
1898
0
    }
1899
1900
0
  return count;
1901
0
}
1902
1903
/** < private >
1904
 * g_utf8_to_utf16_make_valid:
1905
 *
1906
 * @utf8: source UTF-8 string. May contain invalid or incomplete sequences.
1907
 * @buffer: optional auxiliary buffer where the output UTF-16 string will be
1908
 *          stored if large enough to hold the output. Callers can pass NULL,
1909
 *          in which case the output buffer is allocated on the heap.
1910
 * @buffer_len: length, in count of gunichar2, of @buffer. This is used only
1911
 *              if @buffer is not NULL.
1912
 * @out_utf16: pointer that will be set the to output string. If @buffer is
1913
 *             long enough to hold the data, *out_utf16 will equal @buffer
1914
 *             upon return; otherwise *out_utf16 will point to heap-allocated
1915
 *             data, which must be freed using `g_free`.
1916
 * @out_utf16_len: pointer to size_t that will be set to the length of the
1917
 *                 output UTF-16 string on return, in count of gunichar2.
1918
 *                 Can be NULL.
1919
 *
1920
 * Performs conversion of an UTF-8 string that may contain invalid sequences
1921
 * to UTF-16.
1922
 *
1923
 * On return, the caller should check if *out_utf16 equals @buffer and call
1924
 * `g_free` accordingly.
1925
 */
1926
void
1927
g_utf8_to_utf16_make_valid (const char  *utf8,
1928
                            gunichar2   *buffer,
1929
                            size_t       buffer_len,
1930
                            gunichar2  **out_utf16,
1931
                            size_t      *out_utf16_len)
1932
0
{
1933
0
  size_t output_length = utf8_to_utf16_make_valid_get_output_length (utf8);
1934
1935
0
  if (output_length < buffer_len)
1936
0
    {
1937
0
      *out_utf16 = buffer;
1938
0
    }
1939
0
  else
1940
0
    {
1941
      /* output_length cannot be greater than strlen (utf8), which
1942
       * is less than SIZE_MAX since utf8 is null-terminated.
1943
       * As such, (output_length + 1) cannot overflow.
1944
       */
1945
0
      *out_utf16 = g_new (gunichar2, output_length + 1);
1946
0
    }
1947
1948
0
  utf8_to_utf16_make_valid (utf8, *out_utf16);
1949
1950
  /* Add the terminating NULL character */
1951
0
  (*out_utf16)[output_length] = L'\0';
1952
1953
0
  if (out_utf16_len)
1954
0
    *out_utf16_len = output_length;
1955
0
}
1956
1957
/** < private >
1958
 * g_utf8_to_utf16_make_valid_backtrack:
1959
 *
1960
 * @utf8: source UTF-8 string. May contain invalid or incomplete sequences.
1961
 * @utf16_len: length within the output UTF-16 string expressed as a count
1962
 *             of gunichar2.
1963
 *
1964
 * Backtracks an output-length in count of gunichar2 to the
1965
 * corresponding length, in bytes, of the source string.
1966
 */
1967
size_t
1968
g_utf8_to_utf16_make_valid_backtrack (const char  *utf8,
1969
                                      size_t       utf16_len)
1970
0
{
1971
0
  return utf8_to_utf16_make_valid_backtrack (utf8, utf16_len);
1972
0
}
1973
1974
/* SIMD-based UTF-8 validation originates in the c-utf8 project from
1975
 * https://github.com/c-util/c-utf8/ from the following authors:
1976
 *
1977
 *   David Rheinsberg <david@readahead.eu>
1978
 *   Evgeny Vereshchagin <evvers@ya.ru>
1979
 *   Jan Engelhardt <jengelh@inai.de>
1980
 *   Tom Gundersen <teg@jklm.no>
1981
 *
1982
 * It has been adapted for portability and integration.
1983
 * The original code is dual-licensed Apache-2.0 or LGPLv2.1+
1984
 */
1985
1986
2.67M
#define align_to(_val, _to) (((_val) + (_to) - 1) & ~((_to) - 1))
1987
1988
static inline guint8
1989
load_u8 (gconstpointer memory,
1990
         gsize         offset)
1991
30.8M
{
1992
30.8M
  return ((const guint8 *)memory)[offset];
1993
30.8M
}
1994
1995
#if G_GNUC_CHECK_VERSION(4,8) || defined(__clang__)
1996
22.3M
# define _attribute_aligned(n) __attribute__((aligned(n)))
1997
#elif defined(_MSC_VER)
1998
# define _attribute_aligned(n) __declspec(align(n))
1999
#else
2000
# define _attribute_aligned(n)
2001
#endif
2002
2003
static inline gsize
2004
load_word (gconstpointer memory,
2005
           gsize         offset)
2006
22.3M
{
2007
22.3M
#if GLIB_SIZEOF_VOID_P == 8
2008
22.3M
  _attribute_aligned(8) const guint8 *m = ((const guint8 *)memory) + offset;
2009
2010
22.3M
  return ((guint64)m[0] <<  0) | ((guint64)m[1] <<  8) |
2011
22.3M
         ((guint64)m[2] << 16) | ((guint64)m[3] << 24) |
2012
22.3M
         ((guint64)m[4] << 32) | ((guint64)m[5] << 40) |
2013
22.3M
         ((guint64)m[6] << 48) | ((guint64)m[7] << 56);
2014
#else
2015
  _attribute_aligned(4) const guint8 *m = ((const guint8 *)memory) + offset;
2016
2017
  return ((guint)m[0] <<  0) | ((guint)m[1] <<  8) |
2018
         ((guint)m[2] << 16) | ((guint)m[3] << 24);
2019
#endif
2020
22.3M
}
2021
2022
/* The following constants are truncated on 32-bit machines */
2023
22.3M
#define UTF8_ASCII_MASK ((gsize)0x8080808080808080L)
2024
22.3M
#define UTF8_ASCII_SUB  ((gsize)0x0101010101010101L)
2025
2026
static inline int
2027
utf8_word_is_ascii (gsize word)
2028
22.3M
{
2029
  /* True unless any byte is NULL or has the MSB set. */
2030
22.3M
  return ((((word - UTF8_ASCII_SUB) | word) & UTF8_ASCII_MASK) == 0);
2031
22.3M
}
2032
2033
static void
2034
utf8_verify_ascii (const char **strp,
2035
                   gsize       *lenp)
2036
1.78M
{
2037
1.78M
  const char *str = *strp;
2038
18.4E
  gsize len = lenp ? *lenp : strlen (str);
2039
2040
4.44M
  while (len > 0 && load_u8 (str, 0) < 128)
2041
2.67M
    {
2042
2.67M
      if ((gpointer) align_to ((guintptr) str, sizeof (gsize)) == str)
2043
1.64M
        {
2044
12.6M
          while (len >= 2 * sizeof (gsize))
2045
11.2M
            {
2046
11.2M
              if (!utf8_word_is_ascii (load_word (str, 0)) ||
2047
11.1M
                  !utf8_word_is_ascii (load_word (str, sizeof (gsize))))
2048
225k
                break;
2049
2050
11.0M
              str += 2 * sizeof(gsize);
2051
11.0M
              len -= 2 * sizeof(gsize);
2052
11.0M
            }
2053
2054
10.6M
          while (len > 0 && load_u8 (str, 0) < 128)
2055
9.05M
            {
2056
9.05M
              if G_UNLIKELY (load_u8 (str, 0) == 0x00)
2057
9.70k
                goto out;
2058
2059
9.04M
              ++str;
2060
9.04M
              --len;
2061
9.04M
            }
2062
1.64M
        }
2063
1.02M
      else
2064
1.02M
        {
2065
1.02M
          if G_UNLIKELY (load_u8 (str, 0) == 0x00)
2066
1.12k
            goto out;
2067
2068
1.02M
          ++str;
2069
1.02M
          --len;
2070
1.02M
        }
2071
2.67M
    }
2072
2073
1.78M
out:
2074
1.78M
  *strp = str;
2075
2076
1.78M
  if (lenp)
2077
1.78M
    *lenp = len;
2078
1.78M
}
2079
2080
#define UTF8_CHAR_IS_TAIL(_x) (((_x) & 0xC0) == 0x80)
2081
2082
static void
2083
utf8_verify (const char **strp,
2084
             gsize       *lenp)
2085
1.79M
{
2086
1.79M
  const char *str = *strp;
2087
1.79M
  gsize len = lenp ? *lenp : strlen (str);
2088
2089
  /* See Unicode 10.0.0, Chapter 3, Section D92 */
2090
2091
6.62M
  while (len > 0)
2092
4.95M
    {
2093
4.95M
      guint8 b = load_u8 (str, 0);
2094
2095
4.95M
      if (b == 0x00)
2096
21.3k
        goto out;
2097
2098
4.93M
      else if (b <= 0x7F)
2099
1.78M
        {
2100
          /*
2101
           * Special-case and optimize the ASCII case.
2102
           */
2103
1.78M
          utf8_verify_ascii ((const char **)&str, &len);
2104
1.78M
        }
2105
2106
3.14M
      else if (b >= 0xC2 && b <= 0xDF)
2107
2.81M
        {
2108
2.81M
          if G_UNLIKELY (len < 2)
2109
1.93k
            goto out;
2110
2.81M
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 1)))
2111
11.0k
            goto out;
2112
2113
2.80M
          str += 2;
2114
2.80M
          len -= 2;
2115
2116
2.80M
        }
2117
2118
332k
      else if (b == 0xE0)
2119
37.2k
        {
2120
37.2k
          if G_UNLIKELY (len < 3)
2121
507
            goto out;
2122
36.7k
          if G_UNLIKELY (load_u8 (str, 1) < 0xA0 || load_u8 (str, 1) > 0xBF)
2123
2.19k
            goto out;
2124
34.5k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 2)))
2125
513
            goto out;
2126
2127
34.0k
          str += 3;
2128
34.0k
          len -= 3;
2129
34.0k
        }
2130
2131
295k
      else if (b >= 0xE1 && b <= 0xEC)
2132
89.4k
        {
2133
89.4k
          if G_UNLIKELY (len < 3)
2134
2.07k
            goto out;
2135
87.3k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 1)))
2136
2.39k
            goto out;
2137
84.9k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 2)))
2138
1.00k
            goto out;
2139
2140
83.9k
          str += 3;
2141
83.9k
          len -= 3;
2142
83.9k
        }
2143
2144
206k
      else if (b == 0xED)
2145
9.02k
        {
2146
9.02k
          if G_UNLIKELY (len < 3)
2147
972
            goto out;
2148
8.05k
          if G_UNLIKELY (load_u8 (str, 1) < 0x80 || load_u8 (str, 1) > 0x9F)
2149
1.46k
            goto out;
2150
6.59k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 2)))
2151
605
            goto out;
2152
2153
5.98k
          str += 3;
2154
5.98k
          len -= 3;
2155
5.98k
        }
2156
2157
196k
      else if (b >= 0xEE && b <= 0xEF)
2158
38.0k
        {
2159
38.0k
          if G_UNLIKELY (len < 3)
2160
1.38k
            goto out;
2161
36.6k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 1)))
2162
1.15k
            goto out;
2163
35.4k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 2)))
2164
1.06k
            goto out;
2165
2166
34.4k
          str += 3;
2167
34.4k
          len -= 3;
2168
34.4k
        }
2169
2170
158k
      else if (b == 0xF0)
2171
33.4k
        {
2172
33.4k
          if G_UNLIKELY (len < 4)
2173
550
            goto out;
2174
32.8k
          if G_UNLIKELY (load_u8 (str, 1) < 0x90 || load_u8 (str, 1) > 0xBF)
2175
1.94k
            goto out;
2176
30.9k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 2)))
2177
693
            goto out;
2178
30.2k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 3)))
2179
709
            goto out;
2180
2181
29.5k
          str += 4;
2182
29.5k
          len -= 4;
2183
29.5k
        }
2184
2185
125k
      else if (b >= 0xF1 && b <= 0xF3)
2186
56.1k
        {
2187
56.1k
          if G_UNLIKELY (len < 4)
2188
1.02k
            goto out;
2189
55.0k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 1)))
2190
1.15k
            goto out;
2191
53.9k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 2)))
2192
908
            goto out;
2193
53.0k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 3)))
2194
800
            goto out;
2195
2196
52.2k
          str += 4;
2197
52.2k
          len -= 4;
2198
52.2k
        }
2199
2200
69.4k
      else if (b == 0xF4)
2201
7.08k
        {
2202
7.08k
          if G_UNLIKELY (len < 4)
2203
735
            goto out;
2204
6.34k
          if G_UNLIKELY (load_u8 (str, 1) < 0x80 || load_u8 (str, 1) > 0x8F)
2205
1.46k
            goto out;
2206
4.88k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 2)))
2207
595
            goto out;
2208
4.29k
          if G_UNLIKELY (!UTF8_CHAR_IS_TAIL (load_u8 (str, 3)))
2209
347
            goto out;
2210
2211
3.94k
          str += 4;
2212
3.94k
          len -= 4;
2213
3.94k
        }
2214
2215
62.3k
      else goto out;
2216
4.95M
    }
2217
2218
1.79M
out:
2219
1.79M
  *strp = str;
2220
2221
1.79M
  if (lenp)
2222
1.79M
    *lenp = len;
2223
1.79M
}
2224
2225
/**
2226
 * g_utf8_validate:
2227
 * @str: (array length=max_len) (element-type guint8): a pointer to character data
2228
 * @max_len: max bytes to validate, or `-1` to go until nul
2229
 * @end: (out) (optional) (transfer none) (array zero-terminated=1) (element-type guint8): return location for end of valid data
2230
 * 
2231
 * Validates UTF-8 encoded text.
2232
 *
2233
 * @str is the text to validate; if @str is nul-terminated, then @max_len can be
2234
 * `-1`, otherwise @max_len should be the number of bytes to validate.
2235
 *
2236
 * If @end is non-`NULL`, then the end of the valid range will be stored there.
2237
 * This is the first byte of the first invalid character if some bytes were
2238
 * invalid, or the end of the text being validated otherwise — either the
2239
 * trailing nul byte, or the first byte beyond @max_len (if it’s positive).
2240
 *
2241
 * Note that `g_utf8_validate()` returns `FALSE` if @max_len is  positive and
2242
 * any of the @max_len bytes are nul.
2243
 *
2244
 * Returns `TRUE` if all of @str was valid. Many GLib and GTK
2245
 * routines require valid UTF-8 as input; so data read from a file
2246
 * or the network should be checked with `g_utf8_validate()` before
2247
 * doing anything else with it.
2248
 * 
2249
 * Returns: `TRUE` if the text was valid UTF-8
2250
 */
2251
gboolean
2252
g_utf8_validate (const char   *str,
2253
                 gssize        max_len,
2254
                 const gchar **end)
2255
1.79M
{
2256
1.79M
  size_t max_len_unsigned = (max_len >= 0) ? (size_t) max_len : strlen (str);
2257
2258
1.79M
  return g_utf8_validate_len (str, max_len_unsigned, end);
2259
1.79M
}
2260
2261
/**
2262
 * g_utf8_validate_len:
2263
 * @str: (array length=max_len) (element-type guint8): a pointer to character data
2264
 * @max_len: max bytes to validate
2265
 * @end: (out) (optional) (transfer none) (array zero-terminated=1) (element-type guint8): return location for end of valid data
2266
 *
2267
 * Validates UTF-8 encoded text.
2268
 *
2269
 * As with [func@GLib.utf8_validate], but @max_len must be set, and hence this
2270
 * function will always return `FALSE` if any of the bytes of @str are nul.
2271
 *
2272
 * Returns: `TRUE` if the text was valid UTF-8
2273
 * Since: 2.60
2274
 */
2275
gboolean
2276
g_utf8_validate_len (const char   *str,
2277
                     gsize         max_len,
2278
                     const gchar **end)
2279
2280
1.79M
{
2281
1.79M
  utf8_verify (&str, &max_len);
2282
2283
1.79M
  if (end != NULL)
2284
46.8k
    *end = str;
2285
2286
1.79M
  return max_len == 0;
2287
1.79M
}
2288
2289
/**
2290
 * g_str_is_ascii:
2291
 * @str: a string
2292
 *
2293
 * Determines if a string is pure ASCII. A string is pure ASCII if it
2294
 * contains no bytes with the high bit set.
2295
 *
2296
 * Returns: true if @str is ASCII
2297
 *
2298
 * Since: 2.40
2299
 */
2300
gboolean
2301
g_str_is_ascii (const gchar *str)
2302
0
{
2303
0
  utf8_verify_ascii (&str, NULL);
2304
2305
0
  return *str == 0;
2306
0
}
2307
2308
/**
2309
 * g_unichar_validate:
2310
 * @ch: a Unicode character
2311
 * 
2312
 * Checks whether @ch is a valid Unicode character.
2313
 *
2314
 * Some possible integer values of @ch will not be valid. U+0000 is considered a
2315
 * valid character, though it’s normally a string terminator.
2316
 * 
2317
 * Returns: `TRUE` if @ch is a valid Unicode character
2318
 **/
2319
gboolean
2320
g_unichar_validate (gunichar ch)
2321
0
{
2322
0
  return UNICODE_VALID (ch);
2323
0
}
2324
2325
/**
2326
 * g_utf8_strreverse:
2327
 * @str: a UTF-8 encoded string
2328
 * @len: the maximum length of @str to use, in bytes. If @len is negative,
2329
 *   then the string is nul-terminated.
2330
 *
2331
 * Reverses a UTF-8 string.
2332
 *
2333
 * @str must be valid UTF-8 encoded text. (Use [func@GLib.utf8_validate] on all
2334
 * text before trying to use UTF-8 utility functions with it.)
2335
 *
2336
 * This function is intended for programmatic uses of reversed strings.
2337
 * It pays no attention to decomposed characters, combining marks, byte 
2338
 * order marks, directional indicators (LRM, LRO, etc) and similar 
2339
 * characters which might need special handling when reversing a string 
2340
 * for display purposes.
2341
 *
2342
 * Note that unlike [func@GLib.strreverse], this function returns
2343
 * newly-allocated memory, which should be freed with [func@GLib.free] when
2344
 * no longer needed. 
2345
 *
2346
 * Returns: (transfer full): a newly-allocated string which is the reverse of @str
2347
 *
2348
 * Since: 2.2
2349
 */
2350
gchar *
2351
g_utf8_strreverse (const gchar *str,
2352
       gssize       len)
2353
0
{
2354
0
  gchar *r, *result;
2355
0
  const gchar *p;
2356
2357
0
  if (len < 0)
2358
0
    len = strlen (str);
2359
2360
0
  result = g_new (gchar, len + 1);
2361
0
  r = result + len;
2362
0
  p = str;
2363
0
  while (r > result)
2364
0
    {
2365
0
      gchar *m, skip = g_utf8_skip[*(guchar*) p];
2366
0
      r -= skip;
2367
0
      g_assert (r >= result);
2368
0
      for (m = r; skip; skip--)
2369
0
        *m++ = *p++;
2370
0
    }
2371
0
  result[len] = 0;
2372
2373
0
  return result;
2374
0
}
2375
2376
/**
2377
 * g_utf8_make_valid:
2378
 * @str: string to coerce into UTF-8
2379
 * @len: the maximum length of @str to use, in bytes. If @len is negative,
2380
 *   then the string is nul-terminated.
2381
 *
2382
 * If the provided string is valid UTF-8, return a copy of it. If not,
2383
 * return a copy in which bytes that could not be interpreted as valid Unicode
2384
 * are replaced with the Unicode replacement character (U+FFFD).
2385
 *
2386
 * For example, this is an appropriate function to use if you have received
2387
 * a string that was incorrectly declared to be UTF-8, and you need a valid
2388
 * UTF-8 version of it that can be logged or displayed to the user, with the
2389
 * assumption that it is close enough to ASCII or UTF-8 to be mostly
2390
 * readable as-is.
2391
 *
2392
 * Returns: (transfer full): a valid UTF-8 string whose content resembles @str
2393
 *
2394
 * Since: 2.52
2395
 */
2396
gchar *
2397
g_utf8_make_valid (const gchar *str,
2398
                   gssize       len)
2399
0
{
2400
0
  GString *string;
2401
0
  const gchar *remainder, *invalid;
2402
0
  gsize remaining_bytes, valid_bytes;
2403
2404
0
  g_return_val_if_fail (str != NULL, NULL);
2405
2406
0
  if (len < 0)
2407
0
    len = strlen (str);
2408
2409
0
  string = NULL;
2410
0
  remainder = str;
2411
0
  remaining_bytes = len;
2412
2413
0
  while (remaining_bytes != 0) 
2414
0
    {
2415
0
      if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
2416
0
  break;
2417
0
      valid_bytes = invalid - remainder;
2418
    
2419
0
      if (string == NULL) 
2420
0
  string = g_string_sized_new (remaining_bytes);
2421
2422
0
      g_string_append_len (string, remainder, valid_bytes);
2423
      /* append U+FFFD REPLACEMENT CHARACTER */
2424
0
      g_string_append (string, "\357\277\275");
2425
      
2426
0
      remaining_bytes -= valid_bytes + 1;
2427
0
      remainder = invalid + 1;
2428
0
    }
2429
  
2430
0
  if (string == NULL)
2431
0
    return g_strndup (str, len);
2432
  
2433
0
  g_string_append_len (string, remainder, remaining_bytes);
2434
0
  g_string_append_c (string, '\0');
2435
2436
0
  g_assert (g_utf8_validate (string->str, -1, NULL));
2437
2438
0
  return g_string_free (string, FALSE);
2439
0
}