From 7a18f52ff655ddfeee6b099746e6304224a1049a Mon Sep 17 00:00:00 2001 From: David Hewitt Date: Sat, 7 Dec 2024 16:11:54 +0900 Subject: [PATCH] gio: add content_type_guess_for_filename helper --- gio/src/content_type.rs | 28 ++++++++++++++++++++++++++++ gio/src/lib.rs | 2 ++ gio/tests/content_type.rs | 15 +++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 gio/src/content_type.rs create mode 100644 gio/tests/content_type.rs diff --git a/gio/src/content_type.rs b/gio/src/content_type.rs new file mode 100644 index 000000000000..b90f6fde6d95 --- /dev/null +++ b/gio/src/content_type.rs @@ -0,0 +1,28 @@ +// 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; + +// rustdoc-stripper-ignore-next +/// 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"); +}