make files bendable
This commit is contained in:
parent
ba15f4fda3
commit
308e3a9d11
1 changed files with 43 additions and 2 deletions
|
@ -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)?
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue