Skip to content

Commit

Permalink
gio: add content_type_guess_for_filename helper
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmhewitt committed Dec 7, 2024
1 parent c8df619 commit 8ecd700
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
27 changes: 27 additions & 0 deletions gio/src/content_type.rs
Original file line number Diff line number Diff line change
@@ -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<std::path::Path>,
) -> (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()))
}
}
2 changes: 2 additions & 0 deletions gio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
15 changes: 15 additions & 0 deletions gio/tests/content_type.rs
Original file line number Diff line number Diff line change
@@ -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");
}

0 comments on commit 8ecd700

Please sign in to comment.