gutf8: Add a g_utf8_validate_len() function

This is a variant of g_utf8_validate() which requires the length to be
specified, thereby allowing string lengths up to G_MAXSIZE rather than
just G_MAXSSIZE.

Signed-off-by: Philip Withnall <withnall@endlessm.com>
This commit is contained in:
Philip Withnall 2018-10-01 19:52:14 +01:00
parent b78fb7407a
commit 5fab65270d
2 changed files with 44 additions and 6 deletions

View File

@ -20,6 +20,7 @@
#define __G_UNICODE_PRIVATE_H__
#include "gtypes.h"
#include "gunicode.h"
G_BEGIN_DECLS
@ -27,6 +28,10 @@ gunichar *_g_utf8_normalize_wc (const gchar *str,
gssize max_len,
GNormalizeMode mode);
gboolean _g_utf8_validate_len (const gchar *str,
gsize max_len,
const gchar **end);
G_END_DECLS
#endif /* __G_UNICODE_PRIVATE_H__ */

View File

@ -39,6 +39,7 @@
#include "gtypes.h"
#include "gthread.h"
#include "glibintl.h"
#include "gunicodeprivate.h"
#define UTF8_COMPUTE(Char, Mask, Len) \
if (Char < 128) \
@ -1669,16 +1670,48 @@ g_utf8_validate (const char *str,
{
const gchar *p;
if (max_len < 0)
p = fast_validate (str);
else
p = fast_validate_len (str, max_len);
if (max_len >= 0)
return _g_utf8_validate_len (str, max_len, end);
p = fast_validate (str);
if (end)
*end = p;
if ((max_len >= 0 && p != str + max_len) ||
(max_len < 0 && *p != '\0'))
if (*p != '\0')
return FALSE;
else
return TRUE;
}
/*
* _g_utf8_validate_len:
* @str: (array length=max_len) (element-type guint8): a pointer to character data
* @max_len: max bytes to validate
* @end: (out) (optional) (transfer none): return location for end of valid data
*
* Validates UTF-8 encoded text.
*
* As with g_utf8_validate(), but @max_len must be set, and hence this function
* will always return %FALSE if any of the bytes of @str are nul.
*
* Returns: %TRUE if the text was valid UTF-8
* Since: 2.60 (backported to 2.56)
*/
gboolean
_g_utf8_validate_len (const char *str,
gsize max_len,
const gchar **end)
{
const gchar *p;
p = fast_validate_len (str, max_len);
if (end)
*end = p;
if (p != str + max_len)
return FALSE;
else
return TRUE;