Skip to content

Commit 2fb96e4

Browse files
feat:
+ Added `free_c_str` for check is valid path + Addded test case for this function
1 parent 3bf446f commit 2fb96e4

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

ffi_rs/src/utils/path.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use std::{ffi::{CStr}, os::raw::c_char, path::Path};
2+
3+
#[unsafe(no_mangle)]
4+
pub unsafe extern "C" fn is_valid_path(path: *mut c_char) -> bool { unsafe {
5+
if path.is_null() {
6+
return false;
7+
}
8+
9+
let c_str = match CStr::from_ptr(path).to_str() {
10+
Ok(string) => string,
11+
Err(_) => return false,
12+
};
13+
14+
if c_str.is_empty() {
15+
return false;
16+
}
17+
18+
let path = Path::new(c_str);
19+
20+
path
21+
.as_os_str()
22+
.as_encoded_bytes()
23+
.iter()
24+
.all(|&char| char != 0)
25+
}}
26+
27+
#[test]
28+
fn test_is_valid_path() {
29+
use std::ffi::{CString};
30+
use std::ptr::null_mut;
31+
use crate::alloc::memory::free_c_str;
32+
33+
unsafe {
34+
let c_string = CString
35+
::new("../../src/utils/path.rs") /* Path to some exits file ...*/
36+
.map(|raw| raw.into_raw())
37+
.unwrap_or(null_mut());
38+
39+
assert_eq!(true, is_valid_path(c_string));
40+
free_c_str(c_string);
41+
}
42+
}

0 commit comments

Comments
 (0)