use std::{fs, io};
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use cbsk_base::log;
pub trait WriteToFile: Debug {
fn write_to_file(&self, bytes: impl AsRef<[u8]>) {
if let Err(e) = self.try_write_to_file(bytes) {
log::error!("write bytes to file[{self:?}] fail: {e:?}");
}
}
fn try_write_to_file(&self, bytes: impl AsRef<[u8]>) -> io::Result<()>;
}
impl WriteToFile for Path {
fn try_write_to_file(&self, bytes: impl AsRef<[u8]>) -> io::Result<()> {
super::try_create_file(self)?;
fs::write(self, bytes)
}
}
impl WriteToFile for PathBuf {
fn try_write_to_file(&self, bytes: impl AsRef<[u8]>) -> io::Result<()> {
self.as_path().try_write_to_file(bytes)
}
}
impl WriteToFile for String {
fn try_write_to_file(&self, bytes: impl AsRef<[u8]>) -> io::Result<()> {
Path::new(self).try_write_to_file(bytes)
}
}
impl WriteToFile for &str {
fn try_write_to_file(&self, bytes: impl AsRef<[u8]>) -> io::Result<()> {
Path::new(self).try_write_to_file(bytes)
}
}