Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Music::from_bytes() function #704

Merged
merged 3 commits into from
Sep 10, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions src/sdl2/mixer/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//!
//! A binding for the library `SDL2_mixer`
//!
//!
//!
//! Note that you need to build with the
//! feature `mixer` for this module to be enabled,
//! like so:
Expand All @@ -27,7 +27,7 @@ use std::ffi::{CString, CStr};
use std::str::from_utf8;
use std::borrow::ToOwned;
use std::path::Path;
use libc::{c_int, uint16_t, c_double, c_uint};
use libc::{c_int, uint16_t, c_double, c_uint, c_void};
use ::get_error;
use ::rwops::RWops;
use ::version::Version;
Expand Down Expand Up @@ -790,6 +790,28 @@ impl<'a> Music<'a> {
}
}

/// Load music from a byte buffer.
pub fn from_bytes(buf: &[u8]) -> Result<Music<'static>, String> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is pretty unsafe, if the &[u8] comes from a Vec that gets destroyed right afterwards, this will probably crash, unless I'm missing something.

Please replace that by &'static [u8], and change the fn name to from_static_bytes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right; I tried that and it crashed immediately.

let rw = unsafe {
::sys::rwops::SDL_RWFromConstMem(buf.as_ptr() as *const c_void, buf.len() as c_int)
};

if rw.is_null() {
return Err(get_error());
}

let raw = unsafe { ffi::Mix_LoadMUS_RW(rw, 1) };
if raw.is_null() {
Err(get_error())
} else {
Ok(Music {
raw: raw,
owned: true,
_marker: PhantomData,
})
}
}

/// The file format encoding of the music.
pub fn get_type(&self) -> MusicType {
let ret = unsafe { ffi::Mix_GetMusicType(self.raw) as i32 } as c_uint;
Expand Down