| 1 | use std::io::Read as _; |
| 2 | use std::path::PathBuf; |
| 3 | |
| 4 | #[cfg(embedded_onnxruntime)] |
| 5 | const COMPRESSED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/onnxruntime.dll.deflate")); |
| 6 | #[cfg(not(embedded_onnxruntime))] |
| 7 | const COMPRESSED: &[u8] = &[]; |
| 8 | |
| 9 | pub fn onnxruntime_path() -> Option<PathBuf> { |
| 10 | if COMPRESSED.is_empty() { |
| 11 | return None; |
| 12 | } |
| 13 | let name = format!("onnxruntime-{:08x}.dll", fingerprint(COMPRESSED)); |
| 14 | let path = std::env::current_exe().ok()?.with_file_name(&name); |
| 15 | if path.exists() { |
| 16 | return Some(path); |
| 17 | } |
| 18 | remove_older(&path, &name); |
| 19 | let mut library = Vec::new(); |
| 20 | flate2::read::DeflateDecoder::new(COMPRESSED) |
| 21 | .read_to_end(&mut library) |
| 22 | .ok()?; |
| 23 | let partial = path.with_extension("partial"); |
| 24 | std::fs::write(&partial, &library).ok()?; |
| 25 | std::fs::rename(&partial, &path).ok()?; |
| 26 | Some(path) |
| 27 | } |
| 28 | |
| 29 | fn remove_older(path: &std::path::Path, current: &str) { |
| 30 | let Some(directory) = path.parent() else { |
| 31 | return; |
| 32 | }; |
| 33 | for entry in std::fs::read_dir(directory).into_iter().flatten().flatten() { |
| 34 | let name = entry.file_name().to_string_lossy().into_owned(); |
| 35 | if name.starts_with("onnxruntime-") && name.ends_with(".dll") && name != current { |
| 36 | let _ = std::fs::remove_file(entry.path()); |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | fn fingerprint(bytes: &[u8]) -> u32 { |
| 42 | bytes.iter().fold(0x811c_9dc5u32, |hash, &byte| { |
| 43 | (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193) |
| 44 | }) |
| 45 | } |