Break some long lines.
[platform/upstream/glib.git] / glib / gutf8.c
index abf9dee..07ef84f 100644 (file)
@@ -28,6 +28,7 @@
 #include <string.h>
 
 #include "glib.h"
+#include "galias.h"
 
 #ifdef G_PLATFORM_WIN32
 #include <stdio.h>
@@ -283,6 +284,11 @@ g_utf8_get_char (const gchar *p)
  * Converts from an integer character offset to a pointer to a position
  * within the string.
  * 
+ * Since 2.10, this function allows to pass a negative @offset to
+ * step backwards. It is usually worth stepping backwards from the end
+ * instead of forwards if @offset is in the last fourth of the string, 
+ * since moving forward is about 3 times faster than moving backward.
+ * 
  * Return value: the resulting pointer
  **/
 gchar *
@@ -290,9 +296,29 @@ g_utf8_offset_to_pointer  (const gchar *str,
                           glong        offset)    
 {
   const gchar *s = str;
-  while (offset--)
-    s = g_utf8_next_char (s);
-  
+
+  if (offset > 0) 
+    while (offset--)
+      s = g_utf8_next_char (s);
+  else
+    {
+      const char *s1;
+
+      /* This nice technique for fast backwards stepping 
+       * through a UTF-8 string was dubbed "stutter stepping" 
+       * by its inventor, Larry Ewing.
+       */
+      while (offset)
+       {
+         s1 = s;
+         s += offset;
+         while ((*s & 0xc0) == 0x80)
+           s--;
+
+         offset += g_utf8_pointer_to_offset (s, s1);
+       }
+    }
+
   return (gchar *)s;
 }
 
@@ -303,6 +329,9 @@ g_utf8_offset_to_pointer  (const gchar *str,
  * 
  * Converts from a pointer to position within a string to a integer
  * character offset.
+ *
+ * Since 2.10, this function allows @pos to be before @str, and returns
+ * a negative offset in this case.
  * 
  * Return value: the resulting character offset
  **/
@@ -312,13 +341,16 @@ g_utf8_pointer_to_offset (const gchar *str,
 {
   const gchar *s = str;
   glong offset = 0;    
-  
-  while (s < pos)
-    {
-      s = g_utf8_next_char (s);
-      offset++;
-    }
 
+  if (pos < str) 
+    offset = - g_utf8_pointer_to_offset (pos, str);
+  else
+    while (s < pos)
+      {
+       s = g_utf8_next_char (s);
+       offset++;
+      }
+  
   return offset;
 }
 
@@ -329,7 +361,7 @@ g_utf8_pointer_to_offset (const gchar *str,
  * @src: UTF-8 encoded string
  * @n: character count
  * 
- * Like the standard C <function>strncpy()</function> function, but 
+ * Like the standard C strncpy() function, but 
  * copies a given number of characters instead of a given number of 
  * bytes. The @src string must be valid UTF-8 encoded text. 
  * (Use g_utf8_validate() on all text before trying to use UTF-8 
@@ -522,7 +554,7 @@ g_get_charset (G_CONST_RETURN char **charset)
 
 /**
  * g_unichar_to_utf8:
- * @c: a ISO10646 character code
+ * @c: a Unicode character code
  * @outbuf: output buffer, must have at least 6 bytes of space.
  *       If %NULL, the length will be computed and returned
  *       and nothing will be written to @outbuf.
@@ -535,6 +567,7 @@ int
 g_unichar_to_utf8 (gunichar c,
                   gchar   *outbuf)
 {
+  /* If this gets modified, also update the copy in g_string_insert_unichar() */
   guint len = 0;    
   int first;
   int i;
@@ -587,9 +620,9 @@ g_unichar_to_utf8 (gunichar c,
  * g_utf8_strchr:
  * @p: a nul-terminated UTF-8 encoded string
  * @len: the maximum length of @p
- * @c: a ISO10646 character
+ * @c: a Unicode character
  * 
- * Finds the leftmost occurrence of the given ISO10646 character
+ * Finds the leftmost occurrence of the given Unicode character
  * in a UTF-8 encoded string, while limiting the search to @len bytes.
  * If @len is -1, allow unbounded search.
  * 
@@ -615,9 +648,9 @@ g_utf8_strchr (const char *p,
  * g_utf8_strrchr:
  * @p: a nul-terminated UTF-8 encoded string
  * @len: the maximum length of @p
- * @c: a ISO10646 character
+ * @c: a Unicode character
  * 
- * Find the rightmost occurrence of the given ISO10646 character
+ * Find the rightmost occurrence of the given Unicode character
  * in a UTF-8 encoded string, while limiting the search to @len bytes.
  * If @len is -1, allow unbounded search.
  * 
@@ -730,9 +763,9 @@ g_utf8_get_char_extended (const  gchar *p,
  * overlong encodings of valid characters.
  * 
  * Return value: the resulting character. If @p points to a partial
- *    sequence at the end of a string that could begin a valid character,
- *    returns (gunichar)-2; otherwise, if @p does not point to a valid
- *    UTF-8 encoded Unicode character, returns (gunichar)-1.
+ *    sequence at the end of a string that could begin a valid 
+ *    character, returns (gunichar)-2; otherwise, if @p does not point 
+ *    to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.
  **/
 gunichar
 g_utf8_get_char_validated (const  gchar *p,
@@ -894,7 +927,7 @@ g_utf8_to_ucs4 (const gchar *str,
   n_chars = 0;
   while ((len < 0 || str + len - in > 0) && *in)
     {
-      gunichar wc = g_utf8_get_char_extended (in, str + len - in);
+      gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
       if (wc & 0x80000000)
        {
          if (wc == (gunichar)-2)
@@ -940,9 +973,9 @@ g_utf8_to_ucs4 (const gchar *str,
 /**
  * g_ucs4_to_utf8:
  * @str: a UCS-4 encoded string
- * @len: the maximum length of @str to use. If @len < 0, then
- *       the string is terminated with a 0 character.
- * @items_read: location to store number of characters read read, or %NULL.
+ * @len: the maximum length (number of characters) of @str to use. 
+ *       If @len < 0, then the string is terminated with a 0 character.
+ * @items_read: location to store number of characters read, or %NULL.
  * @items_written: location to store number of bytes written or %NULL.
  *                 The value here stored does not include the trailing 0
  *                 byte. 
@@ -956,7 +989,9 @@ g_utf8_to_ucs4 (const gchar *str,
  * Return value: a pointer to a newly allocated UTF-8 string.
  *               This value must be freed with g_free(). If an
  *               error occurs, %NULL will be returned and
- *               @error set.
+ *               @error set. In that case, @items_read will be
+ *               set to the position of the first invalid input 
+ *               character.
  **/
 gchar *
 g_ucs4_to_utf8 (const gunichar *str,
@@ -978,9 +1013,6 @@ g_ucs4_to_utf8 (const gunichar *str,
 
       if (str[i] >= 0x80000000)
        {
-         if (items_read)
-           *items_read = i;
-         
          g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
                       _("Character out of range for UTF-8"));
          goto err_out;
@@ -1013,8 +1045,8 @@ g_ucs4_to_utf8 (const gunichar *str,
 /**
  * g_utf16_to_utf8:
  * @str: a UTF-16 encoded string
- * @len: the maximum length of @str to use. If @len < 0, then
- *       the string is terminated with a 0 character.
+ * @len: the maximum length (number of <type>gunichar2</type>) of @str to use. 
+ *       If @len < 0, then the string is terminated with a 0 character.
  * @items_read: location to store number of words read, or %NULL.
  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
  *              returned in case @str contains a trailing partial
@@ -1029,6 +1061,11 @@ g_ucs4_to_utf8 (const gunichar *str,
  *
  * Convert a string from UTF-16 to UTF-8. The result will be
  * terminated with a 0 byte.
+ *
+ * Note that the input is expected to be already in native endianness,
+ * an initial byte-order-mark character is not handled specially.
+ * g_convert() can be used to convert a byte buffer of UTF-16 data of 
+ * ambiguous endianess.
  * 
  * Return value: a pointer to a newly allocated UTF-8 string.
  *               This value must be freed with g_free(). If an
@@ -1157,8 +1194,8 @@ g_utf16_to_utf8 (const gunichar2  *str,
 /**
  * g_utf16_to_ucs4:
  * @str: a UTF-16 encoded string
- * @len: the maximum length of @str to use. If @len < 0, then
- *       the string is terminated with a 0 character.
+ * @len: the maximum length (number of <type>gunichar2</type>) of @str to use. 
+ *       If @len < 0, then the string is terminated with a 0 character.
  * @items_read: location to store number of words read, or %NULL.
  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
  *              returned in case @str contains a trailing partial
@@ -1299,21 +1336,21 @@ g_utf16_to_ucs4 (const gunichar2  *str,
 /**
  * g_utf8_to_utf16:
  * @str: a UTF-8 encoded string
- * @len: the maximum length of @str to use. If @len < 0, then
- *       the string is nul-terminated.
+ * @len: the maximum length (number of characters) of @str to use. 
+ *       If @len < 0, then the string is nul-terminated.
  * @items_read: location to store number of bytes read, or %NULL.
  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
  *              returned in case @str contains a trailing partial
  *              character. If an error occurs then the index of the
  *              invalid input is stored here.
- * @items_written: location to store number of words written, or %NULL.
- *                 The value stored here does not include the trailing
- *                 0 word.
+ * @items_written: location to store number of <type>gunichar2</type> written, 
+ *                 or %NULL.
+ *                 The value stored here does not include the trailing 0.
  * @error: location to store the error occuring, or %NULL to ignore
  *         errors. Any of the errors in #GConvertError other than
  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
  *
- * Convert a string from UTF-8 to UTF-16. A 0 word will be
+ * Convert a string from UTF-8 to UTF-16. A 0 character will be
  * added to the result after the converted text.
  * 
  * Return value: a pointer to a newly allocated UTF-16 string.
@@ -1339,7 +1376,7 @@ g_utf8_to_utf16 (const gchar *str,
   n16 = 0;
   while ((len < 0 || str + len - in > 0) && *in)
     {
-      gunichar wc = g_utf8_get_char_extended (in, str + len - in);
+      gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
       if (wc & 0x80000000)
        {
          if (wc == (gunichar)-2)
@@ -1416,19 +1453,19 @@ g_utf8_to_utf16 (const gchar *str,
 /**
  * g_ucs4_to_utf16:
  * @str: a UCS-4 encoded string
- * @len: the maximum length of @str to use. If @len < 0, then
- *       the string is terminated with a 0 character.
+ * @len: the maximum length (number of characters) of @str to use. 
+ *       If @len < 0, then the string is terminated with a 0 character.
  * @items_read: location to store number of bytes read, or %NULL.
  *              If an error occurs then the index of the invalid input
  *              is stored here.
- * @items_written: location to store number of words written, or %NULL.
- *                 The value stored here does not include the trailing
- *                 0 word.
+ * @items_written: location to store number of <type>gunichar2</type> 
+ *                 written, or %NULL. The value stored here does not 
+ *                 include the trailing 0.
  * @error: location to store the error occuring, or %NULL to ignore
  *         errors. Any of the errors in #GConvertError other than
  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
  *
- * Convert a string from UCS-4 to UTF-16. A 0 word will be
+ * Convert a string from UCS-4 to UTF-16. A 0 character will be
  * added to the result after the converted text.
  * 
  * Return value: a pointer to a newly allocated UTF-16 string.
@@ -1505,19 +1542,171 @@ g_ucs4_to_utf16 (const gunichar  *str,
   return result;
 }
 
+#define CONTINUATION_CHAR                           \
+ G_STMT_START {                                     \
+  if ((*(guchar *)p & 0xc0) != 0x80) /* 10xxxxxx */ \
+    goto error;                                     \
+  val <<= 6;                                        \
+  val |= (*(guchar *)p) & 0x3f;                     \
+ } G_STMT_END
+
+static const gchar *
+fast_validate (const char *str)
+
+{
+  gunichar val = 0;
+  gunichar min = 0;
+  const gchar *p;
+
+  for (p = str; *p; p++)
+    {
+      if (*(guchar *)p < 128)
+       /* done */;
+      else 
+       {
+         const gchar *last;
+         
+         last = p;
+         if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
+           {
+             if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
+               goto error;
+             p++;
+             if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
+               goto error;
+           }
+         else
+           {
+             if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
+               {
+                 min = (1 << 11);
+                 val = *(guchar *)p & 0x0f;
+                 goto TWO_REMAINING;
+               }
+             else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
+               {
+                 min = (1 << 16);
+                 val = *(guchar *)p & 0x07;
+               }
+             else
+               goto error;
+             
+             p++;
+             CONTINUATION_CHAR;
+           TWO_REMAINING:
+             p++;
+             CONTINUATION_CHAR;
+             p++;
+             CONTINUATION_CHAR;
+             
+             if (G_UNLIKELY (val < min))
+               goto error;
+
+             if (G_UNLIKELY (!UNICODE_VALID(val)))
+               goto error;
+           } 
+         
+         continue;
+         
+       error:
+         return last;
+       }
+    }
+
+  return p;
+}
+
+static const gchar *
+fast_validate_len (const char *str,
+                  gssize      max_len)
+
+{
+  gunichar val = 0;
+  gunichar min = 0;
+  const gchar *p;
+
+  for (p = str; (max_len < 0 || (p - str) < max_len) && *p; p++)
+    {
+      if (*(guchar *)p < 128)
+       /* done */;
+      else 
+       {
+         const gchar *last;
+         
+         last = p;
+         if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
+           {
+             if (G_UNLIKELY (max_len >= 0 && max_len - (p - str) < 2))
+               goto error;
+             
+             if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
+               goto error;
+             p++;
+             if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
+               goto error;
+           }
+         else
+           {
+             if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
+               {
+                 if (G_UNLIKELY (max_len >= 0 && max_len - (p - str) < 3))
+                   goto error;
+                 
+                 min = (1 << 11);
+                 val = *(guchar *)p & 0x0f;
+                 goto TWO_REMAINING;
+               }
+             else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
+               {
+                 if (G_UNLIKELY (max_len >= 0 && max_len - (p - str) < 4))
+                   goto error;
+                 
+                 min = (1 << 16);
+                 val = *(guchar *)p & 0x07;
+               }
+             else
+               goto error;
+             
+             p++;
+             CONTINUATION_CHAR;
+           TWO_REMAINING:
+             p++;
+             CONTINUATION_CHAR;
+             p++;
+             CONTINUATION_CHAR;
+             
+             if (G_UNLIKELY (val < min))
+               goto error;
+             if (G_UNLIKELY (!UNICODE_VALID(val)))
+               goto error;
+           } 
+         
+         continue;
+         
+       error:
+         return last;
+       }
+    }
+
+  return p;
+}
+
 /**
  * g_utf8_validate:
  * @str: a pointer to character data
- * @max_len: max bytes to validate, or -1 to go until nul
+ * @max_len: max bytes to validate, or -1 to go until NUL
  * @end: return location for end of valid data
  * 
  * Validates UTF-8 encoded text. @str is the text to validate;
  * if @str is nul-terminated, then @max_len can be -1, otherwise
  * @max_len should be the number of bytes to validate.
  * If @end is non-%NULL, then the end of the valid range
- * will be stored there (i.e. the address of the first invalid byte
- * if some bytes were invalid, or the end of the text being validated
- * otherwise).
+ * will be stored there (i.e. the start of the first invalid 
+ * character if some bytes were invalid, or the end of the text 
+ * being validated otherwise).
+ *
+ * Note that g_utf8_validate() returns %FALSE if @max_len is 
+ * positive and NUL is met before @max_len bytes have been read.
  *
  * Returns %TRUE if all of @str was valid. Many GLib and GTK+
  * routines <emphasis>require</emphasis> valid UTF-8 as input;
@@ -1527,66 +1716,29 @@ g_ucs4_to_utf16 (const gunichar  *str,
  * Return value: %TRUE if the text was valid UTF-8
  **/
 gboolean
-g_utf8_validate (const gchar  *str,
-                 gssize        max_len,    
-                 const gchar **end)
-{
+g_utf8_validate (const char   *str,
+                gssize        max_len,    
+                const gchar **end)
 
+{
   const gchar *p;
 
-  g_return_val_if_fail (str != NULL, FALSE);
-  
-  if (end)
-    *end = str;
-  
-  p = str;
-  
-  while ((max_len < 0 || (p - str) < max_len) && *p)
-    {
-      int i, mask = 0, len;
-      gunichar result;
-      unsigned char c = (unsigned char) *p;
-      
-      UTF8_COMPUTE (c, mask, len);
-
-      if (len == -1)
-        break;
-
-      /* check that the expected number of bytes exists in str */
-      if (max_len >= 0 &&
-          ((max_len - (p - str)) < len))
-        break;
-        
-      UTF8_GET (result, p, i, mask, len);
-
-      if (UTF8_LENGTH (result) != len) /* Check for overlong UTF-8 */
-       break;
-
-      if (result == (gunichar)-1)
-        break;
-
-      if (!UNICODE_VALID (result))
-       break;
-      
-      p += len;
-    }
+  if (max_len < 0)
+    p = fast_validate (str);
+  else
+    p = fast_validate_len (str, max_len);
 
   if (end)
     *end = p;
 
-  /* See that we covered the entire length if a length was
-   * passed in, or that we ended on a nul if not
-   */
-  if (max_len >= 0 &&
-      p != (str + max_len))
-    return FALSE;
-  else if (max_len < 0 &&
-           *p != '\0')
+  if ((max_len >= 0 && p != str + max_len) ||
+      (max_len < 0 && *p != '\0'))
     return FALSE;
   else
     return TRUE;
 }
 
+
 /**
  * g_unichar_validate:
  * @ch: a Unicode character
@@ -1646,3 +1798,6 @@ g_utf8_strreverse (const gchar *str,
 
   return result;
 }
+
+#define __G_UTF8_C__
+#include "galiasdef.c"