use pyruts::c_wrap;
use std::os::raw::c_char;
mod native {
use std::os::raw::c_char;
#[no_mangle]
pub extern "C" fn my_count_args(argv: *const *const c_char) -> i32 {
if argv.is_null() {
return -1;
}
let mut count = 0;
unsafe {
let mut p = argv;
while !(*p).is_null() {
count += 1;
p = p.add(1);
}
}
count
}
#[no_mangle]
pub extern "C" fn my_first_arg(argv: *const *const c_char) -> *const c_char {
unsafe {
if argv.is_null() || (*argv).is_null() {
return std::ptr::null();
}
*argv
}
}
#[no_mangle]
pub extern "C" fn my_total_bytes(argv: *const *const c_char) -> usize {
if argv.is_null() {
return 0;
}
let mut total = 0;
unsafe {
let mut p = argv;
while !(*p).is_null() {
let mut q = *p;
while *q != 0 {
total += 1;
q = q.add(1);
}
p = p.add(1);
}
}
total
}
}
c_wrap! {
extern "C" {
fn my_count_args(argv: *const *const c_char) -> i32;
fn my_first_arg(argv: *const *const c_char) -> *const c_char;
fn my_total_bytes(argv: *const *const c_char) -> usize;
}
}
#[test]
fn c_wrap_str_array_count_three() {
assert_eq!(safe_my_count_args(&["a", "b", "c"]), 3);
}
#[test]
fn c_wrap_str_array_empty() {
assert_eq!(safe_my_count_args(&[]), 0);
}
#[test]
fn c_wrap_str_array_single() {
assert_eq!(safe_my_count_args(&["only"]), 1);
}
#[test]
fn c_wrap_str_array_first_arg() {
assert_eq!(safe_my_first_arg(&["hello", "world"]), "hello");
}
#[test]
fn c_wrap_str_array_total_bytes() {
let total = safe_my_total_bytes(&["foo", "bar", "baz"]);
assert_eq!(total, 9);
}
#[test]
fn c_wrap_str_array_total_bytes_empty() {
assert_eq!(safe_my_total_bytes(&[]), 0);
}
#[test]
fn c_wrap_str_array_accepts_vec_slice() {
let v: Vec<&str> = vec!["x", "y", "z"];
assert_eq!(safe_my_count_args(v.as_slice()), 3);
}
#[test]
fn c_wrap_str_array_accepts_array_ref() {
let arr: [&str; 4] = ["1", "2", "3", "4"];
assert_eq!(safe_my_count_args(&arr), 4);
}
#[test]
fn c_wrap_str_array_longer_strings() {
assert_eq!(
safe_my_total_bytes(&["hello", "world", "rust", "proc_macro"]),
"hello".len() + "world".len() + "rust".len() + "proc_macro".len()
);
}