docs: Fix a minor syntax error in a documentation comment
[glib.git] / glib / gutf8.c
bloba0fb16370c2d18931d9847a58582e49f57ad5588
1 /* gutf8.c - Operations on UTF-8 strings.
3 * Copyright (C) 1999 Tom Tromey
4 * Copyright (C) 2000 Red Hat, Inc.
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.
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.
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/>.
20 #include "config.h"
22 #include <stdlib.h>
23 #ifdef HAVE_CODESET
24 #include <langinfo.h>
25 #endif
26 #include <string.h>
28 #ifdef G_PLATFORM_WIN32
29 #include <stdio.h>
30 #define STRICT
31 #include <windows.h>
32 #undef STRICT
33 #endif
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"
43 #define UTF8_COMPUTE(Char, Mask, Len) \
44 if (Char < 128) \
45 { \
46 Len = 1; \
47 Mask = 0x7f; \
48 } \
49 else if ((Char & 0xe0) == 0xc0) \
50 { \
51 Len = 2; \
52 Mask = 0x1f; \
53 } \
54 else if ((Char & 0xf0) == 0xe0) \
55 { \
56 Len = 3; \
57 Mask = 0x0f; \
58 } \
59 else if ((Char & 0xf8) == 0xf0) \
60 { \
61 Len = 4; \
62 Mask = 0x07; \
63 } \
64 else if ((Char & 0xfc) == 0xf8) \
65 { \
66 Len = 5; \
67 Mask = 0x03; \
68 } \
69 else if ((Char & 0xfe) == 0xfc) \
70 { \
71 Len = 6; \
72 Mask = 0x01; \
73 } \
74 else \
75 Len = -1;
77 #define UTF8_LENGTH(Char) \
78 ((Char) < 0x80 ? 1 : \
79 ((Char) < 0x800 ? 2 : \
80 ((Char) < 0x10000 ? 3 : \
81 ((Char) < 0x200000 ? 4 : \
82 ((Char) < 0x4000000 ? 5 : 6)))))
85 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
86 (Result) = (Chars)[0] & (Mask); \
87 for ((Count) = 1; (Count) < (Len); ++(Count)) \
88 { \
89 if (((Chars)[(Count)] & 0xc0) != 0x80) \
90 { \
91 (Result) = -1; \
92 break; \
93 } \
94 (Result) <<= 6; \
95 (Result) |= ((Chars)[(Count)] & 0x3f); \
99 * Check whether a Unicode (5.2) char is in a valid range.
101 * The first check comes from the Unicode guarantee to never encode
102 * a point above 0x0010ffff, since UTF-16 couldn't represent it.
104 * The second check covers surrogate pairs (category Cs).
106 * @param Char the character
108 #define UNICODE_VALID(Char) \
109 ((Char) < 0x110000 && \
110 (((Char) & 0xFFFFF800) != 0xD800))
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
124 const gchar * const g_utf8_skip = utf8_skip_data;
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
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.
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.
139 * Returns: a pointer to the found character or %NULL.
141 gchar *
142 g_utf8_find_prev_char (const char *str,
143 const char *p)
145 for (--p; p >= str; --p)
147 if ((*p & 0xc0) != 0x80)
148 return (gchar *)p;
150 return NULL;
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
159 * Finds the start of the next UTF-8 character in the string after @p.
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.
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.
170 * Returns: (nullable): a pointer to the found character or %NULL if @end is
171 * set and is reached
173 gchar *
174 g_utf8_find_next_char (const gchar *p,
175 const gchar *end)
177 if (end)
179 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
181 return (p >= end) ? NULL : (gchar *)p;
183 else
185 for (++p; (*p & 0xc0) == 0x80; ++p)
187 return (gchar *)p;
192 * g_utf8_prev_char:
193 * @p: a pointer to a position within a UTF-8 encoded string
195 * Finds the previous UTF-8 character in the string before @p.
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.
202 * Returns: a pointer to the found character
204 gchar *
205 g_utf8_prev_char (const gchar *p)
207 while (TRUE)
209 p--;
210 if ((*p & 0xc0) != 0x80)
211 return (gchar *)p;
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
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.
228 * Returns: the length of the string in characters
230 glong
231 g_utf8_strlen (const gchar *p,
232 gssize max)
234 glong len = 0;
235 const gchar *start = p;
236 g_return_val_if_fail (p != NULL || max == 0, 0);
238 if (max < 0)
240 while (*p)
242 p = g_utf8_next_char (p);
243 ++len;
246 else
248 if (max == 0 || !*p)
249 return 0;
251 p = g_utf8_next_char (p);
253 while (p - start < max && *p)
255 ++len;
256 p = g_utf8_next_char (p);
259 /* only do the last len increment if we got a complete
260 * char (don't count partial chars)
262 if (p - start <= max)
263 ++len;
266 return len;
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
275 * Copies a substring out of a UTF-8 encoded string.
276 * The substring will contain @end_pos - @start_pos characters.
278 * Returns: a newly allocated copy of the requested
279 * substring. Free with g_free() when no longer needed.
281 * Since: 2.30
283 gchar *
284 g_utf8_substring (const gchar *str,
285 glong start_pos,
286 glong end_pos)
288 gchar *start, *end, *out;
290 start = g_utf8_offset_to_pointer (str, start_pos);
291 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
293 out = g_malloc (end - start + 1);
294 memcpy (out, start, end - start);
295 out[end - start] = 0;
297 return out;
301 * g_utf8_get_char:
302 * @p: a pointer to Unicode character encoded as UTF-8
304 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
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.
311 * Returns: the resulting character
313 gunichar
314 g_utf8_get_char (const gchar *p)
316 int i, mask = 0, len;
317 gunichar result;
318 unsigned char c = (unsigned char) *p;
320 UTF8_COMPUTE (c, mask, len);
321 if (len == -1)
322 return (gunichar)-1;
323 UTF8_GET (result, p, i, mask, len);
325 return result;
329 * g_utf8_offset_to_pointer:
330 * @str: a UTF-8 encoded string
331 * @offset: a character offset within @str
333 * Converts from an integer character offset to a pointer to a position
334 * within the string.
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.
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.
347 * Returns: the resulting pointer
349 gchar *
350 g_utf8_offset_to_pointer (const gchar *str,
351 glong offset)
353 const gchar *s = str;
355 if (offset > 0)
356 while (offset--)
357 s = g_utf8_next_char (s);
358 else
360 const char *s1;
362 /* This nice technique for fast backwards stepping
363 * through a UTF-8 string was dubbed "stutter stepping"
364 * by its inventor, Larry Ewing.
366 while (offset)
368 s1 = s;
369 s += offset;
370 while ((*s & 0xc0) == 0x80)
371 s--;
373 offset += g_utf8_pointer_to_offset (s, s1);
377 return (gchar *)s;
381 * g_utf8_pointer_to_offset:
382 * @str: a UTF-8 encoded string
383 * @pos: a pointer to a position within @str
385 * Converts from a pointer to position within a string to a integer
386 * character offset.
388 * Since 2.10, this function allows @pos to be before @str, and returns
389 * a negative offset in this case.
391 * Returns: the resulting character offset
393 glong
394 g_utf8_pointer_to_offset (const gchar *str,
395 const gchar *pos)
397 const gchar *s = str;
398 glong offset = 0;
400 if (pos < str)
401 offset = - g_utf8_pointer_to_offset (pos, str);
402 else
403 while (s < pos)
405 s = g_utf8_next_char (s);
406 offset++;
409 return offset;
414 * g_utf8_strncpy:
415 * @dest: buffer to fill with characters from @src
416 * @src: UTF-8 encoded string
417 * @n: character count
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.)
424 * Note you must ensure @dest is at least 4 * @n to fit the
425 * largest possible UTF-8 characters
427 * Returns: @dest
429 gchar *
430 g_utf8_strncpy (gchar *dest,
431 const gchar *src,
432 gsize n)
434 const gchar *s = src;
435 while (n && *s)
437 s = g_utf8_next_char(s);
438 n--;
440 strncpy(dest, src, s - src);
441 dest[s - src] = 0;
442 return dest;
445 /* unicode_strchr */
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.
454 * Converts a single character to UTF-8.
456 * Returns: number of bytes written
459 g_unichar_to_utf8 (gunichar c,
460 gchar *outbuf)
462 /* If this gets modified, also update the copy in g_string_insert_unichar() */
463 guint len = 0;
464 int first;
465 int i;
467 if (c < 0x80)
469 first = 0;
470 len = 1;
472 else if (c < 0x800)
474 first = 0xc0;
475 len = 2;
477 else if (c < 0x10000)
479 first = 0xe0;
480 len = 3;
482 else if (c < 0x200000)
484 first = 0xf0;
485 len = 4;
487 else if (c < 0x4000000)
489 first = 0xf8;
490 len = 5;
492 else
494 first = 0xfc;
495 len = 6;
498 if (outbuf)
500 for (i = len - 1; i > 0; --i)
502 outbuf[i] = (c & 0x3f) | 0x80;
503 c >>= 6;
505 outbuf[0] = c | first;
508 return len;
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
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.
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.
525 gchar *
526 g_utf8_strchr (const char *p,
527 gssize len,
528 gunichar c)
530 gchar ch[10];
532 gint charlen = g_unichar_to_utf8 (c, ch);
533 ch[charlen] = '\0';
535 return g_strstr_len (p, len, ch);
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
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.
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.
553 gchar *
554 g_utf8_strrchr (const char *p,
555 gssize len,
556 gunichar c)
558 gchar ch[10];
560 gint charlen = g_unichar_to_utf8 (c, ch);
561 ch[charlen] = '\0';
563 return g_strrstr_len (p, len, ch);
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.
572 static inline gunichar
573 g_utf8_get_char_extended (const gchar *p,
574 gssize max_len)
576 guint i, len;
577 gunichar min_code;
578 gunichar wc = (guchar) *p;
579 const gunichar partial_sequence = (gunichar) -2;
580 const gunichar malformed_sequence = (gunichar) -1;
582 if (wc < 0x80)
584 return wc;
586 else if (G_UNLIKELY (wc < 0xc0))
588 return malformed_sequence;
590 else if (wc < 0xe0)
592 len = 2;
593 wc &= 0x1f;
594 min_code = 1 << 7;
596 else if (wc < 0xf0)
598 len = 3;
599 wc &= 0x0f;
600 min_code = 1 << 11;
602 else if (wc < 0xf8)
604 len = 4;
605 wc &= 0x07;
606 min_code = 1 << 16;
608 else if (wc < 0xfc)
610 len = 5;
611 wc &= 0x03;
612 min_code = 1 << 21;
614 else if (wc < 0xfe)
616 len = 6;
617 wc &= 0x01;
618 min_code = 1 << 26;
620 else
622 return malformed_sequence;
625 if (G_UNLIKELY (max_len >= 0 && len > max_len))
627 for (i = 1; i < max_len; i++)
629 if ((((guchar *)p)[i] & 0xc0) != 0x80)
630 return malformed_sequence;
632 return partial_sequence;
635 for (i = 1; i < len; ++i)
637 gunichar ch = ((guchar *)p)[i];
639 if (G_UNLIKELY ((ch & 0xc0) != 0x80))
641 if (ch)
642 return malformed_sequence;
643 else
644 return partial_sequence;
647 wc <<= 6;
648 wc |= (ch & 0x3f);
651 if (G_UNLIKELY (wc < min_code))
652 return malformed_sequence;
654 return wc;
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
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.
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.
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.
677 gunichar
678 g_utf8_get_char_validated (const gchar *p,
679 gssize max_len)
681 gunichar result;
683 if (max_len == 0)
684 return (gunichar)-2;
686 result = g_utf8_get_char_extended (p, max_len);
688 if (result & 0x80000000)
689 return result;
690 else if (!UNICODE_VALID (result))
691 return (gunichar)-1;
692 else
693 return result;
696 #define CONT_BYTE_FAST(p) ((guchar)*p++ & 0x3f)
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.
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.
712 * Returns: a pointer to a newly allocated UCS-4 string.
713 * This value must be freed with g_free().
715 gunichar *
716 g_utf8_to_ucs4_fast (const gchar *str,
717 glong len,
718 glong *items_written)
720 gunichar *result;
721 gint n_chars, i;
722 const gchar *p;
724 g_return_val_if_fail (str != NULL, NULL);
726 p = str;
727 n_chars = 0;
728 if (len < 0)
730 while (*p)
732 p = g_utf8_next_char (p);
733 ++n_chars;
736 else
738 while (p < str + len && *p)
740 p = g_utf8_next_char (p);
741 ++n_chars;
745 result = g_new (gunichar, n_chars + 1);
747 p = str;
748 for (i=0; i < n_chars; i++)
750 guchar first = (guchar)*p++;
751 gunichar wc;
753 if (first < 0xc0)
755 /* We really hope first < 0x80, but we don't want to test an
756 * extra branch for invalid input, which this function
757 * does not care about. Handling unexpected continuation bytes
758 * here will do the least damage. */
759 wc = first;
761 else
763 gunichar c1 = CONT_BYTE_FAST(p);
764 if (first < 0xe0)
766 wc = ((first & 0x1f) << 6) | c1;
768 else
770 gunichar c2 = CONT_BYTE_FAST(p);
771 if (first < 0xf0)
773 wc = ((first & 0x0f) << 12) | (c1 << 6) | c2;
775 else
777 gunichar c3 = CONT_BYTE_FAST(p);
778 wc = ((first & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
779 if (G_UNLIKELY (first >= 0xf8))
781 /* This can't be valid UTF-8, but g_utf8_next_char()
782 * and company allow out-of-range sequences */
783 gunichar mask = 1 << 20;
784 while ((wc & mask) != 0)
786 wc <<= 6;
787 wc |= CONT_BYTE_FAST(p);
788 mask <<= 5;
790 wc &= mask - 1;
795 result[i] = wc;
797 result[i] = 0;
799 if (items_written)
800 *items_written = i;
802 return result;
805 static gpointer
806 try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
808 gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
809 if (ptr == NULL)
810 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
811 _("Failed to allocate memory"));
812 return ptr;
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.
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.
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.
841 gunichar *
842 g_utf8_to_ucs4 (const gchar *str,
843 glong len,
844 glong *items_read,
845 glong *items_written,
846 GError **error)
848 gunichar *result = NULL;
849 gint n_chars, i;
850 const gchar *in;
852 in = str;
853 n_chars = 0;
854 while ((len < 0 || str + len - in > 0) && *in)
856 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
857 if (wc & 0x80000000)
859 if (wc == (gunichar)-2)
861 if (items_read)
862 break;
863 else
864 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
865 _("Partial character sequence at end of input"));
867 else
868 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
869 _("Invalid byte sequence in conversion input"));
871 goto err_out;
874 n_chars++;
876 in = g_utf8_next_char (in);
879 result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
880 if (result == NULL)
881 goto err_out;
883 in = str;
884 for (i=0; i < n_chars; i++)
886 result[i] = g_utf8_get_char (in);
887 in = g_utf8_next_char (in);
889 result[i] = 0;
891 if (items_written)
892 *items_written = n_chars;
894 err_out:
895 if (items_read)
896 *items_read = in - str;
898 return result;
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.
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.
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.
923 gchar *
924 g_ucs4_to_utf8 (const gunichar *str,
925 glong len,
926 glong *items_read,
927 glong *items_written,
928 GError **error)
930 gint result_length;
931 gchar *result = NULL;
932 gchar *p;
933 gint i;
935 result_length = 0;
936 for (i = 0; len < 0 || i < len ; i++)
938 if (!str[i])
939 break;
941 if (str[i] >= 0x80000000)
943 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
944 _("Character out of range for UTF-8"));
945 goto err_out;
948 result_length += UTF8_LENGTH (str[i]);
951 result = try_malloc_n (result_length + 1, 1, error);
952 if (result == NULL)
953 goto err_out;
955 p = result;
957 i = 0;
958 while (p < result + result_length)
959 p += g_unichar_to_utf8 (str[i++], p);
961 *p = '\0';
963 if (items_written)
964 *items_written = p - result;
966 err_out:
967 if (items_read)
968 *items_read = i;
970 return result;
973 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
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.
991 * Convert a string from UTF-16 to UTF-8. The result will be
992 * terminated with a 0 byte.
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.
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.
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.
1009 gchar *
1010 g_utf16_to_utf8 (const gunichar2 *str,
1011 glong len,
1012 glong *items_read,
1013 glong *items_written,
1014 GError **error)
1016 /* This function and g_utf16_to_ucs4 are almost exactly identical -
1017 * The lines that differ are marked.
1019 const gunichar2 *in;
1020 gchar *out;
1021 gchar *result = NULL;
1022 gint n_bytes;
1023 gunichar high_surrogate;
1025 g_return_val_if_fail (str != NULL, NULL);
1027 n_bytes = 0;
1028 in = str;
1029 high_surrogate = 0;
1030 while ((len < 0 || in - str < len) && *in)
1032 gunichar2 c = *in;
1033 gunichar wc;
1035 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1037 if (high_surrogate)
1039 wc = SURROGATE_VALUE (high_surrogate, c);
1040 high_surrogate = 0;
1042 else
1044 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1045 _("Invalid sequence in conversion input"));
1046 goto err_out;
1049 else
1051 if (high_surrogate)
1053 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1054 _("Invalid sequence in conversion input"));
1055 goto err_out;
1058 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1060 high_surrogate = c;
1061 goto next1;
1063 else
1064 wc = c;
1067 /********** DIFFERENT for UTF8/UCS4 **********/
1068 n_bytes += UTF8_LENGTH (wc);
1070 next1:
1071 in++;
1074 if (high_surrogate && !items_read)
1076 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1077 _("Partial character sequence at end of input"));
1078 goto err_out;
1081 /* At this point, everything is valid, and we just need to convert
1083 /********** DIFFERENT for UTF8/UCS4 **********/
1084 result = try_malloc_n (n_bytes + 1, 1, error);
1085 if (result == NULL)
1086 goto err_out;
1088 high_surrogate = 0;
1089 out = result;
1090 in = str;
1091 while (out < result + n_bytes)
1093 gunichar2 c = *in;
1094 gunichar wc;
1096 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1098 wc = SURROGATE_VALUE (high_surrogate, c);
1099 high_surrogate = 0;
1101 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1103 high_surrogate = c;
1104 goto next2;
1106 else
1107 wc = c;
1109 /********** DIFFERENT for UTF8/UCS4 **********/
1110 out += g_unichar_to_utf8 (wc, out);
1112 next2:
1113 in++;
1116 /********** DIFFERENT for UTF8/UCS4 **********/
1117 *out = '\0';
1119 if (items_written)
1120 /********** DIFFERENT for UTF8/UCS4 **********/
1121 *items_written = out - result;
1123 err_out:
1124 if (items_read)
1125 *items_read = in - str;
1127 return result;
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.
1146 * Convert a string from UTF-16 to UCS-4. The result will be
1147 * nul-terminated.
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.
1153 gunichar *
1154 g_utf16_to_ucs4 (const gunichar2 *str,
1155 glong len,
1156 glong *items_read,
1157 glong *items_written,
1158 GError **error)
1160 const gunichar2 *in;
1161 gchar *out;
1162 gchar *result = NULL;
1163 gint n_bytes;
1164 gunichar high_surrogate;
1166 g_return_val_if_fail (str != NULL, NULL);
1168 n_bytes = 0;
1169 in = str;
1170 high_surrogate = 0;
1171 while ((len < 0 || in - str < len) && *in)
1173 gunichar2 c = *in;
1175 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1177 if (high_surrogate)
1179 high_surrogate = 0;
1181 else
1183 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1184 _("Invalid sequence in conversion input"));
1185 goto err_out;
1188 else
1190 if (high_surrogate)
1192 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1193 _("Invalid sequence in conversion input"));
1194 goto err_out;
1197 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1199 high_surrogate = c;
1200 goto next1;
1204 /********** DIFFERENT for UTF8/UCS4 **********/
1205 n_bytes += sizeof (gunichar);
1207 next1:
1208 in++;
1211 if (high_surrogate && !items_read)
1213 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1214 _("Partial character sequence at end of input"));
1215 goto err_out;
1218 /* At this point, everything is valid, and we just need to convert
1220 /********** DIFFERENT for UTF8/UCS4 **********/
1221 result = try_malloc_n (n_bytes + 4, 1, error);
1222 if (result == NULL)
1223 goto err_out;
1225 high_surrogate = 0;
1226 out = result;
1227 in = str;
1228 while (out < result + n_bytes)
1230 gunichar2 c = *in;
1231 gunichar wc;
1233 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1235 wc = SURROGATE_VALUE (high_surrogate, c);
1236 high_surrogate = 0;
1238 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1240 high_surrogate = c;
1241 goto next2;
1243 else
1244 wc = c;
1246 /********** DIFFERENT for UTF8/UCS4 **********/
1247 *(gunichar *)out = wc;
1248 out += sizeof (gunichar);
1250 next2:
1251 in++;
1254 /********** DIFFERENT for UTF8/UCS4 **********/
1255 *(gunichar *)out = 0;
1257 if (items_written)
1258 /********** DIFFERENT for UTF8/UCS4 **********/
1259 *items_written = (out - result) / sizeof (gunichar);
1261 err_out:
1262 if (items_read)
1263 *items_read = in - str;
1265 return (gunichar *)result;
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.
1284 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1285 * added to the result after the converted text.
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.
1291 gunichar2 *
1292 g_utf8_to_utf16 (const gchar *str,
1293 glong len,
1294 glong *items_read,
1295 glong *items_written,
1296 GError **error)
1298 gunichar2 *result = NULL;
1299 gint n16;
1300 const gchar *in;
1301 gint i;
1303 g_return_val_if_fail (str != NULL, NULL);
1305 in = str;
1306 n16 = 0;
1307 while ((len < 0 || str + len - in > 0) && *in)
1309 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1310 if (wc & 0x80000000)
1312 if (wc == (gunichar)-2)
1314 if (items_read)
1315 break;
1316 else
1317 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1318 _("Partial character sequence at end of input"));
1320 else
1321 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1322 _("Invalid byte sequence in conversion input"));
1324 goto err_out;
1327 if (wc < 0xd800)
1328 n16 += 1;
1329 else if (wc < 0xe000)
1331 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1332 _("Invalid sequence in conversion input"));
1334 goto err_out;
1336 else if (wc < 0x10000)
1337 n16 += 1;
1338 else if (wc < 0x110000)
1339 n16 += 2;
1340 else
1342 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1343 _("Character out of range for UTF-16"));
1345 goto err_out;
1348 in = g_utf8_next_char (in);
1351 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1352 if (result == NULL)
1353 goto err_out;
1355 in = str;
1356 for (i = 0; i < n16;)
1358 gunichar wc = g_utf8_get_char (in);
1360 if (wc < 0x10000)
1362 result[i++] = wc;
1364 else
1366 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1367 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1370 in = g_utf8_next_char (in);
1373 result[i] = 0;
1375 if (items_written)
1376 *items_written = n16;
1378 err_out:
1379 if (items_read)
1380 *items_read = in - str;
1382 return result;
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.
1400 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1401 * added to the result after the converted text.
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.
1407 gunichar2 *
1408 g_ucs4_to_utf16 (const gunichar *str,
1409 glong len,
1410 glong *items_read,
1411 glong *items_written,
1412 GError **error)
1414 gunichar2 *result = NULL;
1415 gint n16;
1416 gint i, j;
1418 n16 = 0;
1419 i = 0;
1420 while ((len < 0 || i < len) && str[i])
1422 gunichar wc = str[i];
1424 if (wc < 0xd800)
1425 n16 += 1;
1426 else if (wc < 0xe000)
1428 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1429 _("Invalid sequence in conversion input"));
1431 goto err_out;
1433 else if (wc < 0x10000)
1434 n16 += 1;
1435 else if (wc < 0x110000)
1436 n16 += 2;
1437 else
1439 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1440 _("Character out of range for UTF-16"));
1442 goto err_out;
1445 i++;
1448 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1449 if (result == NULL)
1450 goto err_out;
1452 for (i = 0, j = 0; j < n16; i++)
1454 gunichar wc = str[i];
1456 if (wc < 0x10000)
1458 result[j++] = wc;
1460 else
1462 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1463 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1466 result[j] = 0;
1468 if (items_written)
1469 *items_written = n16;
1471 err_out:
1472 if (items_read)
1473 *items_read = i;
1475 return result;
1478 #define VALIDATE_BYTE(mask, expect) \
1479 G_STMT_START { \
1480 if (G_UNLIKELY((*(guchar *)p & (mask)) != (expect))) \
1481 goto error; \
1482 } G_STMT_END
1484 /* see IETF RFC 3629 Section 4 */
1486 static const gchar *
1487 fast_validate (const char *str)
1490 const gchar *p;
1492 for (p = str; *p; p++)
1494 if (*(guchar *)p < 128)
1495 /* done */;
1496 else
1498 const gchar *last;
1500 last = p;
1501 if (*(guchar *)p < 0xe0) /* 110xxxxx */
1503 if (G_UNLIKELY (*(guchar *)p < 0xc2))
1504 goto error;
1506 else
1508 if (*(guchar *)p < 0xf0) /* 1110xxxx */
1510 switch (*(guchar *)p++ & 0x0f)
1512 case 0:
1513 VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1514 break;
1515 case 0x0d:
1516 VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1517 break;
1518 default:
1519 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1522 else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1524 switch (*(guchar *)p++ & 0x07)
1526 case 0:
1527 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1528 if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1529 goto error;
1530 break;
1531 case 4:
1532 VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1533 break;
1534 default:
1535 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1537 p++;
1538 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1540 else
1541 goto error;
1544 p++;
1545 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1547 continue;
1549 error:
1550 return last;
1554 return p;
1557 static const gchar *
1558 fast_validate_len (const char *str,
1559 gssize max_len)
1562 const gchar *p;
1564 g_assert (max_len >= 0);
1566 for (p = str; ((p - str) < max_len) && *p; p++)
1568 if (*(guchar *)p < 128)
1569 /* done */;
1570 else
1572 const gchar *last;
1574 last = p;
1575 if (*(guchar *)p < 0xe0) /* 110xxxxx */
1577 if (G_UNLIKELY (max_len - (p - str) < 2))
1578 goto error;
1580 if (G_UNLIKELY (*(guchar *)p < 0xc2))
1581 goto error;
1583 else
1585 if (*(guchar *)p < 0xf0) /* 1110xxxx */
1587 if (G_UNLIKELY (max_len - (p - str) < 3))
1588 goto error;
1590 switch (*(guchar *)p++ & 0x0f)
1592 case 0:
1593 VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1594 break;
1595 case 0x0d:
1596 VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1597 break;
1598 default:
1599 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1602 else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1604 if (G_UNLIKELY (max_len - (p - str) < 4))
1605 goto error;
1607 switch (*(guchar *)p++ & 0x07)
1609 case 0:
1610 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1611 if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1612 goto error;
1613 break;
1614 case 4:
1615 VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1616 break;
1617 default:
1618 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1620 p++;
1621 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1623 else
1624 goto error;
1627 p++;
1628 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1630 continue;
1632 error:
1633 return last;
1637 return p;
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
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).
1654 * Note that g_utf8_validate() returns %FALSE if @max_len is
1655 * positive and any of the @max_len bytes are nul.
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.
1662 * Returns: %TRUE if the text was valid UTF-8
1664 gboolean
1665 g_utf8_validate (const char *str,
1666 gssize max_len,
1667 const gchar **end)
1670 const gchar *p;
1672 if (max_len < 0)
1673 p = fast_validate (str);
1674 else
1675 p = fast_validate_len (str, max_len);
1677 if (end)
1678 *end = p;
1680 if ((max_len >= 0 && p != str + max_len) ||
1681 (max_len < 0 && *p != '\0'))
1682 return FALSE;
1683 else
1684 return TRUE;
1688 * g_unichar_validate:
1689 * @ch: a Unicode character
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.
1695 * Returns: %TRUE if @ch is a valid Unicode character
1697 gboolean
1698 g_unichar_validate (gunichar ch)
1700 return UNICODE_VALID (ch);
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.
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.)
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.
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.
1723 * Returns: a newly-allocated string which is the reverse of @str
1725 * Since: 2.2
1727 gchar *
1728 g_utf8_strreverse (const gchar *str,
1729 gssize len)
1731 gchar *r, *result;
1732 const gchar *p;
1734 if (len < 0)
1735 len = strlen (str);
1737 result = g_new (gchar, len + 1);
1738 r = result + len;
1739 p = str;
1740 while (r > result)
1742 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1743 r -= skip;
1744 for (m = r; skip; skip--)
1745 *m++ = *p++;
1747 result[len] = 0;
1749 return result;
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.
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).
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.
1768 * Returns: (transfer full): a valid UTF-8 string whose content resembles @str
1770 * Since: 2.52
1772 gchar *
1773 g_utf8_make_valid (const gchar *str,
1774 gssize len)
1776 GString *string;
1777 const gchar *remainder, *invalid;
1778 gsize remaining_bytes, valid_bytes;
1780 g_return_val_if_fail (str != NULL, NULL);
1782 if (len < 0)
1783 len = strlen (str);
1785 string = NULL;
1786 remainder = str;
1787 remaining_bytes = len;
1789 while (remaining_bytes != 0)
1791 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1792 break;
1793 valid_bytes = invalid - remainder;
1795 if (string == NULL)
1796 string = g_string_sized_new (remaining_bytes);
1798 g_string_append_len (string, remainder, valid_bytes);
1799 /* append U+FFFD REPLACEMENT CHARACTER */
1800 g_string_append (string, "\357\277\275");
1802 remaining_bytes -= valid_bytes + 1;
1803 remainder = invalid + 1;
1806 if (string == NULL)
1807 return g_strndup (str, len);
1809 g_string_append_len (string, remainder, remaining_bytes);
1810 g_string_append_c (string, '\0');
1812 g_assert (g_utf8_validate (string->str, -1, NULL));
1814 return g_string_free (string, FALSE);