[go: up one dir, main page]

gio/
resource.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{mem, ptr};
4
5use glib::translate::*;
6
7use crate::{resources_register, Resource};
8
9impl Resource {
10    #[doc(alias = "g_resource_new_from_data")]
11    pub fn from_data(data: &glib::Bytes) -> Result<Resource, glib::Error> {
12        unsafe {
13            let mut error = ptr::null_mut();
14
15            // Create a copy of data if it is not pointer-aligned
16            // https://bugzilla.gnome.org/show_bug.cgi?id=790030
17            let mut data = data.clone();
18            let data_ptr = glib::ffi::g_bytes_get_data(data.to_glib_none().0, ptr::null_mut());
19            if data_ptr as usize % mem::align_of::<*const u8>() != 0 {
20                data = glib::Bytes::from(&*data);
21            }
22
23            let ret = crate::ffi::g_resource_new_from_data(data.to_glib_none().0, &mut error);
24            if error.is_null() {
25                Ok(from_glib_full(ret))
26            } else {
27                Err(from_glib_full(error))
28            }
29        }
30    }
31}
32
33#[doc(hidden)]
34pub fn resources_register_include_impl(bytes: &'static [u8]) -> Result<(), glib::Error> {
35    let bytes = glib::Bytes::from_static(bytes);
36    let resource = Resource::from_data(&bytes)?;
37    resources_register(&resource);
38    Ok(())
39}
40
41// rustdoc-stripper-ignore-next
42/// Include gresources generated with `glib_build_tools::compile_resources` and register with glib. `path` is
43/// relative to `OUTDIR`.
44///
45/// ```ignore
46/// gio::resources_register_include!("compiled.gresource").unwrap();
47/// ```
48#[macro_export]
49macro_rules! resources_register_include {
50    ($path:expr) => {
51        $crate::resources_register_include_impl(include_bytes!(concat!(
52            env!("OUT_DIR"),
53            "/",
54            $path
55        )))
56    };
57}