Skip to content

Commit

Permalink
added hpx::sort along with comparator closure as an argument
Browse files Browse the repository at this point in the history
Signed-off-by: Dikshant <[email protected]>
  • Loading branch information
pingu-73 committed Jul 31, 2024
1 parent 354b234 commit 43ec447
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
13 changes: 13 additions & 0 deletions hpx-sys/include/wrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,16 @@ inline void hpx_sort(rust::Vec<int32_t>& src) {
src.push_back(item);
}
}

inline void hpx_sort_comp(rust::Vec<int32_t>& src, rust::Fn<bool(int32_t, int32_t)> comp) {
std::vector<int32_t> cpp_vec(src.begin(), src.end());

hpx::sort(hpx::execution::par, cpp_vec.begin(), cpp_vec.end(),
[&](int32_t a, int32_t b) { return comp(a, b); });

src.clear();
src.reserve(cpp_vec.size());
for (const auto& item : cpp_vec) {
src.push_back(item);
}
}
34 changes: 34 additions & 0 deletions hpx-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub mod ffi {
fn hpx_fill(src: &mut Vec<i32>, value: i32); // will only work for linear vectors
fn hpx_find(src: &Vec<i32>, value: i32) -> i64;
fn hpx_sort(src: &mut Vec<i32>);
fn hpx_sort_comp(src: &mut Vec<i32>, comp: fn(i32, i32) -> bool);
}
}

Expand Down Expand Up @@ -366,4 +367,37 @@ mod tests {
assert_eq!(result, 0);
}
}

#[test]
#[serial]
fn test_hpx_sort_comp() {
let (argc, mut argv) = create_c_args(&["test_hpx_sort_comp"]);

let hpx_main = |_argc: i32, _argv: *mut *mut c_char| -> i32 {
let mut v = vec![5, 2, 8, 1, 9, 3, 7, 6, 4];
ffi::hpx_sort_comp(&mut v, |a, b| a > b); // sorting in descending order
assert_eq!(v, vec![9, 8, 7, 6, 5, 4, 3, 2, 1]);

// sorting even numbers before odd numbers
let mut v2 = vec![5, 2, 8, 1, 9, 3, 7, 6, 4];
ffi::hpx_sort_comp(
&mut v2,
|a, b| {
if a % 2 == b % 2 {
a < b
} else {
a % 2 == 0
}
},
);
assert_eq!(v2, vec![2, 4, 6, 8, 1, 3, 5, 7, 9]);

ffi::finalize()
};

unsafe {
let result = ffi::init(hpx_main, argc, argv.as_mut_ptr());
assert_eq!(result, 0);
}
}
}

0 comments on commit 43ec447

Please sign in to comment.