Skip to content

Commit

Permalink
Make BufReader private
Browse files Browse the repository at this point in the history
  • Loading branch information
fintelia committed Oct 29, 2024
1 parent 0cd3fc7 commit e57ab2f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
19 changes: 14 additions & 5 deletions src/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use std::{
collections::HashMap,
io::{BufReader, Read, Seek},
io::{BufRead, BufReader, Read, Seek},
sync::RwLock,
};

Expand All @@ -12,25 +12,34 @@ use crate::{ImageDecoder, ImageFormat, ImageResult};
pub(crate) trait ReadSeek: Read + Seek {}
impl<T: Read + Seek> ReadSeek for T {}


pub(crate) static DECODING_HOOKS: RwLock<Option<HashMap<ImageFormat, DecodingHook>>> =
RwLock::new(None);

/// A wrapper around a type-erased trait object that implements `Read` and `Seek`.
pub struct BoxReadSeek<'a>(pub(crate) Box<dyn ReadSeek + 'a>);
impl Read for BoxReadSeek<'_> {
pub struct GenericReader<'a>(pub(crate) BufReader<Box<dyn ReadSeek + 'a>>);
impl Read for GenericReader<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.0.read(buf)
}
}
impl Seek for BoxReadSeek<'_> {
impl BufRead for GenericReader<'_> {
fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
self.0.fill_buf()
}
fn consume(&mut self, amt: usize) {
self.0.consume(amt)
}
}
impl Seek for GenericReader<'_> {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
self.0.seek(pos)
}
}

/// A function to produce an `ImageDecoder` for a given image format.
pub type DecodingHook = Box<
dyn for<'a> Fn(BufReader<BoxReadSeek<'a>>) -> ImageResult<Box<dyn ImageDecoder + 'a>>
dyn for<'a> Fn(GenericReader<'a>) -> ImageResult<Box<dyn ImageDecoder + 'a>>
+ Send
+ Sync,
>;
Expand Down
4 changes: 2 additions & 2 deletions src/image_reader/image_reader_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::path::Path;

use crate::dynimage::DynamicImage;
use crate::error::{ImageFormatHint, UnsupportedError, UnsupportedErrorKind};
use crate::hooks::{BoxReadSeek, DECODING_HOOKS};
use crate::hooks::{BoxReadSeek, GenericReader, DECODING_HOOKS};
use crate::image::ImageFormat;
use crate::{ImageDecoder, ImageError, ImageResult};

Expand Down Expand Up @@ -182,7 +182,7 @@ impl<'a, R: 'a + BufRead + Seek> ImageReader<R> {
let hooks = DECODING_HOOKS.read().unwrap();
if let Some(hooks) = hooks.as_ref() {
if let Some(hook) = hooks.get(&format) {
return hook(BufReader::new(BoxReadSeek(Box::new(reader))));
return hook(GenericReader(BufReader::new(Box::new(reader))));
}
}

Expand Down

0 comments on commit e57ab2f

Please sign in to comment.