use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
use std::time::{SystemTime, UNIX_EPOCH};
pub struct TempPath(PathBuf);
impl TempPath {
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub fn new(suffix: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let pid = std::process::id();
let at = std::env::temp_dir().join(format!("amethystate-{suffix}-{pid}-{nanos}-{seq}"));
let _ = std::fs::create_dir_all(&at);
Self(at.join(format!("{suffix}.db")))
}
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
pub fn new(suffix: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let run = uuid::Uuid::new_v4().simple();
Self(PathBuf::from(format!("amethystate-{suffix}-{run}-{seq}")))
}
pub fn path(&self) -> &Path {
&self.0
}
}
impl std::ops::Deref for TempPath {
type Target = Path;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsRef<Path> for TempPath {
fn as_ref(&self) -> &Path {
&self.0
}
}
impl From<&TempPath> for PathBuf {
fn from(at: &TempPath) -> Self {
at.0.clone()
}
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
impl Drop for TempPath {
fn drop(&mut self) {
if let Some(dir) = self.0.parent() {
let _ = std::fs::remove_dir_all(dir);
}
}
}