use core::ffi::c_char;

use crate::util::PointerStrExt;

const DOT: *mut c_char = c".".as_ptr().cast_mut();

#[no_mangle]
unsafe extern "C" fn basename(path: *mut c_char) -> *mut c_char {
    if path.is_null() {
        return DOT;
    }
    let path_str = path.cast_const().ensure_str();
    if path_str.is_empty() {
        DOT
    } else if path_str == "/" {
        path
    } else {
        let path_str = path_str.trim_end_matches('/');
        if let Some(last_slash) = path_str.rfind('/') {
            path.add(last_slash + 1)
        } else {
            path
        }
    }
}

#[no_mangle]
unsafe extern "C" fn dirname(path: *mut c_char) -> *mut c_char {
    if path.is_null() {
        return DOT;
    }
    let path_str = path.cast_const().ensure_str();
    if path_str.is_empty() {
        DOT
    } else if path_str == "/" {
        path
    } else {
        let path_str = path_str.trim_end_matches('/');
        if let Some(last_slash) = path_str.rfind('/') {
            // Turn last slash into '\0' to terminate dirname
            path.add(last_slash).write(0);
            path
        } else {
            DOT
        }
    }
}
