armybox 0.3.0

A memory-safe #[no_std] BusyBox/Toybox clone in Rust - 299 Unix utilities in ~500KB
Documentation
//! swapon - enable devices and files for paging and swapping
//!
//! Enable swap on a device or file.

use crate::sys;
use crate::applets::get_arg;

/// swapon - enable devices and files for paging and swapping
///
/// # Synopsis
/// ```text
/// swapon device
/// ```
///
/// # Description
/// Enable swapping on the specified device or file. Requires root.
///
/// # Exit Status
/// - 0: Success
/// - >0: An error occurred
pub fn swapon(argc: i32, argv: *const *const u8) -> i32 {
    if argc < 2 { return 1; }
    let path = unsafe { get_arg(argv, 1).unwrap() };
    let mut path_buf = [0u8; 4096];
    path_buf[..path.len()].copy_from_slice(path);

    if unsafe { libc::swapon(path_buf.as_ptr() as *const i8, 0) } != 0 {
        sys::perror(b"swapon");
        return 1;
    }
    0
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::process::Command;
    use std::path::PathBuf;

    fn get_armybox_path() -> PathBuf {
        if let Ok(path) = std::env::var("ARMYBOX_PATH") {
            return PathBuf::from(path);
        }
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| std::env::current_dir().unwrap());
        let release = manifest_dir.join("target/release/armybox");
        if release.exists() { return release; }
        manifest_dir.join("target/debug/armybox")
    }

    #[test]
    fn test_swapon_no_args() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["swapon"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(1));
    }

    #[test]
    fn test_swapon_invalid() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["swapon", "/nonexistent"])
            .output()
            .unwrap();

        // Should fail - not a swap device or permission denied
        assert_eq!(output.status.code(), Some(1));
    }
}