Skip to content

Commit 8ecd700

Browse files
committed
gio: add content_type_guess_for_filename helper
1 parent c8df619 commit 8ecd700

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

gio/src/content_type.rs

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Take a look at the license at the top of the repository in the LICENSE file.
2+
3+
use std::ptr;
4+
5+
use glib::translate::*;
6+
7+
use crate::ffi;
8+
9+
/// Guesses the content type based on only a filename.
10+
///
11+
/// This function is equivalent to calling `g_content_type_guess()` with the `data` parameter set to NULL.
12+
///
13+
/// See [`crate::content_type_guess`] for more information.
14+
pub fn content_type_guess_for_filename(
15+
filename: impl AsRef<std::path::Path>,
16+
) -> (glib::GString, bool) {
17+
unsafe {
18+
let mut result_uncertain = std::mem::MaybeUninit::uninit();
19+
let ret = from_glib_full(ffi::g_content_type_guess(
20+
filename.as_ref().to_glib_none().0,
21+
ptr::null_mut(),
22+
0,
23+
result_uncertain.as_mut_ptr(),
24+
));
25+
(ret, from_glib(result_uncertain.assume_init()))
26+
}
27+
}

gio/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ mod async_initable;
2121
mod cancellable;
2222
mod cancellable_future;
2323
pub use crate::cancellable_future::{CancellableFuture, Cancelled};
24+
mod content_type;
25+
pub use self::content_type::content_type_guess_for_filename;
2426
mod converter;
2527
mod credentials;
2628
mod data_input_stream;

gio/tests/content_type.rs

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Take a look at the license at the top of the repository in the LICENSE file.
2+
3+
#[cfg(unix)]
4+
#[test]
5+
fn test_content_type_guess_for_filename() {
6+
// We only test for directory and file without extension here as we can't guarantee the
7+
// CI runners will have any mimetypes installed.
8+
let filename = std::path::Path::new("test/");
9+
let ret: (glib::GString, bool) = gio::content_type_guess_for_filename(filename);
10+
assert_eq!(ret.0, "inode/directory");
11+
12+
let filename = std::path::Path::new("test");
13+
let ret: (glib::GString, bool) = gio::content_type_guess_for_filename(filename);
14+
assert_eq!(ret.0, "application/octet-stream");
15+
}

0 commit comments

Comments
 (0)