Break some long lines.
[platform/upstream/glib.git] / glib / gutf8.c
index d1863e9..07ef84f 100644 (file)
@@ -28,6 +28,7 @@
 #include <string.h>
 
 #include "glib.h"
+#include "galias.h"
 
 #ifdef G_PLATFORM_WIN32
 #include <stdio.h>
@@ -36,6 +37,8 @@
 #undef STRICT
 #endif
 
+#include "libcharset/libcharset.h"
+
 #include "glibintl.h"
 
 #define UTF8_COMPUTE(Char, Mask, Len)                                        \
 
 #define UNICODE_VALID(Char)                   \
     ((Char) < 0x110000 &&                     \
-     ((Char) < 0xD800 || (Char) >= 0xE000) && \
-     (Char) != 0xFFFE && (Char) != 0xFFFF)
+     (((Char) & 0xFFFFF800) != 0xD800) &&     \
+     ((Char) < 0xFDD0 || (Char) > 0xFDEF) &&  \
+     ((Char) & 0xFFFE) != 0xFFFE)
    
      
-gchar g_utf8_skip[256] = {
+static const gchar utf8_skip_data[256] = {
   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,
   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,
   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,
@@ -107,19 +111,21 @@ gchar g_utf8_skip[256] = {
   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,
   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,
   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,
-  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,0,0
+  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
 };
 
+const gchar * const g_utf8_skip = utf8_skip_data;
+
 /**
  * g_utf8_find_prev_char:
- * @str: pointer to the beginning of a UTF-8 string
+ * @str: pointer to the beginning of a UTF-8 encoded string
  * @p: pointer to some position within @str
  * 
  * Given a position @p with a UTF-8 encoded string @str, find the start
  * of the previous UTF-8 character starting before @p. Returns %NULL if no
  * UTF-8 characters are present in @p before @str.
  *
- * @p does not have to be at the beginning of a UTF-8 chracter. No check
+ * @p does not have to be at the beginning of a UTF-8 character. No check
  * is made to see if the character found is actually valid other than
  * it starts with an appropriate byte.
  *
@@ -129,7 +135,7 @@ gchar *
 g_utf8_find_prev_char (const char *str,
                       const char *p)
 {
-  for (--p; p > str; --p)
+  for (--p; p >= str; --p)
     {
       if ((*p & 0xc0) != 0x80)
        return (gchar *)p;
@@ -141,12 +147,12 @@ g_utf8_find_prev_char (const char *str,
  * g_utf8_find_next_char:
  * @p: a pointer to a position within a UTF-8 encoded string
  * @end: a pointer to the end of the string, or %NULL to indicate
- *        that the string is NULL terminated, in which case
+ *        that the string is nul-terminated, in which case
  *        the returned value will be 
  *
- * Find the start of the next utf-8 character in the string after @p
+ * Finds the start of the next UTF-8 character in the string after @p.
  *
- * @p does not have to be at the beginning of a UTF-8 chracter. No check
+ * @p does not have to be at the beginning of a UTF-8 character. No check
  * is made to see if the character found is actually valid other than
  * it starts with an appropriate byte.
  * 
@@ -172,12 +178,12 @@ g_utf8_find_next_char (const gchar *p,
  * g_utf8_prev_char:
  * @p: a pointer to a position within a UTF-8 encoded string
  *
- * Find the previous UTF-8 character in the string before @p.
+ * Finds the previous UTF-8 character in the string before @p.
  *
  * @p does not have to be at the beginning of a UTF-8 character. No check
  * is made to see if the character found is actually valid other than
  * it starts with an appropriate byte. If @p might be the first
- * character of the string, you must use g_utf8_find_prev_char instead.
+ * character of the string, you must use g_utf8_find_prev_char() instead.
  * 
  * Return value: a pointer to the found character.
  **/
@@ -194,11 +200,14 @@ g_utf8_prev_char (const gchar *p)
 
 /**
  * g_utf8_strlen:
- * @p: pointer to the start of a UTF-8 string.
+ * @p: pointer to the start of a UTF-8 encoded string.
  * @max: the maximum number of bytes to examine. If @max
  *       is less than 0, then the string is assumed to be
- *       nul-terminated.
+ *       nul-terminated. If @max is 0, @p will not be examined and 
+ *       may be %NULL.
  * 
+ * Returns the length of the string in characters.
+ *
  * Return value: the length of the string in characters
  **/
 glong
@@ -207,6 +216,7 @@ g_utf8_strlen (const gchar *p,
 {
   glong len = 0;
   const gchar *start = p;
+  g_return_val_if_fail (p != NULL || max == 0, 0);
 
   if (max < 0)
     {
@@ -241,11 +251,13 @@ g_utf8_strlen (const gchar *p,
 
 /**
  * g_utf8_get_char:
- * @p: a pointer to unicode character encoded as UTF-8
+ * @p: a pointer to Unicode character encoded as UTF-8
  * 
- * Convert a sequence of bytes encoded as UTF-8 to a unicode character.
+ * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
  * If @p does not point to a valid UTF-8 encoded character, results are
- * undefined.
+ * undefined. If you are not sure that the bytes are complete
+ * valid Unicode characters, you should use g_utf8_get_char_validated()
+ * instead.
  * 
  * Return value: the resulting character
  **/
@@ -267,11 +279,16 @@ g_utf8_get_char (const gchar *p)
 /**
  * g_utf8_offset_to_pointer:
  * @str: a UTF-8 encoded string
- * @offset: a character offset within the string.
+ * @offset: a character offset within @str
  * 
  * 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 *
@@ -279,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;
 }
 
@@ -291,7 +328,10 @@ g_utf8_offset_to_pointer  (const gchar *str,
  * @pos: a pointer to a position within @str
  * 
  * Converts from a pointer to position within a string to a integer
- * character offset
+ * 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
  **/
@@ -301,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;
 }
 
@@ -315,18 +358,21 @@ g_utf8_pointer_to_offset (const gchar *str,
 /**
  * g_utf8_strncpy:
  * @dest: buffer to fill with characters from @src
- * @src: UTF-8 string
+ * @src: UTF-8 encoded string
  * @n: character count
  * 
- * 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 utility functions with it.)
+ * 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 
+ * utility functions with it.)
  * 
  * Return value: @dest
  **/
 gchar *
-g_utf8_strncpy (gchar *dest, const gchar *src, size_t n)
+g_utf8_strncpy (gchar       *dest,
+               const gchar *src,
+               gsize        n)
 {
   const gchar *s = src;
   while (n && *s)
@@ -339,60 +385,120 @@ g_utf8_strncpy (gchar *dest, const gchar *src, size_t n)
   return dest;
 }
 
-static gboolean
-g_utf8_get_charset_internal (char **a)
-{
-  char *charset = getenv("CHARSET");
+G_LOCK_DEFINE_STATIC (aliases);
 
-  if (charset && a && ! *a)
-    *a = charset;
+static GHashTable *
+get_alias_hash (void)
+{
+  static GHashTable *alias_hash = NULL;
+  const char *aliases;
 
-  if (charset && strstr (charset, "UTF-8"))
-      return TRUE;
+  G_LOCK (aliases);
 
-#ifdef HAVE_CODESET
-  charset = nl_langinfo(CODESET);
-  if (charset)
+  if (!alias_hash)
     {
-      if (a && ! *a)
-       *a = charset;
-      if (strcmp (charset, "UTF-8") == 0)
-       return TRUE;
+      alias_hash = g_hash_table_new (g_str_hash, g_str_equal);
+      
+      aliases = _g_locale_get_charset_aliases ();
+      while (*aliases != '\0')
+       {
+         const char *canonical;
+         const char *alias;
+         const char **alias_array;
+         int count = 0;
+         
+         alias = aliases;
+         aliases += strlen (aliases) + 1;
+         canonical = aliases;
+         aliases += strlen (aliases) + 1;
+         
+         alias_array = g_hash_table_lookup (alias_hash, canonical);
+         if (alias_array)
+           {
+             while (alias_array[count])
+               count++;
+           }
+         
+         alias_array = g_renew (const char *, alias_array, count + 2);
+         alias_array[count] = alias;
+         alias_array[count + 1] = NULL;
+         
+         g_hash_table_insert (alias_hash, (char *)canonical, alias_array);
+       }
     }
-#endif
-  
-#if 0 /* #ifdef _NL_CTYPE_CODESET_NAME */
-  charset = nl_langinfo (_NL_CTYPE_CODESET_NAME);
-  if (charset)
+
+  G_UNLOCK (aliases);
+
+  return alias_hash;
+}
+
+/* As an abuse of the alias table, the following routines gets
+ * the charsets that are aliases for the canonical name.
+ */
+const char **
+_g_charset_get_aliases (const char *canonical_name)
+{
+  GHashTable *alias_hash = get_alias_hash ();
+
+  return g_hash_table_lookup (alias_hash, canonical_name);
+}
+
+static gboolean
+g_utf8_get_charset_internal (const char  *raw_data,
+                            const char **a)
+{
+  const char *charset = getenv("CHARSET");
+
+  if (charset && *charset)
     {
-      if (a && ! *a)
-       *a = charset;
-      if (strcmp (charset, "UTF-8") == 0)
+      *a = charset;
+
+      if (charset && strstr (charset, "UTF-8"))
        return TRUE;
+      else
+       return FALSE;
     }
-#endif
 
-#ifdef G_PLATFORM_WIN32
-  if (a && ! *a)
+  /* The libcharset code tries to be thread-safe without
+   * a lock, but has a memory leak and a missing memory
+   * barrier, so we lock for it
+   */
+  G_LOCK (aliases);
+  charset = _g_locale_charset_unalias (raw_data);
+  G_UNLOCK (aliases);
+  
+  if (charset && *charset)
     {
-      static char codepage[10];
+      *a = charset;
       
-      sprintf (codepage, "CP%d", GetACP ());
-      *a = codepage;
-      /* What about codepage 1200? Is that UTF-8? */
-      return FALSE;
+      if (charset && strstr (charset, "UTF-8"))
+       return TRUE;
+      else
+       return FALSE;
     }
-#else
-  if (a && ! *a) 
-    *a = "US-ASCII";
-#endif
 
   /* Assume this for compatibility at present.  */
+  *a = "US-ASCII";
+  
   return FALSE;
 }
 
-static int utf8_locale_cache = -1;
-static char *utf8_charset_cache = NULL;
+typedef struct _GCharsetCache GCharsetCache;
+
+struct _GCharsetCache {
+  gboolean is_utf8;
+  gchar *raw;
+  gchar *charset;
+};
+
+static void
+charset_cache_free (gpointer data)
+{
+  GCharsetCache *cache = data;
+  g_free (cache->raw);
+  g_free (cache->charset);
+  g_free (cache);
+}
 
 /**
  * g_get_charset:
@@ -415,28 +521,45 @@ static char *utf8_charset_cache = NULL;
 gboolean
 g_get_charset (G_CONST_RETURN char **charset) 
 {
-  if (utf8_locale_cache != -1)
+  static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
+  GCharsetCache *cache = g_static_private_get (&cache_private);
+  const gchar *raw;
+
+  if (!cache)
     {
-      if (charset)
-       *charset = utf8_charset_cache;
-      return utf8_locale_cache;
+      cache = g_new0 (GCharsetCache, 1);
+      g_static_private_set (&cache_private, cache, charset_cache_free);
     }
-  utf8_locale_cache = g_utf8_get_charset_internal (&utf8_charset_cache);
-  if (charset) 
-    *charset = utf8_charset_cache;
-  return utf8_locale_cache;
+
+  raw = _g_locale_charset_raw ();
+  
+  if (!(cache->raw && strcmp (cache->raw, raw) == 0))
+    {
+      const gchar *new_charset;
+           
+      g_free (cache->raw);
+      g_free (cache->charset);
+      cache->raw = g_strdup (raw);
+      cache->is_utf8 = g_utf8_get_charset_internal (raw, &new_charset);
+      cache->charset = g_strdup (new_charset);
+    }
+
+  if (charset)
+    *charset = cache->charset;
+  
+  return cache->is_utf8;
 }
 
 /* unicode_strchr */
 
 /**
  * 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 @out.
+ *       and nothing will be written to @outbuf.
  * 
- * Convert a single character to utf8
+ * Converts a single character to UTF-8.
  * 
  * Return value: number of bytes written
  **/
@@ -444,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;
@@ -494,55 +618,57 @@ g_unichar_to_utf8 (gunichar c,
 
 /**
  * g_utf8_strchr:
- * @p: a nul-terminated utf-8 string
- * @p_len: the maximum length of p
- * @c: a iso-10646 character
+ * @p: a nul-terminated UTF-8 encoded string
+ * @len: the maximum length of @p
+ * @c: a Unicode character
  * 
- * Find the leftmost occurence of the given iso-10646 character
- * in a UTF-8 string, while limiting the search to p_len bytes.
- * If len is -1, allow unbounded search.
+ * 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.
  * 
- * Return value: NULL if the string does not contain the character, otherwise, a
- *               a pointer to the start of the leftmost of the character in the string.
+ * Return value: %NULL if the string does not contain the character, 
+ *   otherwise, a pointer to the start of the leftmost occurrence of 
+ *   the character in the string.
  **/
 gchar *
 g_utf8_strchr (const char *p,
-              gssize      p_len,
+              gssize      len,
               gunichar    c)
 {
   gchar ch[10];
 
-  gint len = g_unichar_to_utf8 (c, ch);
-  ch[len] = '\0';
+  gint charlen = g_unichar_to_utf8 (c, ch);
+  ch[charlen] = '\0';
   
-  return g_strstr_len (p, p_len, ch);
+  return g_strstr_len (p, len, ch);
 }
 
 
 /**
  * g_utf8_strrchr:
- * @p: a nul-terminated utf-8 string
- * @p_len: the maximum length of p
- * @c: a iso-10646 character/
+ * @p: a nul-terminated UTF-8 encoded string
+ * @len: the maximum length of @p
+ * @c: a Unicode character
  * 
- * Find the rightmost occurence of the given iso-10646 character
- * in a UTF-8 string, while limiting the search to p_len bytes.
- * If len is -1, allow unbounded search.
+ * 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.
  * 
- * Return value: NULL if the string does not contain the character, otherwise, a
- *               a pointer to the start of the rightmost of the character in the string.
+ * Return value: %NULL if the string does not contain the character, 
+ *   otherwise, a pointer to the start of the rightmost occurrence of the 
+ *   character in the string.
  **/
 gchar *
 g_utf8_strrchr (const char *p,
-               gssize      p_len,
+               gssize      len,
                gunichar    c)
 {
   gchar ch[10];
 
-  gint len = g_unichar_to_utf8 (c, ch);
-  ch[len] = '\0';
+  gint charlen = g_unichar_to_utf8 (c, ch);
+  ch[charlen] = '\0';
   
-  return g_strrstr_len (p, p_len, ch);
+  return g_strrstr_len (p, len, ch);
 }
 
 
@@ -550,7 +676,8 @@ g_utf8_strrchr (const char *p,
  * and return (gunichar)-2 on incomplete trailing character
  */
 static inline gunichar
-g_utf8_get_char_extended (const gchar *p, gsize max_len)  
+g_utf8_get_char_extended (const  gchar *p,
+                         gssize max_len)  
 {
   guint i, len;
   gunichar wc = (guchar) *p;
@@ -626,10 +753,39 @@ g_utf8_get_char_extended (const gchar *p, gsize max_len)
 }
 
 /**
+ * g_utf8_get_char_validated:
+ * @p: a pointer to Unicode character encoded as UTF-8
+ * @max_len: the maximum number of bytes to read, or -1, for no maximum.
+ * 
+ * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
+ * This function checks for incomplete characters, for invalid characters
+ * such as characters that are out of the range of Unicode, and for
+ * 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.
+ **/
+gunichar
+g_utf8_get_char_validated (const  gchar *p,
+                          gssize max_len)
+{
+  gunichar result = g_utf8_get_char_extended (p, max_len);
+
+  if (result & 0x80000000)
+    return result;
+  else if (!UNICODE_VALID (result))
+    return (gunichar)-1;
+  else
+    return result;
+}
+
+/**
  * g_utf8_to_ucs4_fast:
  * @str: a UTF-8 encoded string
- * @len: the maximum length of @str to use. If < 0, then
- *       the string is %NULL terminated.
+ * @len: the maximum length of @str to use. If @len < 0, then
+ *       the string is nul-terminated.
  * @items_written: location to store the number of characters in the
  *                 result, or %NULL.
  *
@@ -639,7 +795,7 @@ g_utf8_get_char_extended (const gchar *p, gsize max_len)
  * but does no error checking on the input.
  * 
  * Return value: a pointer to a newly allocated UCS-4 string.
- *               This value must be freed with g_free()
+ *               This value must be freed with g_free().
  **/
 gunichar *
 g_utf8_to_ucs4_fast (const gchar *str,
@@ -733,8 +889,8 @@ g_utf8_to_ucs4_fast (const gchar *str,
 /**
  * g_utf8_to_ucs4:
  * @str: a UTF-8 encoded string
- * @len: the maximum length of @str to use. If < 0, then
- *       the string is %NULL terminated.
+ * @len: the maximum length 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
@@ -771,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)
@@ -817,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 < 0, then
- *       the string is %NULL terminated.
- * @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. 
@@ -833,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,
@@ -855,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;
@@ -890,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 < 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
@@ -906,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
@@ -1034,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 < 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
@@ -1176,22 +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 < 0, then
- *       the string is %NULL 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.
@@ -1217,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)
@@ -1294,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 < 0, then
- *       the string is terminated with a zero 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.
@@ -1383,88 +1542,203 @@ 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).
  *
- * Returns TRUE if all of @str was valid. Many GLib and GTK+
- * routines <emphasis>require</emphasis> valid UTF8 as input;
+ * 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;
  * so data read from a file or the network should be checked
  * with g_utf8_validate() before doing anything else with it.
  * 
- * Return value: TRUE if the text was valid UTF-8.
+ * 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
@@ -1480,3 +1754,50 @@ g_unichar_validate (gunichar ch)
 {
   return UNICODE_VALID (ch);
 }
+
+/**
+ * g_utf8_strreverse:
+ * @str: a UTF-8 encoded string
+ * @len: the maximum length of @str to use. If @len < 0, then
+ *       the string is nul-terminated.
+ *
+ * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text. 
+ * (Use g_utf8_validate() on all text before trying to use UTF-8 
+ * utility functions with it.)
+ *
+ * Note that unlike g_strreverse(), this function returns
+ * newly-allocated memory, which should be freed with g_free() when
+ * no longer needed. 
+ *
+ * Returns: a newly-allocated string which is the reverse of @str.
+ *
+ * Since: 2.2
+ */
+gchar *
+g_utf8_strreverse (const gchar *str, 
+                  gssize len)
+{
+  gchar *result;
+  const gchar *p;
+  gchar *m, *r, skip;
+
+  if (len < 0)
+    len = strlen (str);
+
+  result = g_new (gchar, len + 1);
+  r = result + len;
+  p = str;
+  while (*p) 
+    {
+      skip = g_utf8_skip[*(guchar*)p];
+      r -= skip;
+      for (m = r; skip; skip--)
+        *m++ = *p++;
+    }
+  result[len] = 0;
+
+  return result;
+}
+
+#define __G_UTF8_C__
+#include "galiasdef.c"