Skip to content

Commit

Permalink
fix(playback): avoid unnecessary boxing (#60)
Browse files Browse the repository at this point in the history
Add a helper trait to upcast trait object.
see also: https://www.zhihu.com/question/643804984/answer/3393253605
  • Loading branch information
snylonue authored Oct 14, 2024
1 parent f75baee commit d05e374
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion anni-playback/src/decoder/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ impl Decoder {
buffer_signal: Arc<AtomicBool>,
) -> anyhow::Result<Playback> {
let duration_hint = source.duration_hint();
let mss = MediaSourceStream::new(Box::new(source), Default::default());
let mss = MediaSourceStream::new(source.into(), Default::default());
let format_options = FormatOptions {
enable_gapless: true,
..Default::default()
Expand Down
19 changes: 18 additions & 1 deletion anni-playback/src/sources/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ struct Receiver {
receiver: std::sync::mpsc::Receiver<(usize, Vec<u8>)>,
}

pub trait AnniSource: MediaSource {
pub trait AnniSource: MediaSource + IntoBoxedMediaSource {
/// The duration of underlying source in seconds.
fn duration_hint(&self) -> Option<u64> {
None
Expand All @@ -46,6 +46,23 @@ impl MediaSource for Box<dyn AnniSource> {

impl AnniSource for std::fs::File {}

// helper trait to do upcasting
pub trait IntoBoxedMediaSource {
fn into_media_source(self: Box<Self>) -> Box<dyn MediaSource>;
}

impl<T: MediaSource + 'static> IntoBoxedMediaSource for T {
fn into_media_source(self: Box<Self>) -> Box<dyn MediaSource> {
self
}
}

impl From<Box<dyn AnniSource>> for Box<dyn MediaSource> {
fn from(value: Box<dyn AnniSource>) -> Self {
value.into_media_source()
}
}

// Specialization is not well-supported so far (even the unstable feature is unstable ww).
// Therefore, we do not provide the default implementation below.
// Users can use a newtype pattern if needed.
Expand Down

0 comments on commit d05e374

Please sign in to comment.