diff --git a/gio/src/content_type.rs b/gio/src/content_type.rs new file mode 100644 index 000000000000..fb8a7f58571f --- /dev/null +++ b/gio/src/content_type.rs @@ -0,0 +1,27 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use std::ptr; + +use glib::translate::*; + +use crate::ffi; + +/// Guesses the content type based on only a filename. +/// +/// This function is equivalent to calling `g_content_type_guess()` with the `data` parameter set to NULL. +/// +/// See [`crate::content_type_guess`] for more information. +pub fn content_type_guess_for_filename( + filename: impl AsRef, +) -> (glib::GString, bool) { + unsafe { + let mut result_uncertain = std::mem::MaybeUninit::uninit(); + let ret = from_glib_full(ffi::g_content_type_guess( + filename.as_ref().to_glib_none().0, + ptr::null_mut(), + 0, + result_uncertain.as_mut_ptr(), + )); + (ret, from_glib(result_uncertain.assume_init())) + } +} diff --git a/gio/src/lib.rs b/gio/src/lib.rs index da084ca7d6a3..59da4c4e9554 100644 --- a/gio/src/lib.rs +++ b/gio/src/lib.rs @@ -21,6 +21,8 @@ mod async_initable; mod cancellable; mod cancellable_future; pub use crate::cancellable_future::{CancellableFuture, Cancelled}; +mod content_type; +pub use self::content_type::content_type_guess_for_filename; mod converter; mod credentials; mod data_input_stream; diff --git a/gio/tests/content_type.rs b/gio/tests/content_type.rs new file mode 100644 index 000000000000..9e06f26a4f01 --- /dev/null +++ b/gio/tests/content_type.rs @@ -0,0 +1,15 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +#[cfg(unix)] +#[test] +fn test_content_type_guess_for_filename() { + // We only test for directory and file without extension here as we can't guarantee the + // CI runners will have any mimetypes installed. + let filename = std::path::Path::new("test/"); + let ret: (glib::GString, bool) = gio::content_type_guess_for_filename(filename); + assert_eq!(ret.0, "inode/directory"); + + let filename = std::path::Path::new("test"); + let ret: (glib::GString, bool) = gio::content_type_guess_for_filename(filename); + assert_eq!(ret.0, "application/octet-stream"); +}