use crate::{Content, ContentPath, ContentType};
pub struct BufferContent<T: ContentType> {
buffer: Vec<u8>,
path: ContentPath,
content_type: Option<T>,
}
impl<T: ContentType> BufferContent<T> {
pub fn new(buffer: &[u8], path: &str) -> Self {
Self {
buffer: buffer.to_vec(),
path: ContentPath::from_str(path),
content_type: None,
}
}
pub fn from_vec(buffer: Vec<u8>, path: &str) -> Self {
Self {
buffer,
path: ContentPath::from_str(path),
content_type: None,
}
}
pub fn with_content_type(buffer: &[u8], path: &str, content_type: T) -> Self {
Self {
buffer: buffer.to_vec(),
path: ContentPath::from_str(path),
content_type: Some(content_type),
}
}
pub fn from_parts(buffer: Vec<u8>, path: String, content_type: Option<T>) -> Self {
Self {
buffer,
path: ContentPath::with_string(path),
content_type,
}
}
}
impl<T: ContentType> Content<T> for BufferContent<T> {
#[inline(always)]
fn content_type(&self) -> Option<T> {
self.content_type
}
#[inline(always)]
fn path(&self) -> &ContentPath {
&self.path
}
#[inline(always)]
fn size(&self) -> u64 {
self.buffer.len() as u64
}
fn read(&mut self, offset: u64, count: u32) -> Option<&[u8]> {
if offset > self.buffer.len() as u64 {
return None;
}
if offset == self.buffer.len() as u64 {
return Some(&[]);
}
let len = (self.buffer.len() as u64 - offset).min(count as u64) as usize;
Some(&self.buffer.as_slice()[offset as usize..offset as usize + len])
}
#[inline(always)]
fn set_content_type(&mut self, ty: T) {
self.content_type = Some(ty);
}
}