use crate::io::{FileRead, FileWrite};
use bytes::Bytes;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct VecFileWrite {
buf: Arc<Mutex<Vec<u8>>>,
}
impl VecFileWrite {
pub fn new() -> Self {
Self {
buf: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn into_bytes(self) -> Vec<u8> {
match Arc::try_unwrap(self.buf) {
Ok(mutex) => mutex.into_inner().unwrap(),
Err(arc) => arc.lock().unwrap().clone(),
}
}
pub fn to_vec(&self) -> Vec<u8> {
self.buf.lock().unwrap().clone()
}
}
#[async_trait::async_trait]
impl FileWrite for VecFileWrite {
async fn write(&mut self, bs: Bytes) -> crate::Result<()> {
self.buf.lock().unwrap().extend_from_slice(&bs);
Ok(())
}
async fn close(&mut self) -> crate::Result<()> {
Ok(())
}
}
pub struct BytesFileRead(pub Bytes);
#[async_trait::async_trait]
impl FileRead for BytesFileRead {
async fn read(&self, range: std::ops::Range<u64>) -> crate::Result<Bytes> {
Ok(self.0.slice(range.start as usize..range.end as usize))
}
}