hdy-string-utf8.c 1.18 KB
Newer Older
1 2 3
/*
 * Copyright (C) 2017 Purism SPC
 *
4
 * SPDX-License-Identifier: LGPL-2.1+
5 6 7 8
 */

#include <stdlib.h>
#include <gmodule.h>
9
#include "hdy-string-utf8.h"
10 11 12 13 14 15 16 17 18 19

/**
 * SECTION:hdy-string-utf8
 * @short_description: #GString utf-8 helpers
 * @title: HdyStringUtf8
 *
 * Helpers to ease utf-8 handling based on #GString
 */

/**
20
 * hdy_string_utf8_truncate:
21 22 23 24 25 26 27 28
 * @string: a #GString
 * @len: the new size of the string
 *
 * Cut of the end of the string @string so that @len utf8 characters remain
 *
 * Returns: (transfer none): @string
 */
GString *
Sebastien Lafargue's avatar
Sebastien Lafargue committed
29 30
hdy_string_utf8_truncate (GString *string,
                          gsize    len)
31
{
32
  gint cutoff;
33 34 35 36
  gchar *off;

  g_return_val_if_fail (string != NULL, NULL);

37
  cutoff = MIN (len, g_utf8_strlen (string->str, -1));
38 39 40 41 42 43
  off = g_utf8_offset_to_pointer (string->str, cutoff);
  g_string_truncate (string, off - string->str);
  return string;
}

/**
44
 * hdy_string_utf8_len:
45 46 47 48 49 50 51 52 53 54 55 56
 * @string: a #GString
 *
 * Computes the length of the string in utf-8 characters. See #g_utf8_strlen.
 *
 * Returns: the length of @string in characters
 */
glong
hdy_string_utf8_len (GString *string)
{
  g_return_val_if_fail (string != NULL, 0);
  return g_utf8_strlen (string->str, -1);
}