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 f039d43
Show file tree
Hide file tree
Showing 3 changed files with 43 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
14 changes: 14 additions & 0 deletions gio/tests/content_type.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Take a look at the license at the top of the repository in the LICENSE file.

#[test]
fn test_content_type_guess_for_filename() {
let filename = std::path::Path::new("test.pdf");
let ret: (glib::GString, bool) = gio::content_type_guess_for_filename(filename);
assert_eq!(ret.0, "application/pdf");
assert_eq!(ret.1, false);

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");
assert_eq!(ret.1, true);
}

0 comments on commit f039d43

Please sign in to comment.