make files bendable

This commit is contained in:
Breval Ferrari 2025-03-22 22:28:41 -04:00
parent ba15f4fda3
commit 308e3a9d11
No known key found for this signature in database
GPG key ID: F71E304D6400AB8E

View file

@ -9,13 +9,13 @@ pub(crate) type Bytes = Vec<u8>;
mod dynamic {
use std::{
fs::File,
io::{self, Read},
io::{self, Read, Write},
path::Path,
};
use crate::{
snd::{self, Audio},
TryFromDataBytes,
Bendable, IntoDataBytes, TryFromDataBytes,
};
use super::{
@ -36,6 +36,7 @@ mod dynamic {
Sound(Audio),
Text,
Archive(PdfDocument),
Meta,
}
#[derive(Debug, Error)]
@ -50,6 +51,46 @@ mod dynamic {
Pdf(String),
}
impl TryFromDataBytes for File {
type Error = io::Error;
type Format = Box<dyn AsRef<Path>>;
fn try_from_data_bytes(
bytes: Bytes,
format: Self::Format,
_crop: crate::Crop,
) -> Result<Self, Self::Error>
where
Self: Sized,
{
let mut file = File::create(format.as_ref())?;
file.write_all(&bytes)?;
Ok(file)
}
}
impl IntoDataBytes for File {
fn into_data_bytes(self) -> Bytes {
self.bytes().flatten().collect() // !! will return an empty vec if it can't read the file!
}
}
impl Bendable for File {
type Unit = u8;
/// /!\ may panic with io errors /!\
fn map<F: Fn(&Self::Unit) -> Self::Unit + Sync>(mut self, f: F) -> Self {
let mut bytes = Vec::new();
self.read_to_end(&mut bytes).expect("couldn't read file");
self.write_all(&bytes.map(f)).expect("couldn't write file");
self
}
fn format() -> Format {
Format::Meta
}
}
pub fn open<P: AsRef<Path>>(path: P) -> Result<Option<DynamicBendable>, OpenError> {
use MatcherType::*;
infer::get_from_path(&path)?