[gtk+/gtk-3-22] utils: add gtk_file_load_bytes() helper



commit d46c072c4d5469226fef756e77e097b2adbc71bc
Author: Christian Hergert <chergert redhat com>
Date:   Sun Nov 12 19:26:54 2017 -0800

    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

 gtk/gtkutils.c        |   35 +++++++++++++++++++++++++++++++++++
 gtk/gtkutilsprivate.h |    5 ++++-
 2 files changed, 39 insertions(+), 1 deletions(-)
---
diff --git a/gtk/gtkutils.c b/gtk/gtkutils.c
index 69c4ccb..6a1d515 100644
--- a/gtk/gtkutils.c
+++ b/gtk/gtkutils.c
@@ -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;
+}
diff --git a/gtk/gtkutilsprivate.h b/gtk/gtkutilsprivate.h
index a498c74..95845d4 100644
--- a/gtk/gtkutilsprivate.h
+++ b/gtk/gtkutilsprivate.h
@@ -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
 


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]