Coverage Report

Created: 2018-09-25 13:52

/src/glib/glib/gutf8.c
Line
Count
Source (jump to first uncovered line)
1
/* gutf8.c - Operations on UTF-8 strings.
2
 *
3
 * Copyright (C) 1999 Tom Tromey
4
 * Copyright (C) 2000 Red Hat, Inc.
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
#include "config.h"
21
22
#include <stdlib.h>
23
#ifdef HAVE_CODESET
24
#include <langinfo.h>
25
#endif
26
#include <string.h>
27
28
#ifdef G_PLATFORM_WIN32
29
#include <stdio.h>
30
#define STRICT
31
#include <windows.h>
32
#undef STRICT
33
#endif
34
35
#include "gconvert.h"
36
#include "ghash.h"
37
#include "gstrfuncs.h"
38
#include "gtestutils.h"
39
#include "gtypes.h"
40
#include "gthread.h"
41
#include "glibintl.h"
42
43
#define UTF8_COMPUTE(Char, Mask, Len)               \
44
13.1k
  if (Char < 128)                   \
45
13.1k
    {                       \
46
7.33k
      Len = 1;                      \
47
7.33k
      Mask = 0x7f;                    \
48
7.33k
    }                        \
49
13.1k
  else if ((Char & 0xe0) == 0xc0)               \
50
5.78k
    {                       \
51
3.07k
      Len = 2;                      \
52
3.07k
      Mask = 0x1f;                    \
53
3.07k
    }                        \
54
5.78k
  else if ((Char & 0xf0) == 0xe0)               \
55
2.71k
    {                       \
56
1.26k
      Len = 3;                      \
57
1.26k
      Mask = 0x0f;                    \
58
1.26k
    }                        \
59
2.71k
  else if ((Char & 0xf8) == 0xf0)               \
60
1.44k
    {                       \
61
1.44k
      Len = 4;                      \
62
1.44k
      Mask = 0x07;                    \
63
1.44k
    }                        \
64
1.44k
  else if ((Char & 0xfc) == 0xf8)               \
65
0
    {                       \
66
0
      Len = 5;                      \
67
0
      Mask = 0x03;                    \
68
0
    }                        \
69
0
  else if ((Char & 0xfe) == 0xfc)               \
70
0
    {                       \
71
0
      Len = 6;                      \
72
0
      Mask = 0x01;                    \
73
0
    }                        \
74
0
  else                        \
75
0
    Len = -1;
76
77
#define UTF8_LENGTH(Char)              \
78
0
  ((Char) < 0x80 ? 1 :                 \
79
0
   ((Char) < 0x800 ? 2 :               \
80
0
    ((Char) < 0x10000 ? 3 :            \
81
0
     ((Char) < 0x200000 ? 4 :          \
82
0
      ((Char) < 0x4000000 ? 5 : 6)))))
83
   
84
85
#define UTF8_GET(Result, Chars, Count, Mask, Len)           \
86
13.1k
  (Result) = (Chars)[0] & (Mask);               \
87
23.0k
  for ((Count) = 1; (Count) < (Len); ++(Count))             \
88
13.1k
    {                       \
89
9.93k
      if (((Chars)[(Count)] & 0xc0) != 0x80)             \
90
9.93k
  {                     \
91
0
    (Result) = -1;                  \
92
0
    break;                    \
93
0
  }                      \
94
9.93k
      (Result) <<= 6;                   \
95
9.93k
      (Result) |= ((Chars)[(Count)] & 0x3f);              \
96
9.93k
    }
97
    
98
/*
99
 * Check whether a Unicode (5.2) char is in a valid range.
100
 *
101
 * The first check comes from the Unicode guarantee to never encode
102
 * a point above 0x0010ffff, since UTF-16 couldn't represent it.
103
 * 
104
 * The second check covers surrogate pairs (category Cs).
105
 *
106
 * @param Char the character
107
 */
108
#define UNICODE_VALID(Char)                   \
109
95.2M
    ((Char) < 0x110000 &&                     \
110
95.2M
     (((Char) & 0xFFFFF800) != 0xD800))
111
112
    
113
static const gchar utf8_skip_data[256] = {
114
  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,
115
  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,
116
  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,
117
  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,
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
  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,
121
  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
122
};
123
124
const gchar * const g_utf8_skip = utf8_skip_data;
125
126
/**
127
 * g_utf8_find_prev_char:
128
 * @str: pointer to the beginning of a UTF-8 encoded string
129
 * @p: pointer to some position within @str
130
 * 
131
 * Given a position @p with a UTF-8 encoded string @str, find the start
132
 * of the previous UTF-8 character starting before @p. Returns %NULL if no
133
 * UTF-8 characters are present in @str before @p.
134
 *
135
 * @p does not have to be at the beginning of a UTF-8 character. No check
136
 * is made to see if the character found is actually valid other than
137
 * it starts with an appropriate byte.
138
 *
139
 * Returns: a pointer to the found character or %NULL.
140
 */
141
gchar *
142
g_utf8_find_prev_char (const char *str,
143
           const char *p)
144
0
{
145
0
  for (--p; p >= str; --p)
146
0
    {
147
0
      if ((*p & 0xc0) != 0x80)
148
0
  return (gchar *)p;
149
0
    }
150
0
  return NULL;
151
0
}
152
153
/**
154
 * g_utf8_find_next_char:
155
 * @p: a pointer to a position within a UTF-8 encoded string
156
 * @end: (nullable): a pointer to the byte following the end of the string,
157
 *     or %NULL to indicate that the string is nul-terminated
158
 *
159
 * Finds the start of the next UTF-8 character in the string after @p.
160
 *
161
 * @p does not have to be at the beginning of a UTF-8 character. No check
162
 * is made to see if the character found is actually valid other than
163
 * it starts with an appropriate byte.
164
 * 
165
 * If @end is %NULL, the return value will never be %NULL: if the end of the
166
 * string is reached, a pointer to the terminating nul byte is returned. If
167
 * @end is non-%NULL, the return value will be %NULL if the end of the string
168
 * is reached.
169
 *
170
 * Returns: (nullable): a pointer to the found character or %NULL if @end is
171
 *    set and is reached
172
 */
173
gchar *
174
g_utf8_find_next_char (const gchar *p,
175
           const gchar *end)
176
9.10M
{
177
9.10M
  if (end)
178
0
    {
179
0
      for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
180
0
        ;
181
0
      return (p >= end) ? NULL : (gchar *)p;
182
0
    }
183
9.10M
  else
184
9.10M
    {
185
9.84M
      for (++p; (*p & 0xc0) == 0x80; ++p)
186
737k
        ;
187
9.10M
      return (gchar *)p;
188
9.10M
    }
189
9.10M
}
190
191
/**
192
 * g_utf8_prev_char:
193
 * @p: a pointer to a position within a UTF-8 encoded string
194
 *
195
 * Finds the previous UTF-8 character in the string before @p.
196
 *
197
 * @p does not have to be at the beginning of a UTF-8 character. No check
198
 * is made to see if the character found is actually valid other than
199
 * it starts with an appropriate byte. If @p might be the first
200
 * character of the string, you must use g_utf8_find_prev_char() instead.
201
 * 
202
 * Returns: a pointer to the found character
203
 */
204
gchar *
205
g_utf8_prev_char (const gchar *p)
206
0
{
207
0
  while (TRUE)
208
0
    {
209
0
      p--;
210
0
      if ((*p & 0xc0) != 0x80)
211
0
  return (gchar *)p;
212
0
    }
213
0
}
214
 
215
/**
216
 * g_utf8_strlen:
217
 * @p: pointer to the start of a UTF-8 encoded string
218
 * @max: the maximum number of bytes to examine. If @max
219
 *       is less than 0, then the string is assumed to be
220
 *       nul-terminated. If @max is 0, @p will not be examined and
221
 *       may be %NULL. If @max is greater than 0, up to @max
222
 *       bytes are examined
223
 *
224
 * Computes the length of the string in characters, not including
225
 * the terminating nul character. If the @max'th byte falls in the
226
 * middle of a character, the last (partial) character is not counted.
227
 *
228
 * Returns: the length of the string in characters
229
 */
230
glong
231
g_utf8_strlen (const gchar *p,
232
               gssize       max)
233
0
{
234
0
  glong len = 0;
235
0
  const gchar *start = p;
236
0
  g_return_val_if_fail (p != NULL || max == 0, 0);
237
0
238
0
  if (max < 0)
239
0
    {
240
0
      while (*p)
241
0
        {
242
0
          p = g_utf8_next_char (p);
243
0
          ++len;
244
0
        }
245
0
    }
246
0
  else
247
0
    {
248
0
      if (max == 0 || !*p)
249
0
        return 0;
250
0
251
0
      p = g_utf8_next_char (p);
252
0
253
0
      while (p - start < max && *p)
254
0
        {
255
0
          ++len;
256
0
          p = g_utf8_next_char (p);
257
0
        }
258
0
259
0
      /* only do the last len increment if we got a complete
260
0
       * char (don't count partial chars)
261
0
       */
262
0
      if (p - start <= max)
263
0
        ++len;
264
0
    }
265
0
266
0
  return len;
267
0
}
268
269
/**
270
 * g_utf8_substring:
271
 * @str: a UTF-8 encoded string
272
 * @start_pos: a character offset within @str
273
 * @end_pos: another character offset within @str
274
 *
275
 * Copies a substring out of a UTF-8 encoded string.
276
 * The substring will contain @end_pos - @start_pos characters.
277
 *
278
 * Returns: a newly allocated copy of the requested
279
 *     substring. Free with g_free() when no longer needed.
280
 *
281
 * Since: 2.30
282
 */
283
gchar *
284
g_utf8_substring (const gchar *str,
285
                  glong        start_pos,
286
                  glong        end_pos)
287
0
{
288
0
  gchar *start, *end, *out;
289
0
290
0
  start = g_utf8_offset_to_pointer (str, start_pos);
291
0
  end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
292
0
293
0
  out = g_malloc (end - start + 1);
294
0
  memcpy (out, start, end - start);
295
0
  out[end - start] = 0;
296
0
297
0
  return out;
298
0
}
299
300
/**
301
 * g_utf8_get_char:
302
 * @p: a pointer to Unicode character encoded as UTF-8
303
 * 
304
 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
305
 *
306
 * If @p does not point to a valid UTF-8 encoded character, results
307
 * are undefined. If you are not sure that the bytes are complete
308
 * valid Unicode characters, you should use g_utf8_get_char_validated()
309
 * instead.
310
 * 
311
 * Returns: the resulting character
312
 */
313
gunichar
314
g_utf8_get_char (const gchar *p)
315
13.1k
{
316
13.1k
  int i, mask = 0, len;
317
13.1k
  gunichar result;
318
13.1k
  unsigned char c = (unsigned char) *p;
319
13.1k
320
13.1k
  UTF8_COMPUTE (c, mask, len);
321
13.1k
  if (len == -1)
322
0
    return (gunichar)-1;
323
13.1k
  UTF8_GET (result, p, i, mask, len);
324
13.1k
325
13.1k
  return result;
326
13.1k
}
327
328
/**
329
 * g_utf8_offset_to_pointer:
330
 * @str: a UTF-8 encoded string
331
 * @offset: a character offset within @str
332
 *
333
 * Converts from an integer character offset to a pointer to a position
334
 * within the string.
335
 *
336
 * Since 2.10, this function allows to pass a negative @offset to
337
 * step backwards. It is usually worth stepping backwards from the end
338
 * instead of forwards if @offset is in the last fourth of the string,
339
 * since moving forward is about 3 times faster than moving backward.
340
 *
341
 * Note that this function doesn't abort when reaching the end of @str.
342
 * Therefore you should be sure that @offset is within string boundaries
343
 * before calling that function. Call g_utf8_strlen() when unsure.
344
 * This limitation exists as this function is called frequently during
345
 * text rendering and therefore has to be as fast as possible.
346
 *
347
 * Returns: the resulting pointer
348
 */
349
gchar *
350
g_utf8_offset_to_pointer  (const gchar *str,
351
         glong        offset)
352
0
{
353
0
  const gchar *s = str;
354
0
355
0
  if (offset > 0) 
356
0
    while (offset--)
357
0
      s = g_utf8_next_char (s);
358
0
  else
359
0
    {
360
0
      const char *s1;
361
0
362
0
      /* This nice technique for fast backwards stepping 
363
0
       * through a UTF-8 string was dubbed "stutter stepping" 
364
0
       * by its inventor, Larry Ewing.
365
0
       */
366
0
      while (offset)
367
0
  {
368
0
    s1 = s;
369
0
    s += offset;
370
0
    while ((*s & 0xc0) == 0x80)
371
0
      s--;
372
0
373
0
    offset += g_utf8_pointer_to_offset (s, s1);
374
0
  }
375
0
    }
376
0
377
0
  return (gchar *)s;
378
0
}
379
380
/**
381
 * g_utf8_pointer_to_offset:
382
 * @str: a UTF-8 encoded string
383
 * @pos: a pointer to a position within @str
384
 * 
385
 * Converts from a pointer to position within a string to a integer
386
 * character offset.
387
 *
388
 * Since 2.10, this function allows @pos to be before @str, and returns
389
 * a negative offset in this case.
390
 * 
391
 * Returns: the resulting character offset
392
 */
393
glong    
394
g_utf8_pointer_to_offset (const gchar *str,
395
        const gchar *pos)
396
0
{
397
0
  const gchar *s = str;
398
0
  glong offset = 0;    
399
0
400
0
  if (pos < str) 
401
0
    offset = - g_utf8_pointer_to_offset (pos, str);
402
0
  else
403
0
    while (s < pos)
404
0
      {
405
0
  s = g_utf8_next_char (s);
406
0
  offset++;
407
0
      }
408
0
  
409
0
  return offset;
410
0
}
411
412
413
/**
414
 * g_utf8_strncpy:
415
 * @dest: buffer to fill with characters from @src
416
 * @src: UTF-8 encoded string
417
 * @n: character count
418
 * 
419
 * Like the standard C strncpy() function, but copies a given number
420
 * of characters instead of a given number of bytes. The @src string
421
 * must be valid UTF-8 encoded text. (Use g_utf8_validate() on all
422
 * text before trying to use UTF-8 utility functions with it.)
423
 * 
424
 * Note you must ensure @dest is at least 4 * @n to fit the
425
 * largest possible UTF-8 characters
426
 *
427
 * Returns: @dest
428
 */
429
gchar *
430
g_utf8_strncpy (gchar       *dest,
431
    const gchar *src,
432
    gsize        n)
433
0
{
434
0
  const gchar *s = src;
435
0
  while (n && *s)
436
0
    {
437
0
      s = g_utf8_next_char(s);
438
0
      n--;
439
0
    }
440
0
  strncpy(dest, src, s - src);
441
0
  dest[s - src] = 0;
442
0
  return dest;
443
0
}
444
445
/* unicode_strchr */
446
447
/**
448
 * g_unichar_to_utf8:
449
 * @c: a Unicode character code
450
 * @outbuf: (out caller-allocates) (optional): output buffer, must have at
451
 *       least 6 bytes of space. If %NULL, the length will be computed and
452
 *       returned and nothing will be written to @outbuf.
453
 * 
454
 * Converts a single character to UTF-8.
455
 * 
456
 * Returns: number of bytes written
457
 */
458
int
459
g_unichar_to_utf8 (gunichar c,
460
       gchar   *outbuf)
461
6.21M
{
462
6.21M
  /* If this gets modified, also update the copy in g_string_insert_unichar() */
463
6.21M
  guint len = 0;    
464
6.21M
  int first;
465
6.21M
  int i;
466
6.21M
467
6.21M
  if (c < 0x80)
468
6.21M
    {
469
6.21M
      first = 0;
470
6.21M
      len = 1;
471
6.21M
    }
472
2.31k
  else if (c < 0x800)
473
567
    {
474
567
      first = 0xc0;
475
567
      len = 2;
476
567
    }
477
1.74k
  else if (c < 0x10000)
478
1.05k
    {
479
1.05k
      first = 0xe0;
480
1.05k
      len = 3;
481
1.05k
    }
482
687
   else if (c < 0x200000)
483
543
    {
484
543
      first = 0xf0;
485
543
      len = 4;
486
543
    }
487
144
  else if (c < 0x4000000)
488
30
    {
489
30
      first = 0xf8;
490
30
      len = 5;
491
30
    }
492
114
  else
493
114
    {
494
114
      first = 0xfc;
495
114
      len = 6;
496
114
    }
497
6.21M
498
6.21M
  if (outbuf)
499
6.21M
    {
500
6.22M
      for (i = len - 1; i > 0; --i)
501
4.99k
  {
502
4.99k
    outbuf[i] = (c & 0x3f) | 0x80;
503
4.99k
    c >>= 6;
504
4.99k
  }
505
6.21M
      outbuf[0] = c | first;
506
6.21M
    }
507
6.21M
508
6.21M
  return len;
509
6.21M
}
510
511
/**
512
 * g_utf8_strchr:
513
 * @p: a nul-terminated UTF-8 encoded string
514
 * @len: the maximum length of @p
515
 * @c: a Unicode character
516
 * 
517
 * Finds the leftmost occurrence of the given Unicode character
518
 * in a UTF-8 encoded string, while limiting the search to @len bytes.
519
 * If @len is -1, allow unbounded search.
520
 * 
521
 * Returns: %NULL if the string does not contain the character, 
522
 *     otherwise, a pointer to the start of the leftmost occurrence
523
 *     of the character in the string.
524
 */
525
gchar *
526
g_utf8_strchr (const char *p,
527
         gssize      len,
528
         gunichar    c)
529
6.21M
{
530
6.21M
  gchar ch[10];
531
6.21M
532
6.21M
  gint charlen = g_unichar_to_utf8 (c, ch);
533
6.21M
  ch[charlen] = '\0';
534
6.21M
  
535
6.21M
  return g_strstr_len (p, len, ch);
536
6.21M
}
537
538
539
/**
540
 * g_utf8_strrchr:
541
 * @p: a nul-terminated UTF-8 encoded string
542
 * @len: the maximum length of @p
543
 * @c: a Unicode character
544
 * 
545
 * Find the rightmost occurrence of the given Unicode character
546
 * in a UTF-8 encoded string, while limiting the search to @len bytes.
547
 * If @len is -1, allow unbounded search.
548
 * 
549
 * Returns: %NULL if the string does not contain the character, 
550
 *     otherwise, a pointer to the start of the rightmost occurrence
551
 *     of the character in the string.
552
 */
553
gchar *
554
g_utf8_strrchr (const char *p,
555
    gssize      len,
556
    gunichar    c)
557
0
{
558
0
  gchar ch[10];
559
0
560
0
  gint charlen = g_unichar_to_utf8 (c, ch);
561
0
  ch[charlen] = '\0';
562
0
  
563
0
  return g_strrstr_len (p, len, ch);
564
0
}
565
566
567
/* Like g_utf8_get_char, but take a maximum length
568
 * and return (gunichar)-2 on incomplete trailing character;
569
 * also check for malformed or overlong sequences
570
 * and return (gunichar)-1 in this case.
571
 */
572
static inline gunichar
573
g_utf8_get_char_extended (const  gchar *p,
574
        gssize max_len)
575
95.2M
{
576
95.2M
  guint i, len;
577
95.2M
  gunichar min_code;
578
95.2M
  gunichar wc = (guchar) *p;
579
95.2M
  const gunichar partial_sequence = (gunichar) -2;
580
95.2M
  const gunichar malformed_sequence = (gunichar) -1;
581
95.2M
582
95.2M
  if (wc < 0x80)
583
95.2M
    {
584
95.2M
      return wc;
585
95.2M
    }
586
5.88k
  else if (G_UNLIKELY (wc < 0xc0))
587
5.88k
    {
588
20
      return malformed_sequence;
589
20
    }
590
5.86k
  else if (wc < 0xe0)
591
541
    {
592
541
      len = 2;
593
541
      wc &= 0x1f;
594
541
      min_code = 1 << 7;
595
541
    }
596
5.32k
  else if (wc < 0xf0)
597
1.02k
    {
598
1.02k
      len = 3;
599
1.02k
      wc &= 0x0f;
600
1.02k
      min_code = 1 << 11;
601
1.02k
    }
602
4.29k
  else if (wc < 0xf8)
603
4.23k
    {
604
4.23k
      len = 4;
605
4.23k
      wc &= 0x07;
606
4.23k
      min_code = 1 << 16;
607
4.23k
    }
608
63
  else if (wc < 0xfc)
609
26
    {
610
26
      len = 5;
611
26
      wc &= 0x03;
612
26
      min_code = 1 << 21;
613
26
    }
614
37
  else if (wc < 0xfe)
615
29
    {
616
29
      len = 6;
617
29
      wc &= 0x01;
618
29
      min_code = 1 << 26;
619
29
    }
620
8
  else
621
8
    {
622
8
      return malformed_sequence;
623
8
    }
624
5.85k
625
5.85k
  if (G_UNLIKELY (max_len >= 0 && len > max_len))
626
5.85k
    {
627
0
      for (i = 1; i < max_len; i++)
628
0
  {
629
0
    if ((((guchar *)p)[i] & 0xc0) != 0x80)
630
0
      return malformed_sequence;
631
0
  }
632
0
      return partial_sequence;
633
5.85k
    }
634
5.85k
635
21.2k
  for (i = 1; i < len; ++i)
636
15.4k
    {
637
15.4k
      gunichar ch = ((guchar *)p)[i];
638
15.4k
639
15.4k
      if (G_UNLIKELY ((ch & 0xc0) != 0x80))
640
15.4k
  {
641
74
    if (ch)
642
25
      return malformed_sequence;
643
49
    else
644
49
      return partial_sequence;
645
15.3k
  }
646
15.3k
647
15.3k
      wc <<= 6;
648
15.3k
      wc |= (ch & 0x3f);
649
15.3k
    }
650
5.85k
651
5.85k
  if (G_UNLIKELY (wc < min_code))
652
5.78k
    return malformed_sequence;
653
5.78k
654
5.78k
  return wc;
655
5.78k
}
656
657
/**
658
 * g_utf8_get_char_validated:
659
 * @p: a pointer to Unicode character encoded as UTF-8
660
 * @max_len: the maximum number of bytes to read, or -1 if @p is nul-terminated
661
 *
662
 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
663
 * This function checks for incomplete characters, for invalid characters
664
 * such as characters that are out of the range of Unicode, and for
665
 * overlong encodings of valid characters.
666
 *
667
 * Note that g_utf8_get_char_validated() returns (gunichar)-2 if
668
 * @max_len is positive and any of the bytes in the first UTF-8 character
669
 * sequence are nul.
670
 * 
671
 * Returns: the resulting character. If @p points to a partial
672
 *     sequence at the end of a string that could begin a valid 
673
 *     character (or if @max_len is zero), returns (gunichar)-2; 
674
 *     otherwise, if @p does not point to a valid UTF-8 encoded 
675
 *     Unicode character, returns (gunichar)-1.
676
 */
677
gunichar
678
g_utf8_get_char_validated (const gchar *p,
679
         gssize       max_len)
680
95.2M
{
681
95.2M
  gunichar result;
682
95.2M
683
95.2M
  if (max_len == 0)
684
0
    return (gunichar)-2;
685
95.2M
686
95.2M
  result = g_utf8_get_char_extended (p, max_len);
687
95.2M
688
95.2M
  if (result & 0x80000000)
689
104
    return result;
690
95.2M
  else if (!UNICODE_VALID (result))
691
95.2M
    return (gunichar)-1;
692
95.2M
  else
693
95.2M
    return result;
694
95.2M
}
695
696
0
#define CONT_BYTE_FAST(p) ((guchar)*p++ & 0x3f)
697
698
/**
699
 * g_utf8_to_ucs4_fast:
700
 * @str: a UTF-8 encoded string
701
 * @len: the maximum length of @str to use, in bytes. If @len < 0,
702
 *     then the string is nul-terminated.
703
 * @items_written: (out caller-allocates) (optional): location to store the
704
 *     number of characters in the result, or %NULL.
705
 *
706
 * Convert a string from UTF-8 to a 32-bit fixed width
707
 * representation as UCS-4, assuming valid UTF-8 input.
708
 * This function is roughly twice as fast as g_utf8_to_ucs4()
709
 * but does no error checking on the input. A trailing 0 character
710
 * will be added to the string after the converted text.
711
 * 
712
 * Returns: a pointer to a newly allocated UCS-4 string.
713
 *     This value must be freed with g_free().
714
 */
715
gunichar *
716
g_utf8_to_ucs4_fast (const gchar *str,
717
         glong        len,              
718
         glong       *items_written)    
719
0
{
720
0
  gunichar *result;
721
0
  gint n_chars, i;
722
0
  const gchar *p;
723
0
724
0
  g_return_val_if_fail (str != NULL, NULL);
725
0
726
0
  p = str;
727
0
  n_chars = 0;
728
0
  if (len < 0)
729
0
    {
730
0
      while (*p)
731
0
  {
732
0
    p = g_utf8_next_char (p);
733
0
    ++n_chars;
734
0
  }
735
0
    }
736
0
  else
737
0
    {
738
0
      while (p < str + len && *p)
739
0
  {
740
0
    p = g_utf8_next_char (p);
741
0
    ++n_chars;
742
0
  }
743
0
    }
744
0
  
745
0
  result = g_new (gunichar, n_chars + 1);
746
0
  
747
0
  p = str;
748
0
  for (i=0; i < n_chars; i++)
749
0
    {
750
0
      guchar first = (guchar)*p++;
751
0
      gunichar wc;
752
0
753
0
      if (first < 0xc0)
754
0
  {
755
0
          /* We really hope first < 0x80, but we don't want to test an
756
0
           * extra branch for invalid input, which this function
757
0
           * does not care about. Handling unexpected continuation bytes
758
0
           * here will do the least damage. */
759
0
    wc = first;
760
0
  }
761
0
      else
762
0
  {
763
0
          gunichar c1 = CONT_BYTE_FAST(p);
764
0
          if (first < 0xe0)
765
0
            {
766
0
              wc = ((first & 0x1f) << 6) | c1;
767
0
            }
768
0
          else
769
0
            {
770
0
              gunichar c2 = CONT_BYTE_FAST(p);
771
0
              if (first < 0xf0)
772
0
                {
773
0
                  wc = ((first & 0x0f) << 12) | (c1 << 6) | c2;
774
0
                }
775
0
              else
776
0
                {
777
0
                  gunichar c3 = CONT_BYTE_FAST(p);
778
0
                  wc = ((first & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
779
0
                  if (G_UNLIKELY (first >= 0xf8))
780
0
                    {
781
0
                      /* This can't be valid UTF-8, but g_utf8_next_char()
782
0
                       * and company allow out-of-range sequences */
783
0
                      gunichar mask = 1 << 20;
784
0
                      while ((wc & mask) != 0)
785
0
                        {
786
0
                          wc <<= 6;
787
0
                          wc |= CONT_BYTE_FAST(p);
788
0
                          mask <<= 5;
789
0
                        }
790
0
                      wc &= mask - 1;
791
0
                    }
792
0
                }
793
0
            }
794
0
  }
795
0
      result[i] = wc;
796
0
    }
797
0
  result[i] = 0;
798
0
799
0
  if (items_written)
800
0
    *items_written = i;
801
0
802
0
  return result;
803
0
}
804
805
static gpointer
806
try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
807
0
{
808
0
    gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
809
0
    if (ptr == NULL)
810
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
811
0
                           _("Failed to allocate memory"));
812
0
    return ptr;
813
0
}
814
815
/**
816
 * g_utf8_to_ucs4:
817
 * @str: a UTF-8 encoded string
818
 * @len: the maximum length of @str to use, in bytes. If @len < 0,
819
 *     then the string is nul-terminated.
820
 * @items_read: (out caller-allocates) (optional): location to store number of
821
  *    bytes read, or %NULL.
822
 *     If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
823
 *     returned in case @str contains a trailing partial
824
 *     character. If an error occurs then the index of the
825
 *     invalid input is stored here.
826
 * @items_written: (out caller-allocates) (optional): location to store number
827
 *     of characters written or %NULL. The value here stored does not include
828
 *     the trailing 0 character.
829
 * @error: location to store the error occurring, or %NULL to ignore
830
 *     errors. Any of the errors in #GConvertError other than
831
 *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
832
 *
833
 * Convert a string from UTF-8 to a 32-bit fixed width
834
 * representation as UCS-4. A trailing 0 character will be added to the
835
 * string after the converted text.
836
 * 
837
 * Returns: a pointer to a newly allocated UCS-4 string.
838
 *     This value must be freed with g_free(). If an error occurs,
839
 *     %NULL will be returned and @error set.
840
 */
841
gunichar *
842
g_utf8_to_ucs4 (const gchar *str,
843
    glong        len,             
844
    glong       *items_read,      
845
    glong       *items_written,   
846
    GError     **error)
847
0
{
848
0
  gunichar *result = NULL;
849
0
  gint n_chars, i;
850
0
  const gchar *in;
851
0
  
852
0
  in = str;
853
0
  n_chars = 0;
854
0
  while ((len < 0 || str + len - in > 0) && *in)
855
0
    {
856
0
      gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
857
0
      if (wc & 0x80000000)
858
0
  {
859
0
    if (wc == (gunichar)-2)
860
0
      {
861
0
        if (items_read)
862
0
    break;
863
0
        else
864
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
865
0
                                     _("Partial character sequence at end of input"));
866
0
      }
867
0
    else
868
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
869
0
                                 _("Invalid byte sequence in conversion input"));
870
0
871
0
    goto err_out;
872
0
  }
873
0
874
0
      n_chars++;
875
0
876
0
      in = g_utf8_next_char (in);
877
0
    }
878
0
879
0
  result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
880
0
  if (result == NULL)
881
0
      goto err_out;
882
0
883
0
  in = str;
884
0
  for (i=0; i < n_chars; i++)
885
0
    {
886
0
      result[i] = g_utf8_get_char (in);
887
0
      in = g_utf8_next_char (in);
888
0
    }
889
0
  result[i] = 0;
890
0
891
0
  if (items_written)
892
0
    *items_written = n_chars;
893
0
894
0
 err_out:
895
0
  if (items_read)
896
0
    *items_read = in - str;
897
0
898
0
  return result;
899
0
}
900
901
/**
902
 * g_ucs4_to_utf8:
903
 * @str: a UCS-4 encoded string
904
 * @len: the maximum length (number of characters) of @str to use. 
905
 *     If @len < 0, then the string is nul-terminated.
906
 * @items_read: (out caller-allocates) (optional): location to store number of
907
 *     characters read, or %NULL.
908
 * @items_written: (out caller-allocates) (optional): location to store number
909
 *     of bytes written or %NULL. The value here stored does not include the
910
 *     trailing 0 byte.
911
 * @error: location to store the error occurring, or %NULL to ignore
912
 *         errors. Any of the errors in #GConvertError other than
913
 *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
914
 *
915
 * Convert a string from a 32-bit fixed width representation as UCS-4.
916
 * to UTF-8. The result will be terminated with a 0 byte.
917
 * 
918
 * Returns: a pointer to a newly allocated UTF-8 string.
919
 *     This value must be freed with g_free(). If an error occurs,
920
 *     %NULL will be returned and @error set. In that case, @items_read
921
 *     will be set to the position of the first invalid input character.
922
 */
923
gchar *
924
g_ucs4_to_utf8 (const gunichar *str,
925
    glong           len,              
926
    glong          *items_read,       
927
    glong          *items_written,    
928
    GError        **error)
929
0
{
930
0
  gint result_length;
931
0
  gchar *result = NULL;
932
0
  gchar *p;
933
0
  gint i;
934
0
935
0
  result_length = 0;
936
0
  for (i = 0; len < 0 || i < len ; i++)
937
0
    {
938
0
      if (!str[i])
939
0
  break;
940
0
941
0
      if (str[i] >= 0x80000000)
942
0
  {
943
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
944
0
                               _("Character out of range for UTF-8"));
945
0
    goto err_out;
946
0
  }
947
0
      
948
0
      result_length += UTF8_LENGTH (str[i]);
949
0
    }
950
0
951
0
  result = try_malloc_n (result_length + 1, 1, error);
952
0
  if (result == NULL)
953
0
      goto err_out;
954
0
955
0
  p = result;
956
0
957
0
  i = 0;
958
0
  while (p < result + result_length)
959
0
    p += g_unichar_to_utf8 (str[i++], p);
960
0
  
961
0
  *p = '\0';
962
0
963
0
  if (items_written)
964
0
    *items_written = p - result;
965
0
966
0
 err_out:
967
0
  if (items_read)
968
0
    *items_read = i;
969
0
970
0
  return result;
971
0
}
972
973
0
#define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
974
975
/**
976
 * g_utf16_to_utf8:
977
 * @str: a UTF-16 encoded string
978
 * @len: the maximum length (number of #gunichar2) of @str to use. 
979
 *     If @len < 0, then the string is nul-terminated.
980
 * @items_read: (out caller-allocates) (optional): location to store number of
981
 *     words read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
982
 *     be returned in case @str contains a trailing partial character. If
983
 *     an error occurs then the index of the invalid input is stored here.
984
 * @items_written: (out caller-allocates) (optional): location to store number
985
 *     of bytes written, or %NULL. The value stored here does not include the
986
 *     trailing 0 byte.
987
 * @error: location to store the error occurring, or %NULL to ignore
988
 *     errors. Any of the errors in #GConvertError other than
989
 *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
990
 *
991
 * Convert a string from UTF-16 to UTF-8. The result will be
992
 * terminated with a 0 byte.
993
 *
994
 * Note that the input is expected to be already in native endianness,
995
 * an initial byte-order-mark character is not handled specially.
996
 * g_convert() can be used to convert a byte buffer of UTF-16 data of
997
 * ambiguous endianess.
998
 *
999
 * Further note that this function does not validate the result
1000
 * string; it may e.g. include embedded NUL characters. The only
1001
 * validation done by this function is to ensure that the input can
1002
 * be correctly interpreted as UTF-16, i.e. it doesn't contain
1003
 * things unpaired surrogates.
1004
 *
1005
 * Returns: a pointer to a newly allocated UTF-8 string.
1006
 *     This value must be freed with g_free(). If an error occurs,
1007
 *     %NULL will be returned and @error set.
1008
 **/
1009
gchar *
1010
g_utf16_to_utf8 (const gunichar2  *str,
1011
     glong             len,
1012
     glong            *items_read,
1013
     glong            *items_written,
1014
     GError          **error)
1015
0
{
1016
0
  /* This function and g_utf16_to_ucs4 are almost exactly identical -
1017
0
   * The lines that differ are marked.
1018
0
   */
1019
0
  const gunichar2 *in;
1020
0
  gchar *out;
1021
0
  gchar *result = NULL;
1022
0
  gint n_bytes;
1023
0
  gunichar high_surrogate;
1024
0
1025
0
  g_return_val_if_fail (str != NULL, NULL);
1026
0
1027
0
  n_bytes = 0;
1028
0
  in = str;
1029
0
  high_surrogate = 0;
1030
0
  while ((len < 0 || in - str < len) && *in)
1031
0
    {
1032
0
      gunichar2 c = *in;
1033
0
      gunichar wc;
1034
0
1035
0
      if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1036
0
  {
1037
0
    if (high_surrogate)
1038
0
      {
1039
0
        wc = SURROGATE_VALUE (high_surrogate, c);
1040
0
        high_surrogate = 0;
1041
0
      }
1042
0
    else
1043
0
      {
1044
0
        g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1045
0
                                   _("Invalid sequence in conversion input"));
1046
0
        goto err_out;
1047
0
      }
1048
0
  }
1049
0
      else
1050
0
  {
1051
0
    if (high_surrogate)
1052
0
      {
1053
0
        g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1054
0
                                   _("Invalid sequence in conversion input"));
1055
0
        goto err_out;
1056
0
      }
1057
0
1058
0
    if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1059
0
      {
1060
0
        high_surrogate = c;
1061
0
        goto next1;
1062
0
      }
1063
0
    else
1064
0
      wc = c;
1065
0
  }
1066
0
1067
0
      /********** DIFFERENT for UTF8/UCS4 **********/
1068
0
      n_bytes += UTF8_LENGTH (wc);
1069
0
1070
0
    next1:
1071
0
      in++;
1072
0
    }
1073
0
1074
0
  if (high_surrogate && !items_read)
1075
0
    {
1076
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1077
0
                           _("Partial character sequence at end of input"));
1078
0
      goto err_out;
1079
0
    }
1080
0
  
1081
0
  /* At this point, everything is valid, and we just need to convert
1082
0
   */
1083
0
  /********** DIFFERENT for UTF8/UCS4 **********/
1084
0
  result = try_malloc_n (n_bytes + 1, 1, error);
1085
0
  if (result == NULL)
1086
0
      goto err_out;
1087
0
1088
0
  high_surrogate = 0;
1089
0
  out = result;
1090
0
  in = str;
1091
0
  while (out < result + n_bytes)
1092
0
    {
1093
0
      gunichar2 c = *in;
1094
0
      gunichar wc;
1095
0
1096
0
      if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1097
0
  {
1098
0
    wc = SURROGATE_VALUE (high_surrogate, c);
1099
0
    high_surrogate = 0;
1100
0
  }
1101
0
      else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1102
0
  {
1103
0
    high_surrogate = c;
1104
0
    goto next2;
1105
0
  }
1106
0
      else
1107
0
  wc = c;
1108
0
1109
0
      /********** DIFFERENT for UTF8/UCS4 **********/
1110
0
      out += g_unichar_to_utf8 (wc, out);
1111
0
1112
0
    next2:
1113
0
      in++;
1114
0
    }
1115
0
  
1116
0
  /********** DIFFERENT for UTF8/UCS4 **********/
1117
0
  *out = '\0';
1118
0
1119
0
  if (items_written)
1120
0
    /********** DIFFERENT for UTF8/UCS4 **********/
1121
0
    *items_written = out - result;
1122
0
1123
0
 err_out:
1124
0
  if (items_read)
1125
0
    *items_read = in - str;
1126
0
1127
0
  return result;
1128
0
}
1129
1130
/**
1131
 * g_utf16_to_ucs4:
1132
 * @str: a UTF-16 encoded string
1133
 * @len: the maximum length (number of #gunichar2) of @str to use. 
1134
 *     If @len < 0, then the string is nul-terminated.
1135
 * @items_read: (out caller-allocates) (optional): location to store number of
1136
 *     words read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
1137
 *     be returned in case @str contains a trailing partial character. If
1138
 *     an error occurs then the index of the invalid input is stored here.
1139
 * @items_written: (out caller-allocates) (optional): location to store number
1140
 *     of characters written, or %NULL. The value stored here does not include
1141
 *     the trailing 0 character.
1142
 * @error: location to store the error occurring, or %NULL to ignore
1143
 *     errors. Any of the errors in #GConvertError other than
1144
 *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
1145
 *
1146
 * Convert a string from UTF-16 to UCS-4. The result will be
1147
 * nul-terminated.
1148
 * 
1149
 * Returns: a pointer to a newly allocated UCS-4 string.
1150
 *     This value must be freed with g_free(). If an error occurs,
1151
 *     %NULL will be returned and @error set.
1152
 */
1153
gunichar *
1154
g_utf16_to_ucs4 (const gunichar2  *str,
1155
     glong             len,              
1156
     glong            *items_read,       
1157
     glong            *items_written,    
1158
     GError          **error)
1159
0
{
1160
0
  const gunichar2 *in;
1161
0
  gchar *out;
1162
0
  gchar *result = NULL;
1163
0
  gint n_bytes;
1164
0
  gunichar high_surrogate;
1165
0
1166
0
  g_return_val_if_fail (str != NULL, NULL);
1167
0
1168
0
  n_bytes = 0;
1169
0
  in = str;
1170
0
  high_surrogate = 0;
1171
0
  while ((len < 0 || in - str < len) && *in)
1172
0
    {
1173
0
      gunichar2 c = *in;
1174
0
1175
0
      if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1176
0
  {
1177
0
    if (high_surrogate)
1178
0
      {
1179
0
        high_surrogate = 0;
1180
0
      }
1181
0
    else
1182
0
      {
1183
0
        g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1184
0
                                   _("Invalid sequence in conversion input"));
1185
0
        goto err_out;
1186
0
      }
1187
0
  }
1188
0
      else
1189
0
  {
1190
0
    if (high_surrogate)
1191
0
      {
1192
0
        g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1193
0
                                   _("Invalid sequence in conversion input"));
1194
0
        goto err_out;
1195
0
      }
1196
0
1197
0
    if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1198
0
      {
1199
0
        high_surrogate = c;
1200
0
        goto next1;
1201
0
      }
1202
0
  }
1203
0
1204
0
      /********** DIFFERENT for UTF8/UCS4 **********/
1205
0
      n_bytes += sizeof (gunichar);
1206
0
1207
0
    next1:
1208
0
      in++;
1209
0
    }
1210
0
1211
0
  if (high_surrogate && !items_read)
1212
0
    {
1213
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1214
0
                           _("Partial character sequence at end of input"));
1215
0
      goto err_out;
1216
0
    }
1217
0
  
1218
0
  /* At this point, everything is valid, and we just need to convert
1219
0
   */
1220
0
  /********** DIFFERENT for UTF8/UCS4 **********/
1221
0
  result = try_malloc_n (n_bytes + 4, 1, error);
1222
0
  if (result == NULL)
1223
0
      goto err_out;
1224
0
1225
0
  high_surrogate = 0;
1226
0
  out = result;
1227
0
  in = str;
1228
0
  while (out < result + n_bytes)
1229
0
    {
1230
0
      gunichar2 c = *in;
1231
0
      gunichar wc;
1232
0
1233
0
      if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1234
0
  {
1235
0
    wc = SURROGATE_VALUE (high_surrogate, c);
1236
0
    high_surrogate = 0;
1237
0
  }
1238
0
      else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1239
0
  {
1240
0
    high_surrogate = c;
1241
0
    goto next2;
1242
0
  }
1243
0
      else
1244
0
  wc = c;
1245
0
1246
0
      /********** DIFFERENT for UTF8/UCS4 **********/
1247
0
      *(gunichar *)out = wc;
1248
0
      out += sizeof (gunichar);
1249
0
1250
0
    next2:
1251
0
      in++;
1252
0
    }
1253
0
1254
0
  /********** DIFFERENT for UTF8/UCS4 **********/
1255
0
  *(gunichar *)out = 0;
1256
0
1257
0
  if (items_written)
1258
0
    /********** DIFFERENT for UTF8/UCS4 **********/
1259
0
    *items_written = (out - result) / sizeof (gunichar);
1260
0
1261
0
 err_out:
1262
0
  if (items_read)
1263
0
    *items_read = in - str;
1264
0
1265
0
  return (gunichar *)result;
1266
0
}
1267
1268
/**
1269
 * g_utf8_to_utf16:
1270
 * @str: a UTF-8 encoded string
1271
 * @len: the maximum length (number of bytes) of @str to use.
1272
 *     If @len < 0, then the string is nul-terminated.
1273
 * @items_read: (out caller-allocates) (optional): location to store number of
1274
 *     bytes read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
1275
 *     be returned in case @str contains a trailing partial character. If
1276
 *     an error occurs then the index of the invalid input is stored here.
1277
 * @items_written: (out caller-allocates) (optional): location to store number
1278
 *     of #gunichar2 written, or %NULL. The value stored here does not include
1279
 *     the trailing 0.
1280
 * @error: location to store the error occurring, or %NULL to ignore
1281
 *     errors. Any of the errors in #GConvertError other than
1282
 *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
1283
 *
1284
 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1285
 * added to the result after the converted text.
1286
 *
1287
 * Returns: a pointer to a newly allocated UTF-16 string.
1288
 *     This value must be freed with g_free(). If an error occurs,
1289
 *     %NULL will be returned and @error set.
1290
 */
1291
gunichar2 *
1292
g_utf8_to_utf16 (const gchar *str,
1293
     glong        len,
1294
     glong       *items_read,
1295
     glong       *items_written,
1296
     GError     **error)
1297
0
{
1298
0
  gunichar2 *result = NULL;
1299
0
  gint n16;
1300
0
  const gchar *in;
1301
0
  gint i;
1302
0
1303
0
  g_return_val_if_fail (str != NULL, NULL);
1304
0
1305
0
  in = str;
1306
0
  n16 = 0;
1307
0
  while ((len < 0 || str + len - in > 0) && *in)
1308
0
    {
1309
0
      gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1310
0
      if (wc & 0x80000000)
1311
0
  {
1312
0
    if (wc == (gunichar)-2)
1313
0
      {
1314
0
        if (items_read)
1315
0
    break;
1316
0
        else
1317
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1318
0
                                     _("Partial character sequence at end of input"));
1319
0
      }
1320
0
    else
1321
0
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1322
0
                                 _("Invalid byte sequence in conversion input"));
1323
0
1324
0
    goto err_out;
1325
0
  }
1326
0
1327
0
      if (wc < 0xd800)
1328
0
  n16 += 1;
1329
0
      else if (wc < 0xe000)
1330
0
  {
1331
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1332
0
                               _("Invalid sequence in conversion input"));
1333
0
1334
0
    goto err_out;
1335
0
  }
1336
0
      else if (wc < 0x10000)
1337
0
  n16 += 1;
1338
0
      else if (wc < 0x110000)
1339
0
  n16 += 2;
1340
0
      else
1341
0
  {
1342
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1343
0
                               _("Character out of range for UTF-16"));
1344
0
1345
0
    goto err_out;
1346
0
  }
1347
0
      
1348
0
      in = g_utf8_next_char (in);
1349
0
    }
1350
0
1351
0
  result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1352
0
  if (result == NULL)
1353
0
      goto err_out;
1354
0
1355
0
  in = str;
1356
0
  for (i = 0; i < n16;)
1357
0
    {
1358
0
      gunichar wc = g_utf8_get_char (in);
1359
0
1360
0
      if (wc < 0x10000)
1361
0
  {
1362
0
    result[i++] = wc;
1363
0
  }
1364
0
      else
1365
0
  {
1366
0
    result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1367
0
    result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1368
0
  }
1369
0
      
1370
0
      in = g_utf8_next_char (in);
1371
0
    }
1372
0
1373
0
  result[i] = 0;
1374
0
1375
0
  if (items_written)
1376
0
    *items_written = n16;
1377
0
1378
0
 err_out:
1379
0
  if (items_read)
1380
0
    *items_read = in - str;
1381
0
  
1382
0
  return result;
1383
0
}
1384
1385
/**
1386
 * g_ucs4_to_utf16:
1387
 * @str: a UCS-4 encoded string
1388
 * @len: the maximum length (number of characters) of @str to use. 
1389
 *     If @len < 0, then the string is nul-terminated.
1390
 * @items_read: (out caller-allocates) (optional): location to store number of
1391
 *     bytes read, or %NULL. If an error occurs then the index of the invalid
1392
 *     input is stored here.
1393
 * @items_written: (out caller-allocates) (optional): location to store number
1394
 *     of #gunichar2  written, or %NULL. The value stored here does not include
1395
 *     the trailing 0.
1396
 * @error: location to store the error occurring, or %NULL to ignore
1397
 *     errors. Any of the errors in #GConvertError other than
1398
 *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
1399
 *
1400
 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1401
 * added to the result after the converted text.
1402
 * 
1403
 * Returns: a pointer to a newly allocated UTF-16 string.
1404
 *     This value must be freed with g_free(). If an error occurs,
1405
 *     %NULL will be returned and @error set.
1406
 */
1407
gunichar2 *
1408
g_ucs4_to_utf16 (const gunichar  *str,
1409
     glong            len,              
1410
     glong           *items_read,       
1411
     glong           *items_written,    
1412
     GError         **error)
1413
0
{
1414
0
  gunichar2 *result = NULL;
1415
0
  gint n16;
1416
0
  gint i, j;
1417
0
1418
0
  n16 = 0;
1419
0
  i = 0;
1420
0
  while ((len < 0 || i < len) && str[i])
1421
0
    {
1422
0
      gunichar wc = str[i];
1423
0
1424
0
      if (wc < 0xd800)
1425
0
  n16 += 1;
1426
0
      else if (wc < 0xe000)
1427
0
  {
1428
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1429
0
                               _("Invalid sequence in conversion input"));
1430
0
1431
0
    goto err_out;
1432
0
  }
1433
0
      else if (wc < 0x10000)
1434
0
  n16 += 1;
1435
0
      else if (wc < 0x110000)
1436
0
  n16 += 2;
1437
0
      else
1438
0
  {
1439
0
    g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1440
0
                               _("Character out of range for UTF-16"));
1441
0
1442
0
    goto err_out;
1443
0
  }
1444
0
1445
0
      i++;
1446
0
    }
1447
0
1448
0
  result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1449
0
  if (result == NULL)
1450
0
      goto err_out;
1451
0
1452
0
  for (i = 0, j = 0; j < n16; i++)
1453
0
    {
1454
0
      gunichar wc = str[i];
1455
0
1456
0
      if (wc < 0x10000)
1457
0
  {
1458
0
    result[j++] = wc;
1459
0
  }
1460
0
      else
1461
0
  {
1462
0
    result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1463
0
    result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1464
0
  }
1465
0
    }
1466
0
  result[j] = 0;
1467
0
1468
0
  if (items_written)
1469
0
    *items_written = n16;
1470
0
  
1471
0
 err_out:
1472
0
  if (items_read)
1473
0
    *items_read = i;
1474
0
  
1475
0
  return result;
1476
0
}
1477
1478
#define VALIDATE_BYTE(mask, expect)                      \
1479
31.4M
  G_STMT_START {                                         \
1480
31.4M
    if (G_UNLIKELY((*(guchar *)p & (mask)) != (expect))) \
1481
31.4M
      goto error;                                        \
1482
31.4M
  } G_STMT_END
1483
1484
/* see IETF RFC 3629 Section 4 */
1485
1486
static const gchar *
1487
fast_validate (const char *str)
1488
1489
2.45M
{
1490
2.45M
  const gchar *p;
1491
2.45M
1492
119M
  for (p = str; *p; p++)
1493
116M
    {
1494
116M
      if (*(guchar *)p < 128)
1495
101M
  /* done */;
1496
15.5M
      else 
1497
15.5M
  {
1498
15.5M
    const gchar *last;
1499
15.5M
1500
15.5M
    last = p;
1501
15.5M
    if (*(guchar *)p < 0xe0) /* 110xxxxx */
1502
3.25k
      {
1503
3.25k
        if (G_UNLIKELY (*(guchar *)p < 0xc2))
1504
3.25k
    goto error;
1505
15.5M
      }
1506
15.5M
    else
1507
15.5M
      {
1508
15.5M
        if (*(guchar *)p < 0xf0) /* 1110xxxx */
1509
15.5M
    {
1510
15.5M
      switch (*(guchar *)p++ & 0x0f)
1511
15.5M
        {
1512
15.5M
        case 0:
1513
1.33k
          VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1514
1.33k
          break;
1515
1.61k
        case 0x0d:
1516
1.61k
          VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1517
1.61k
          break;
1518
15.5M
        default:
1519
15.5M
          VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1520
15.5M
        }
1521
15.5M
    }
1522
13.1k
        else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1523
13.1k
    {
1524
13.1k
      switch (*(guchar *)p++ & 0x07)
1525
13.1k
        {
1526
13.1k
        case 0:
1527
6.67k
          VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1528
6.67k
          if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1529
6.66k
      goto error;
1530
6.66k
          break;
1531
6.66k
        case 4:
1532
1.53k
          VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1533
1.53k
          break;
1534
4.90k
        default:
1535
4.90k
          VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1536
13.1k
        }
1537
13.1k
      p++;
1538
13.0k
      VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1539
13.0k
    }
1540
21
        else
1541
21
    goto error;
1542
15.5M
      }
1543
15.5M
1544
15.5M
    p++;
1545
15.5M
    VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1546
15.5M
1547
15.5M
    continue;
1548
123
1549
123
  error:
1550
123
    return last;
1551
15.5M
  }
1552
116M
    }
1553
2.45M
1554
2.45M
  return p;
1555
2.45M
}
1556
1557
static const gchar *
1558
fast_validate_len (const char *str,
1559
       gssize      max_len)
1560
1561
15.9M
{
1562
15.9M
  const gchar *p;
1563
15.9M
1564
15.9M
  g_assert (max_len >= 0);
1565
15.9M
1566
24.4M
  for (p = str; ((p - str) < max_len) && *p; p++)
1567
8.88M
    {
1568
8.88M
      if (*(guchar *)p < 128)
1569
8.47M
  /* done */;
1570
412k
      else 
1571
412k
  {
1572
412k
    const gchar *last;
1573
412k
1574
412k
    last = p;
1575
412k
    if (*(guchar *)p < 0xe0) /* 110xxxxx */
1576
147k
      {
1577
147k
        if (G_UNLIKELY (max_len - (p - str) < 2))
1578
147k
    goto error;
1579
147k
        
1580
147k
        if (G_UNLIKELY (*(guchar *)p < 0xc2))
1581
147k
    goto error;
1582
264k
      }
1583
264k
    else
1584
264k
      {
1585
264k
        if (*(guchar *)p < 0xf0) /* 1110xxxx */
1586
163k
    {
1587
163k
      if (G_UNLIKELY (max_len - (p - str) < 3))
1588
163k
        goto error;
1589
163k
1590
163k
      switch (*(guchar *)p++ & 0x0f)
1591
163k
        {
1592
163k
        case 0:
1593
5.18k
          VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1594
5.18k
          break;
1595
5.84k
        case 0x0d:
1596
5.84k
          VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1597
5.84k
          break;
1598
152k
        default:
1599
152k
          VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1600
163k
        }
1601
163k
    }
1602
101k
        else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1603
75.2k
    {
1604
75.2k
      if (G_UNLIKELY (max_len - (p - str) < 4))
1605
75.2k
        goto error;
1606
74.9k
1607
74.9k
      switch (*(guchar *)p++ & 0x07)
1608
74.9k
        {
1609
74.9k
        case 0:
1610
42.3k
          VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1611
42.3k
          if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1612
31.5k
      goto error;
1613
19.5k
          break;
1614
19.5k
        case 4:
1615
16.1k
          VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1616
16.1k
          break;
1617
16.4k
        default:
1618
16.4k
          VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1619
74.9k
        }
1620
74.9k
      p++;
1621
39.1k
      VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1622
39.1k
    }
1623
25.8k
        else
1624
25.8k
    goto error;
1625
92.5k
      }
1626
92.5k
1627
92.5k
    p++;
1628
92.5k
    VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1629
92.5k
1630
92.5k
    continue;
1631
356k
1632
356k
  error:
1633
356k
    return last;
1634
92.5k
  }
1635
8.88M
    }
1636
15.9M
1637
15.9M
  return p;
1638
15.9M
}
1639
1640
/**
1641
 * g_utf8_validate:
1642
 * @str: (array length=max_len) (element-type guint8): a pointer to character data
1643
 * @max_len: max bytes to validate, or -1 to go until NUL
1644
 * @end: (out) (optional) (transfer none): return location for end of valid data
1645
 * 
1646
 * Validates UTF-8 encoded text. @str is the text to validate;
1647
 * if @str is nul-terminated, then @max_len can be -1, otherwise
1648
 * @max_len should be the number of bytes to validate.
1649
 * If @end is non-%NULL, then the end of the valid range
1650
 * will be stored there (i.e. the start of the first invalid 
1651
 * character if some bytes were invalid, or the end of the text 
1652
 * being validated otherwise).
1653
 *
1654
 * Note that g_utf8_validate() returns %FALSE if @max_len is 
1655
 * positive and any of the @max_len bytes are nul.
1656
 *
1657
 * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1658
 * routines require valid UTF-8 as input; so data read from a file
1659
 * or the network should be checked with g_utf8_validate() before
1660
 * doing anything else with it.
1661
 * 
1662
 * Returns: %TRUE if the text was valid UTF-8
1663
 */
1664
gboolean
1665
g_utf8_validate (const char   *str,
1666
     gssize        max_len,    
1667
     const gchar **end)
1668
1669
18.4M
{
1670
18.4M
  const gchar *p;
1671
18.4M
1672
18.4M
  if (max_len < 0)
1673
2.45M
    p = fast_validate (str);
1674
15.9M
  else
1675
15.9M
    p = fast_validate_len (str, max_len);
1676
18.4M
1677
18.4M
  if (end)
1678
15.9M
    *end = p;
1679
18.4M
1680
18.4M
  if ((max_len >= 0 && p != str + max_len) ||
1681
18.4M
      (max_len < 0 && *p != '\0'))
1682
15.9M
    return FALSE;
1683
18.4M
  else
1684
18.4M
    return TRUE;
1685
18.4M
}
1686
1687
/**
1688
 * g_unichar_validate:
1689
 * @ch: a Unicode character
1690
 * 
1691
 * Checks whether @ch is a valid Unicode character. Some possible
1692
 * integer values of @ch will not be valid. 0 is considered a valid
1693
 * character, though it's normally a string terminator.
1694
 * 
1695
 * Returns: %TRUE if @ch is a valid Unicode character
1696
 **/
1697
gboolean
1698
g_unichar_validate (gunichar ch)
1699
0
{
1700
0
  return UNICODE_VALID (ch);
1701
0
}
1702
1703
/**
1704
 * g_utf8_strreverse:
1705
 * @str: a UTF-8 encoded string
1706
 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1707
 *     then the string is nul-terminated.
1708
 *
1709
 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text. 
1710
 * (Use g_utf8_validate() on all text before trying to use UTF-8 
1711
 * utility functions with it.)
1712
 *
1713
 * This function is intended for programmatic uses of reversed strings.
1714
 * It pays no attention to decomposed characters, combining marks, byte 
1715
 * order marks, directional indicators (LRM, LRO, etc) and similar 
1716
 * characters which might need special handling when reversing a string 
1717
 * for display purposes.
1718
 *
1719
 * Note that unlike g_strreverse(), this function returns
1720
 * newly-allocated memory, which should be freed with g_free() when
1721
 * no longer needed. 
1722
 *
1723
 * Returns: a newly-allocated string which is the reverse of @str
1724
 *
1725
 * Since: 2.2
1726
 */
1727
gchar *
1728
g_utf8_strreverse (const gchar *str,
1729
       gssize       len)
1730
0
{
1731
0
  gchar *r, *result;
1732
0
  const gchar *p;
1733
0
1734
0
  if (len < 0)
1735
0
    len = strlen (str);
1736
0
1737
0
  result = g_new (gchar, len + 1);
1738
0
  r = result + len;
1739
0
  p = str;
1740
0
  while (r > result)
1741
0
    {
1742
0
      gchar *m, skip = g_utf8_skip[*(guchar*) p];
1743
0
      r -= skip;
1744
0
      for (m = r; skip; skip--)
1745
0
        *m++ = *p++;
1746
0
    }
1747
0
  result[len] = 0;
1748
0
1749
0
  return result;
1750
0
}
1751
1752
/**
1753
 * g_utf8_make_valid:
1754
 * @str: string to coerce into UTF-8
1755
 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1756
 *     then the string is nul-terminated.
1757
 *
1758
 * If the provided string is valid UTF-8, return a copy of it. If not,
1759
 * return a copy in which bytes that could not be interpreted as valid Unicode
1760
 * are replaced with the Unicode replacement character (U+FFFD).
1761
 *
1762
 * For example, this is an appropriate function to use if you have received
1763
 * a string that was incorrectly declared to be UTF-8, and you need a valid
1764
 * UTF-8 version of it that can be logged or displayed to the user, with the
1765
 * assumption that it is close enough to ASCII or UTF-8 to be mostly
1766
 * readable as-is.
1767
 *
1768
 * Returns: (transfer full): a valid UTF-8 string whose content resembles @str
1769
 *
1770
 * Since: 2.52
1771
 */
1772
gchar *
1773
g_utf8_make_valid (const gchar *str,
1774
                   gssize       len)
1775
3.08k
{
1776
3.08k
  GString *string;
1777
3.08k
  const gchar *remainder, *invalid;
1778
3.08k
  gsize remaining_bytes, valid_bytes;
1779
3.08k
1780
3.08k
  g_return_val_if_fail (str != NULL, NULL);
1781
3.08k
1782
3.08k
  if (len < 0)
1783
2.40k
    len = strlen (str);
1784
3.08k
1785
3.08k
  string = NULL;
1786
3.08k
  remainder = str;
1787
3.08k
  remaining_bytes = len;
1788
3.08k
1789
15.4M
  while (remaining_bytes != 0) 
1790
15.4M
    {
1791
15.4M
      if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
1792
2.73k
  break;
1793
15.4M
      valid_bytes = invalid - remainder;
1794
15.4M
    
1795
15.4M
      if (string == NULL) 
1796
15.4M
  string = g_string_sized_new (remaining_bytes);
1797
15.4M
1798
15.4M
      g_string_append_len (string, remainder, valid_bytes);
1799
15.4M
      /* append U+FFFD REPLACEMENT CHARACTER */
1800
15.4M
      g_string_append (string, "\357\277\275");
1801
15.4M
      
1802
15.4M
      remaining_bytes -= valid_bytes + 1;
1803
15.4M
      remainder = invalid + 1;
1804
15.4M
    }
1805
3.08k
  
1806
3.08k
  if (string == NULL)
1807
3.08k
    return g_strndup (str, len);
1808
990
  
1809
990
  g_string_append_len (string, remainder, remaining_bytes);
1810
990
  g_string_append_c (string, '\0');
1811
990
1812
990
  g_assert (g_utf8_validate (string->str, -1, NULL));
1813
990
1814
990
  return g_string_free (string, FALSE);
1815
990
}