1 use std::{env, path::PathBuf}; 2 3 lazy_static! { 4 static ref CARGO_HANDLER_DATA: CargoHandlerData = CargoHandlerData::new(); 5 } 6 7 struct CargoHandlerData { 8 target_arch: TargetArch, 9 } 10 11 impl CargoHandlerData { new() -> Self12 fn new() -> Self { 13 CargoHandlerData { 14 target_arch: TargetArch::new(), 15 } 16 } 17 } 18 19 #[derive(Debug)] 20 pub struct CargoHandler; 21 22 impl CargoHandler { readenv(key: &str) -> Option<String>23 pub fn readenv(key: &str) -> Option<String> { 24 if let Ok(value) = env::var(key) { 25 Some(value) 26 } else { 27 None 28 } 29 } 30 31 /// 获取当前编译的目标架构 target_arch() -> TargetArch32 pub fn target_arch() -> TargetArch { 33 CARGO_HANDLER_DATA.target_arch 34 } 35 36 /// 设置Cargo对文件更改的监听 37 /// 38 /// ## Parameters 39 /// 40 /// - `files` - The files to set rerun build emit_rerun_if_files_changed(files: &[PathBuf])41 pub fn emit_rerun_if_files_changed(files: &[PathBuf]) { 42 for f in files { 43 println!("cargo:rerun-if-changed={}", f.to_str().unwrap()); 44 } 45 } 46 47 /// 设置链接参数 emit_link_arg(arg: &str)48 pub fn emit_link_arg(arg: &str) { 49 println!("cargo:rustc-link-arg={}", arg); 50 } 51 } 52 53 /// 目标架构 54 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 55 pub enum TargetArch { 56 X86_64, 57 Aarch64, 58 Riscv64, 59 Mips64, 60 Powerpc64, 61 S390x, 62 Sparc64, 63 Unknown, 64 } 65 66 impl TargetArch { new() -> Self67 pub fn new() -> Self { 68 let data = CargoHandler::readenv("CARGO_CFG_TARGET_ARCH") 69 .expect("CARGO_CFG_TARGET_ARCH is not set") 70 .to_ascii_lowercase(); 71 72 match data.as_str() { 73 "x86_64" => TargetArch::X86_64, 74 "aarch64" => TargetArch::Aarch64, 75 "riscv64" => TargetArch::Riscv64, 76 "mips64" => TargetArch::Mips64, 77 "powerpc64" => TargetArch::Powerpc64, 78 "s390x" => TargetArch::S390x, 79 "sparc64" => TargetArch::Sparc64, 80 _ => TargetArch::Unknown, 81 } 82 } 83 } 84