Skip to content

Commit d05e374

Browse files
authored
fix(playback): avoid unnecessary boxing (#60)
Add a helper trait to upcast trait object. see also: https://www.zhihu.com/question/643804984/answer/3393253605
1 parent f75baee commit d05e374

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

anni-playback/src/decoder/decoder.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ impl Decoder {
362362
buffer_signal: Arc<AtomicBool>,
363363
) -> anyhow::Result<Playback> {
364364
let duration_hint = source.duration_hint();
365-
let mss = MediaSourceStream::new(Box::new(source), Default::default());
365+
let mss = MediaSourceStream::new(source.into(), Default::default());
366366
let format_options = FormatOptions {
367367
enable_gapless: true,
368368
..Default::default()

anni-playback/src/sources/mod.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ struct Receiver {
2727
receiver: std::sync::mpsc::Receiver<(usize, Vec<u8>)>,
2828
}
2929

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

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

49+
// helper trait to do upcasting
50+
pub trait IntoBoxedMediaSource {
51+
fn into_media_source(self: Box<Self>) -> Box<dyn MediaSource>;
52+
}
53+
54+
impl<T: MediaSource + 'static> IntoBoxedMediaSource for T {
55+
fn into_media_source(self: Box<Self>) -> Box<dyn MediaSource> {
56+
self
57+
}
58+
}
59+
60+
impl From<Box<dyn AnniSource>> for Box<dyn MediaSource> {
61+
fn from(value: Box<dyn AnniSource>) -> Self {
62+
value.into_media_source()
63+
}
64+
}
65+
4966
// Specialization is not well-supported so far (even the unstable feature is unstable ww).
5067
// Therefore, we do not provide the default implementation below.
5168
// Users can use a newtype pattern if needed.

0 commit comments

Comments
 (0)