//! Lookup functions for preprocessor symbols.
//!
//! Functions in this module may be called to get the value of various
//! preprocessor symbols that are available on the C side of things.
//!
//! ## Rust rewrite notes
//!
//! Until we move away from autootols entirely, we might be stuck with this as
//! along as it makes sense to keep the configure script as the main entrypoint
//! for compile-time configuration.

use std::ffi::{c_char, CStr};

// Functions defined in src/defines.c.
unsafe extern "C" {
    fn get_GSUSER_SUBDIR() -> *const c_char;
}

/// Returns the value of the GSUSER_SUBDIR preprocessor symbol defined at
/// Autotools configuration time prior to compilation. This is the final
/// component of the root path where user data files are stored (usually
/// `GNUstep`, as in `$HOME/GNUstep`). Returns `None` if this value cannot be
/// determined or is empty.
pub fn gsuser_subdir() -> Option<String> {
    let s = unsafe { get_GSUSER_SUBDIR() };
    if s.is_null() {
        return None;
    }
    let s = unsafe { CStr::from_ptr(s) };
    if s.is_empty() {
        return None;
    }
    String::from_utf8(s.to_bytes().iter().copied().collect()).ok()
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn gsuser_subdir_is_set() {
        let s = gsuser_subdir().unwrap();
        assert!(!s.is_empty());
    }
}
