utils: add gtk_file_load_bytes() helper

This helper will load GBytes for a GFile, but try to reuse the
embedded data for a gresource to reduce the chances of copying
data to the heap.

https://bugzilla.gnome.org/show_bug.cgi?id=790270
This commit is contained in:
Christian Hergert 2017-11-12 19:26:54 -08:00
parent 15acb4c340
commit d46c072c4d
2 changed files with 39 additions and 1 deletions

View File

@ -32,6 +32,8 @@
#include <glib/gstdio.h>
#include <gmodule.h>
#include "gtkutilsprivate.h"
/* Copied from pango-utils.c */
/* We need to call getc() a lot in a loop. This is suboptimal,
@ -264,3 +266,36 @@ gtk_split_file_list (const char *str)
return files;
}
GBytes *
gtk_file_load_bytes (GFile *file,
GCancellable *cancellable,
GError **error)
{
gchar *contents;
gsize len;
g_return_val_if_fail (G_IS_FILE (file), NULL);
g_return_val_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable), NULL);
if (g_file_has_uri_scheme (file, "resource"))
{
gchar *uri, *unescaped;
GBytes *bytes;
uri = g_file_get_uri (file);
unescaped = g_uri_unescape_string (uri + strlen ("resource://"), NULL);
g_free (uri);
bytes = g_resources_lookup_data (unescaped, 0, error);
g_free (unescaped);
return bytes;
}
/* contents is always \0 terminated, but we don't include that in the bytes */
if (g_file_load_contents (file, cancellable, &contents, &len, NULL, error))
return g_bytes_new_take (contents, len);
return NULL;
}

View File

@ -1,7 +1,7 @@
#ifndef __GTKUTILS_H__
#define __GTKUTILS_H__
#include <glib.h>
#include <gio/gio.h>
G_BEGIN_DECLS
@ -12,6 +12,9 @@ gint gtk_read_line (FILE *stream,
GString *str);
char * gtk_trim_string (const char *str);
char ** gtk_split_file_list (const char *str);
GBytes *gtk_file_load_bytes (GFile *file,
GCancellable *cancellable,
GError **error);
G_END_DECLS