Update APIs to use Into<Option> instead of Option

This commit is contained in:
Jacob Kiesel
2017-04-12 04:03:46 +02:00
committed by Cobrand
parent 9a56099a82
commit a0bd52fe7e
10 changed files with 209 additions and 132 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ fn main() {
// default sample size
};
let device = audio_subsystem.open_queue::<i16>(None, &desired_spec).unwrap();
let device = audio_subsystem.open_queue::<i16, _>(None, &desired_spec).unwrap();
let target_bytes = 48000 * 4;
let wave = gen_wave(target_bytes);
+35 -12
View File
@@ -68,15 +68,16 @@ use sys::audio as ll;
impl AudioSubsystem {
/// Opens a new audio device given the desired parameters and callback.
#[inline]
pub fn open_playback<CB, F>(&self, device: Option<&str>, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String>
where CB: AudioCallback, F: FnOnce(AudioSpec) -> CB
pub fn open_playback<'a, CB, F, D>(&self, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String>
where CB: AudioCallback, F: FnOnce(AudioSpec) -> CB, D: Into<Option<&'a str>>,
{
AudioDevice::open_playback(self, device, spec, get_callback)
}
/// Opens a new audio device which uses queueing rather than older callback method.
#[inline]
pub fn open_queue<Channel>(&self, device: Option<&str>, spec: &AudioSpecDesired) -> Result<AudioQueue<Channel>, String> where Channel: AudioFormatNum
pub fn open_queue<'a, Channel, D>(&self, device: D, spec: &AudioSpecDesired) -> Result<AudioQueue<Channel>, String>
where Channel: AudioFormatNum, D: Into<Option<&'a str>>,
{
AudioQueue::open_queue(self, device, spec)
}
@@ -381,9 +382,19 @@ pub struct AudioSpecDesired {
}
impl AudioSpecDesired {
fn convert_to_ll<CB: AudioCallback>(freq: Option<i32>, channels: Option<u8>, samples: Option<u16>, userdata: *mut CB) -> ll::SDL_AudioSpec {
fn convert_to_ll<CB, F, C, S>(freq: F, channels: C, samples: S, userdata: *mut CB) -> ll::SDL_AudioSpec
where
CB: AudioCallback,
F: Into<Option<i32>>,
C: Into<Option<u8>>,
S: Into<Option<u16>>,
{
use std::mem::transmute;
let freq = freq.into();
let channels = channels.into();
let samples = samples.into();
if let Some(freq) = freq { assert!(freq > 0); }
if let Some(channels) = channels { assert!(channels > 0); }
if let Some(samples) = samples { assert!(samples > 0); }
@@ -409,7 +420,17 @@ impl AudioSpecDesired {
}
}
fn convert_queue_to_ll<Channel: AudioFormatNum>(freq: Option<i32>, channels: Option<u8>, samples: Option<u16>) -> ll::SDL_AudioSpec {
fn convert_queue_to_ll<Channel, F, C, S>(freq: F, channels: C, samples: S) -> ll::SDL_AudioSpec
where
Channel: AudioFormatNum,
F: Into<Option<i32>>,
C: Into<Option<u8>>,
S: Into<Option<u16>>
{
let freq = freq.into();
let channels = channels.into();
let samples = samples.into();
if let Some(freq) = freq { assert!(freq > 0); }
if let Some(channels) = channels { assert!(channels > 0); }
if let Some(samples) = samples { assert!(samples > 0); }
@@ -481,14 +502,14 @@ pub struct AudioQueue<Channel: AudioFormatNum> {
spec: AudioSpec,
}
impl<Channel: AudioFormatNum> AudioQueue<Channel> {
impl<'a, Channel: AudioFormatNum> AudioQueue<Channel> {
/// Opens a new audio device given the desired parameters and callback.
pub fn open_queue(a: &AudioSubsystem, device: Option<&str>, spec: &AudioSpecDesired) -> Result<AudioQueue<Channel>, String> {
let desired = AudioSpecDesired::convert_queue_to_ll::<Channel>(spec.freq, spec.channels, spec.samples);
pub fn open_queue<D: Into<Option<&'a str>>>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired) -> Result<AudioQueue<Channel>, String> {
let desired = AudioSpecDesired::convert_queue_to_ll::<Channel, Option<i32>, Option<u8>, Option<u16>>(spec.freq, spec.channels, spec.samples);
let mut obtained = unsafe { mem::uninitialized::<ll::SDL_AudioSpec>() };
unsafe {
let device = match device {
let device = match device.into() {
Some(device) => Some(CString::new(device).unwrap()),
None => None
};
@@ -568,8 +589,10 @@ pub struct AudioDevice<CB: AudioCallback> {
impl<CB: AudioCallback> AudioDevice<CB> {
/// Opens a new audio device given the desired parameters and callback.
pub fn open_playback<F>(a: &AudioSubsystem, device: Option<&str>, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String>
where F: FnOnce(AudioSpec) -> CB
pub fn open_playback<'a, F, D>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result<AudioDevice <CB>, String>
where
F: FnOnce(AudioSpec) -> CB,
D: Into<Option<&'a str>>,
{
// SDL_OpenAudioDevice needs a userdata pointer, but we can't initialize the
@@ -583,7 +606,7 @@ impl<CB: AudioCallback> AudioDevice<CB> {
let mut obtained = unsafe { mem::uninitialized::<ll::SDL_AudioSpec>() };
unsafe {
let device = match device {
let device = match device.into() {
Some(device) => Some(CString::new(device).unwrap()),
None => None
};
+8 -5
View File
@@ -740,13 +740,16 @@ impl ::std::fmt::Debug for Event {
/// Helper function to make converting scancodes
/// and keycodes to primitive SDL_Keysym types.
fn mk_keysym(scancode: Option<Scancode>,
keycode: Option<Keycode>,
keymod: Mod) -> syskeyboard::SDL_Keysym {
let scancode = scancode
fn mk_keysym<S, K>(scancode: S,
keycode: K,
keymod: Mod) -> syskeyboard::SDL_Keysym
where S: Into<Option<Scancode>>,
K: Into<Option<Keycode>>,
{
let scancode = scancode.into()
.map(|sc| sc as scancode::SDL_Scancode)
.unwrap_or(scancode::SDL_SCANCODE_UNKNOWN);
let keycode = keycode
let keycode = keycode.into()
.map(|kc| kc as keycode::SDL_Keycode)
.unwrap_or(keycode::SDLK_UNKNOWN);
let keymod = keymod.bits() as u16;
+4 -2
View File
@@ -491,8 +491,10 @@ impl<'a> DrawRenderer for Renderer<'a> {
}
/// Sets or resets the current global font data.
pub fn set_font(fontdata: Option<&[u8]>, cw: u32, ch: u32) {
let actual_fontdata = match fontdata {
pub fn set_font<'b, F>(fontdata: F, cw: u32, ch: u32)
where F: Into<Option<&'b [u8]>>
{
let actual_fontdata = match fontdata.into() {
None => ptr::null(),
Some(v) => v.as_ptr()
};
+15 -7
View File
@@ -141,9 +141,11 @@ impl error::Error for ShowMessageError {
/// There is no way to know if the user clicked "Ok" or closed the message box,
/// If you want to retrieve which button was clicked and customize a bit more
/// your message box, use `show_message_box` instead.
pub fn show_simple_message_box(flags: MessageBoxFlag, title: &str,
message: &str, window: Option<&WindowRef>)
-> Result<(), ShowMessageError> {
pub fn show_simple_message_box<'a, W>(flags: MessageBoxFlag, title: &str,
message: &str, window: W)
-> Result<(), ShowMessageError>
where W: Into<Option<&'a WindowRef>>
{
use self::ShowMessageError::*;
let result = unsafe {
let title = match CString::new(title) {
@@ -158,7 +160,7 @@ pub fn show_simple_message_box(flags: MessageBoxFlag, title: &str,
flags.bits(),
title.as_ptr() as *const c_char,
message.as_ptr() as *const c_char,
window.map_or(ptr::null_mut(), |win| win.raw())
window.into().map_or(ptr::null_mut(), |win| win.raw())
)
} == 0;
@@ -178,9 +180,15 @@ pub fn show_simple_message_box(flags: MessageBoxFlag, title: &str,
/// Note that the variant of the `ClickedButton` enum will also be returned if the message box
/// has been forcefully closed (Alt-F4, ...)
///
pub fn show_message_box<'a>(flags:MessageBoxFlag, buttons:&'a [ButtonData], title:&str,
message:&str, window:Option<&WindowRef>, scheme:Option<MessageBoxColorScheme>)
-> Result<ClickedButton<'a>,ShowMessageError> {
pub fn show_message_box<'a, 'b, W, M>(flags:MessageBoxFlag, buttons:&'a [ButtonData], title:&str,
message:&str, window: W, scheme: M)
-> Result<ClickedButton<'a>,ShowMessageError>
where W: Into<Option<&'b WindowRef>>,
M: Into<Option<MessageBoxColorScheme>>,
{
let window = window.into();
let scheme = scheme.into();
use self::ShowMessageError::*;
let mut button_id : c_int = 0;
let title = match CString::new(title) {
+5 -2
View File
@@ -328,8 +328,11 @@ impl Rect {
/// Calculate a minimal rectangle enclosing a set of points.
/// If a clipping rectangle is given, only points that are within it will be
/// considered.
pub fn from_enclose_points(points: &[Point], clipping_rect: Option<Rect>)
-> Option<Rect> {
pub fn from_enclose_points<R: Into<Option<Rect>>>(points: &[Point], clipping_rect: R)
-> Option<Rect>
where R: Into<Option<Rect>>
{
let clipping_rect = clipping_rect.into();
if points.len() == 0 {
return None;
+84 -76
View File
@@ -111,7 +111,7 @@ impl FromPrimitive for BlendMode {
impl RendererInfo {
pub unsafe fn from_ll(info: &ll::SDL_RendererInfo) -> RendererInfo {
let texture_formats: Vec<pixels::PixelFormatEnum> =
let texture_formats: Vec<pixels::PixelFormatEnum> =
info.texture_formats[0..(info.num_texture_formats as usize)]
.iter().map(|&format| {
PixelFormatEnum::from_i64(format as i64).unwrap_or(PixelFormatEnum::Unknown)
@@ -236,9 +236,9 @@ impl RendererBuilder {
impl<'a> Renderer<'a> {
/// Creates a 2D software rendering context for a surface.
///
/// This method should only fail if SDL2 is not built with rendering
/// This method should only fail if SDL2 is not built with rendering
/// support, or there's an out-of-memory error.
pub fn from_surface(surface: surface::Surface<'a>)
pub fn from_surface(surface: surface::Surface<'a>)
-> Result<Renderer<'a>, String> {
let raw_renderer = unsafe { ll::SDL_CreateSoftwareRenderer(surface.raw()) };
if raw_renderer != ptr::null_mut() {
@@ -267,8 +267,8 @@ impl<'a> Renderer<'a> {
fn parent(&self) -> &RendererParent { self.parent.as_ref().unwrap() }
#[inline]
fn parent_mut(&mut self) -> &mut RendererParent<'a> {
self.parent.as_mut().unwrap()
fn parent_mut(&mut self) -> &mut RendererParent<'a> {
self.parent.as_mut().unwrap()
}
/// Gets the associated window reference of the Renderer, if there is one.
@@ -384,8 +384,8 @@ impl<'a> Renderer<'a> {
/// Creates a texture for a rendering context.
///
/// `size` is the width and height of the texture.
pub fn create_texture(&self, format: pixels::PixelFormatEnum,
access: TextureAccess, width: u32, height: u32)
pub fn create_texture(&self, format: pixels::PixelFormatEnum,
access: TextureAccess, width: u32, height: u32)
-> Result<Texture, TextureValueError> {
use self::TextureValueError::*;
let w = match validate_int(width, "width") {
@@ -408,7 +408,7 @@ impl<'a> Renderer<'a> {
_ => ()
}
let result = unsafe {
let result = unsafe {
ll::SDL_CreateTexture(
self.raw, format as uint32_t, access as c_int, w, h
)
@@ -421,21 +421,21 @@ impl<'a> Renderer<'a> {
}
/// Shorthand for `create_texture(format, TextureAccess::Static, size)`
pub fn create_texture_static(&self, format: pixels::PixelFormatEnum,
width: u32, height: u32)
pub fn create_texture_static(&self, format: pixels::PixelFormatEnum,
width: u32, height: u32)
-> Result<Texture, TextureValueError> {
self.create_texture(format, TextureAccess::Static, width, height)
}
/// Shorthand for `create_texture(format, TextureAccess::Streaming, size)`
pub fn create_texture_streaming(&self, format: pixels::PixelFormatEnum,
pub fn create_texture_streaming(&self, format: pixels::PixelFormatEnum,
width: u32, height: u32)
-> Result<Texture, TextureValueError> {
self.create_texture(format, TextureAccess::Streaming, width, height)
}
/// Shorthand for `create_texture(format, TextureAccess::Target, size)`
pub fn create_texture_target(&self, format: pixels::PixelFormatEnum,
pub fn create_texture_target(&self, format: pixels::PixelFormatEnum,
width: u32, height: u32)
-> Result<Texture, TextureValueError> {
self.create_texture(format, TextureAccess::Target, width, height)
@@ -447,7 +447,7 @@ impl<'a> Renderer<'a> {
pub fn create_texture_from_surface<S: AsRef<SurfaceRef>>(&self, surface: S)
-> Result<Texture, TextureValueError> {
use self::TextureValueError::*;
let result = unsafe {
let result = unsafe {
ll::SDL_CreateTextureFromSurface(self.raw, surface.as_ref().raw())
};
if result == ptr::null_mut() {
@@ -499,7 +499,7 @@ impl<'a> Renderer<'a> {
/// Gets the color used for drawing operations (Rect, Line and Clear).
pub fn draw_color(&self) -> pixels::Color {
let (mut r, mut g, mut b, mut a) = (0, 0, 0, 0);
let ret = unsafe {
let ret = unsafe {
ll::SDL_GetRenderDrawColor(self.raw, &mut r, &mut g, &mut b, &mut a)
};
// Should only fail on an invalid renderer
@@ -509,7 +509,7 @@ impl<'a> Renderer<'a> {
/// Sets the blend mode used for drawing operations (Fill and Line).
pub fn set_blend_mode(&mut self, blend: BlendMode) {
let ret = unsafe {
let ret = unsafe {
ll::SDL_SetRenderDrawBlendMode(
self.raw, FromPrimitive::from_i64(blend as i64).unwrap()
)
@@ -549,7 +549,7 @@ impl<'a> Renderer<'a> {
let mut width = 0;
let mut height = 0;
let result = unsafe {
let result = unsafe {
ll::SDL_GetRendererOutputSize(self.raw, &mut width, &mut height)
};
@@ -561,7 +561,7 @@ impl<'a> Renderer<'a> {
}
/// Sets a device independent resolution for rendering.
pub fn set_logical_size(&mut self, width: u32, height: u32)
pub fn set_logical_size(&mut self, width: u32, height: u32)
-> Result<(), IntegerOrSdlError> {
use common::IntegerOrSdlError::*;
let width = try!(validate_int(width, "width"));
@@ -588,12 +588,12 @@ impl<'a> Renderer<'a> {
}
/// Sets the drawing area for rendering on the current target.
pub fn set_viewport(&mut self, rect: Option<Rect>) {
let ptr = match rect {
pub fn set_viewport<R: Into<Option<Rect>>>(&mut self, rect: R) {
let ptr = match rect.into() {
Some(ref rect) => rect.raw(),
None => ptr::null()
};
let ret = unsafe {
let ret = unsafe {
ll::SDL_RenderSetViewport(self.raw, ptr)
};
if ret != 0 { panic!("Could not set viewport: {}", get_error()) }
@@ -602,7 +602,7 @@ impl<'a> Renderer<'a> {
/// Gets the drawing area for the current target.
pub fn viewport(&self) -> Rect {
let mut rect = unsafe { mem::uninitialized() };
unsafe {
unsafe {
ll::SDL_RenderGetViewport(self.raw, &mut rect)
};
Rect::from_ll(rect)
@@ -611,11 +611,11 @@ impl<'a> Renderer<'a> {
/// Sets the clip rectangle for rendering on the specified target.
///
/// If the rectangle is `None`, clipping will be disabled.
pub fn set_clip_rect(&mut self, rect: Option<Rect>) {
pub fn set_clip_rect<R: Into<Option<Rect>>>(&mut self, rect: R) {
let ret = unsafe {
ll::SDL_RenderSetClipRect(
self.raw,
match rect {
match rect.into() {
Some(ref rect) => rect.raw(),
None => ptr::null()
}
@@ -629,8 +629,8 @@ impl<'a> Renderer<'a> {
/// Returns `None` if clipping is disabled.
pub fn clip_rect(&self) -> Option<Rect> {
let mut raw = unsafe { mem::uninitialized() };
unsafe {
ll::SDL_RenderGetClipRect(self.raw, &mut raw)
unsafe {
ll::SDL_RenderGetClipRect(self.raw, &mut raw)
};
if raw.w == 0 || raw.h == 0 {
None
@@ -640,7 +640,7 @@ impl<'a> Renderer<'a> {
}
/// Sets the drawing scale for rendering on the current target.
pub fn set_scale(&mut self, scale_x: f32, scale_y: f32)
pub fn set_scale(&mut self, scale_x: f32, scale_y: f32)
-> Result<(), String> {
let ret = unsafe { ll::SDL_RenderSetScale(self.raw, scale_x, scale_y) };
// Should only fail on an invalid renderer
@@ -790,30 +790,26 @@ impl<'a> Renderer<'a> {
///
/// Errors if drawing fails for any reason (e.g. driver failure),
/// or if the provided texture does not belong to the renderer.
pub fn copy(&mut self, texture: &Texture, src: Option<Rect>, dst: Option<Rect>)
-> Result<(), String> {
pub fn copy<R1, R2>(&mut self, texture: &Texture, src: R1, dst: R2) -> Result<(), String>
where R1: Into<Option<Rect>>,
R2: Into<Option<Rect>>
{
texture.check_renderer();
let ret = unsafe {
ll::SDL_RenderCopy(
self.raw,
texture.raw,
match src {
Some(ref rect) => rect.raw(),
None => ptr::null()
},
match dst {
Some(ref rect) => rect.raw(),
None => ptr::null()
}
)
ll::SDL_RenderCopy(self.raw,
texture.raw,
match src.into() {
Some(ref rect) => rect.raw(),
None => ptr::null(),
},
match dst.into() {
Some(ref rect) => rect.raw(),
None => ptr::null(),
})
};
if ret != 0 {
Err(get_error())
} else {
Ok(())
}
if ret != 0 { Err(get_error()) } else { Ok(()) }
}
/// Copies a portion of the texture to the current rendering target,
@@ -829,10 +825,13 @@ impl<'a> Renderer<'a> {
/// Errors if drawing fails for any reason (e.g. driver failure),
/// if the provided texture does not belong to the renderer,
/// or if the driver does not support RenderCopyEx.
pub fn copy_ex(&mut self, texture: &Texture, src: Option<Rect>,
dst: Option<Rect>, angle: f64, center: Option<Point>,
flip_horizontal: bool, flip_vertical: bool)
-> Result<(), String> {
pub fn copy_ex<R1, R2, P>(&mut self, texture: &Texture, src: R1,
dst: R2, angle: f64, center: P,
flip_horizontal: bool, flip_vertical: bool) -> Result<(), String>
where R1: Into<Option<Rect>>,
R2: Into<Option<Rect>>,
P: Into<Option<Point>>
{
texture.check_renderer();
let flip = match (flip_horizontal, flip_vertical) {
@@ -846,16 +845,16 @@ impl<'a> Renderer<'a> {
ll::SDL_RenderCopyEx(
self.raw,
texture.raw,
match src {
match src.into() {
Some(ref rect) => rect.raw(),
None => ptr::null()
},
match dst {
match dst.into() {
Some(ref rect) => rect.raw(),
None => ptr::null()
},
angle as c_double,
match center {
match center.into() {
Some(ref point) => point.raw(),
None => ptr::null()
},
@@ -873,10 +872,11 @@ impl<'a> Renderer<'a> {
/// Reads pixels from the current rendering target.
/// # Remarks
/// WARNING: This is a very slow operation, and should not be used frequently.
pub fn read_pixels(&self, rect: Option<Rect>,
pub fn read_pixels<R: Into<Option<Rect>>>(&self, rect: R,
format: pixels::PixelFormatEnum)
-> Result<Vec<u8>, String> {
unsafe {
let rect = rect.into();
let (actual_rect, w, h) = match rect {
Some(ref rect) => (rect.raw(), rect.width() as usize, rect.height() as usize),
None => {
@@ -982,7 +982,7 @@ impl<'renderer> RenderTarget<'renderer> {
/// Creates a new texture and sets it as the render target.
///
/// The old render target is returned if the function is successful.
pub fn create_and_set(&mut self, format: pixels::PixelFormatEnum,
pub fn create_and_set(&mut self, format: pixels::PixelFormatEnum,
width: u32, height: u32)
-> Result<Option<Texture>, IntegerOrSdlError> {
use common::IntegerOrSdlError::*;
@@ -1269,17 +1269,20 @@ impl Texture {
/// between lines
///
/// * If `rect` is `None`, the entire texture is updated.
pub fn update(&mut self, rect: Option<Rect>,
pixel_data: &[u8], pitch: usize)
-> Result<(), UpdateTextureError> {
pub fn update<R>(&mut self, rect: R,
pixel_data: &[u8], pitch: usize)
-> Result<(), UpdateTextureError>
where R: Into<Option<Rect>>
{
use self::UpdateTextureError::*;
self.check_renderer();
let rect = rect.into();
let rect_raw_ptr = match rect {
Some(ref rect) => rect.raw(),
None => ptr::null()
};
// Check if the rectangle's position or size is odd, and if the pitch is odd.
// This needs to be done in case the texture's pixel format is planar YUV.
// See issue #334 for details.
@@ -1323,28 +1326,32 @@ impl Texture {
Ok(p) => p,
Err(_) => return Err(PitchOverflows(pitch)),
};
let result = unsafe {
ll::SDL_UpdateTexture(
self.raw, rect_raw_ptr, pixel_data.as_ptr() as *const _, pitch
)
};
if result != 0 {
if result != 0 {
Err(SdlError(get_error()))
} else {
} else {
Ok(())
}
}
/// Updates a rectangle within a planar YV12 or IYUV texture with new pixel data.
pub fn update_yuv(&mut self, rect: Option<Rect>, y_plane: &[u8],
y_pitch: usize, u_plane: &[u8], u_pitch: usize, v_plane: &[u8],
v_pitch: usize)
-> Result<(), UpdateTextureYUVError> {
pub fn update_yuv<R>(&mut self, rect: R, y_plane: &[u8],
y_pitch: usize, u_plane: &[u8], u_pitch: usize, v_plane: &[u8],
v_pitch: usize)
-> Result<(), UpdateTextureYUVError>
where R: Into<Option<Rect>>,
{
use self::UpdateTextureYUVError::*;
self.check_renderer();
let rect = rect.into();
let rect_raw_ptr = match rect {
Some(ref rect) => rect.raw(),
None => ptr::null()
@@ -1389,19 +1396,19 @@ impl Texture {
//let wrong_length =
if y_plane.len() != (y_pitch * height) {
return Err(InvalidPlaneLength {
return Err(InvalidPlaneLength {
plane: "y", length: y_plane.len(), pitch: y_pitch, height: height
});
}
if u_plane.len() != (u_pitch * height / 2) {
return Err(InvalidPlaneLength {
plane: "u", length: u_plane.len(), pitch: u_pitch,
return Err(InvalidPlaneLength {
plane: "u", length: u_plane.len(), pitch: u_pitch,
height: height / 2
});
}
}
if v_plane.len() != (v_pitch * height / 2) {
return Err(InvalidPlaneLength {
plane: "v", length: v_plane.len(), pitch: v_pitch,
return Err(InvalidPlaneLength {
plane: "v", length: v_plane.len(), pitch: v_pitch,
height: height / 2
});
}
@@ -1431,7 +1438,7 @@ impl Texture {
v_pitch
)
};
if result != 0 {
if result != 0 {
Err(SdlError(get_error()))
} else {
Ok(())
@@ -1448,8 +1455,9 @@ impl Texture {
/// necessarily contain the old texture data.
/// This is a write-only operation, and if you need to keep a copy of the
/// texture data you should do that at the application level.
pub fn with_lock<F, R>(&mut self, rect: Option<Rect>, func: F) -> Result<R, String>
where F: FnOnce(&mut [u8], usize) -> R
pub fn with_lock<F, R, R2>(&mut self, rect: R2, func: F) -> Result<R, String>
where F: FnOnce(&mut [u8], usize) -> R,
R2: Into<Option<Rect>>
{
self.check_renderer();
@@ -1459,7 +1467,7 @@ impl Texture {
let mut pixels = ptr::null_mut();
let mut pitch = 0;
let (rect_raw_ptr, height) = match rect {
let (rect_raw_ptr, height) = match rect.into() {
Some(ref rect) => (rect.raw(), rect.height() as usize),
None => (ptr::null(), q.height as usize)
};
+41 -16
View File
@@ -402,9 +402,11 @@ impl SurfaceRef {
}
}
pub fn fill_rect(&mut self, rect: Option<Rect>, color: pixels::Color) -> Result<(), String> {
pub fn fill_rect<R>(&mut self, rect: R, color: pixels::Color) -> Result<(), String>
where R: Into<Option<Rect>>
{
unsafe {
let rect_ptr = mem::transmute( rect.as_ref() );
let rect_ptr = mem::transmute( rect.into().as_ref() );
let format = self.pixel_format();
let result = ll::SDL_FillRect(self.raw(), rect_ptr, color.to_u32(&format) );
match result {
@@ -414,7 +416,8 @@ impl SurfaceRef {
}
}
pub fn fill_rects(&mut self, rects: &[Option<Rect>], color: pixels::Color) -> Result<(), String> {
pub fn fill_rects(&mut self, rects: &[Rect], color: pixels::Color) -> Result<(), String>
{
for rect in rects.iter() {
let result = self.fill_rect(rect.clone(), color);
match result {
@@ -478,7 +481,10 @@ impl SurfaceRef {
/// Sets the clip rectangle for the surface.
///
/// If the rectangle is `None`, clipping will be disabled.
pub fn set_clip_rect(&mut self, rect: Option<Rect>) -> bool {
pub fn set_clip_rect<R>(&mut self, rect: R) -> bool
where R: Into<Option<Rect>>
{
let rect = rect.into();
unsafe {
ll::SDL_SetClipRect(self.raw(), match rect {
Some(rect) => rect.raw(),
@@ -514,16 +520,22 @@ impl SurfaceRef {
}
}
// Note: There's no need to implement SDL_ConvertSurfaceFormat, as it
// Note: There's no need to implement SDL_ConvertSurfaceFormat, as it
// does the same thing as SDL_ConvertSurface but with a slightly different
// function signature.
/// Performs surface blitting (surface copying).
///
/// Returns the final blit rectangle, if a `dst_rect` was provided.
pub fn blit(&self, src_rect: Option<Rect>,
dst: &mut SurfaceRef, dst_rect: Option<Rect>)
-> Result<Option<Rect>, String> {
pub fn blit<R1, R2>(&self, src_rect: R1,
dst: &mut SurfaceRef, dst_rect: R2)
-> Result<Option<Rect>, String>
where R1: Into<Option<Rect>>,
R2: Into<Option<Rect>>,
{
let src_rect = src_rect.into();
let dst_rect = dst_rect.into();
unsafe {
let src_rect_ptr = src_rect.as_ref().map(|r| r.raw()).unwrap_or(ptr::null());
@@ -548,8 +560,13 @@ impl SurfaceRef {
///
/// Unless you know what you're doing, use `blit()` instead, which will clip the input rectangles.
/// This function could crash if the rectangles aren't pre-clipped to the surface, and is therefore unsafe.
pub unsafe fn lower_blit(&self, src_rect: Option<Rect>,
dst: &mut SurfaceRef, dst_rect: Option<Rect>) -> Result<(), String> {
pub unsafe fn lower_blit<R1, R2>(&self, src_rect: R1,
dst: &mut SurfaceRef, dst_rect: R2) -> Result<(), String>
where R1: Into<Option<Rect>>,
R2: Into<Option<Rect>>,
{
let src_rect = src_rect.into();
let dst_rect = dst_rect.into();
match {
// The rectangles don't change, but the function requires mutable pointers.
@@ -567,8 +584,13 @@ impl SurfaceRef {
/// Performs scaled surface bliting (surface copying).
///
/// Returns the final blit rectangle, if a `dst_rect` was provided.
pub fn blit_scaled(&self, src_rect: Option<Rect>,
dst: &mut SurfaceRef, dst_rect: Option<Rect>) -> Result<Option<Rect>, String> {
pub fn blit_scaled<R1, R2>(&self, src_rect: R1,
dst: &mut SurfaceRef, dst_rect: R2) -> Result<Option<Rect>, String>
where R1: Into<Option<Rect>>,
R2: Into<Option<Rect>>,
{
let src_rect = src_rect.into();
let dst_rect = dst_rect.into();
match unsafe {
let src_rect_ptr = src_rect.as_ref().map(|r| r.raw()).unwrap_or(ptr::null());
@@ -589,14 +611,17 @@ impl SurfaceRef {
///
/// Unless you know what you're doing, use `blit_scaled()` instead, which will clip the input rectangles.
/// This function could crash if the rectangles aren't pre-clipped to the surface, and is therefore unsafe.
pub unsafe fn lower_blit_scaled(&self, src_rect: Option<Rect>,
dst: &mut SurfaceRef, dst_rect: Option<Rect>) -> Result<(), String> {
pub unsafe fn lower_blit_scaled<R1, R2>(&self, src_rect: R1,
dst: &mut SurfaceRef, dst_rect: R2) -> Result<(), String>
where R1: Into<Option<Rect>>,
R2: Into<Option<Rect>>
{
match {
// The rectangles don't change, but the function requires mutable pointers.
let src_rect_ptr = src_rect.as_ref().map(|r| r.raw())
let src_rect_ptr = src_rect.into().as_ref().map(|r| r.raw())
.unwrap_or(ptr::null()) as *mut _;
let dst_rect_ptr = dst_rect.as_ref().map(|r| r.raw())
let dst_rect_ptr = dst_rect.into().as_ref().map(|r| r.raw())
.unwrap_or(ptr::null()) as *mut _;
ll::SDL_LowerBlitScaled(self.raw(), src_rect_ptr, dst.raw(), dst_rect_ptr)
} {
+4 -3
View File
@@ -289,9 +289,10 @@ pub fn internal_load_font<'ttf,P:AsRef<Path>>(path: P, ptsize: u16) -> Result<Fo
}
/// Internally used to load a font (for internal visibility).
pub fn internal_load_font_from_ll<'ttf,'r>(raw: *const ffi::TTF_Font, rwops: Option<RWops<'r>>)
-> Font<'ttf,'r> {
Font { raw: raw, rwops: rwops, _marker: PhantomData }
pub fn internal_load_font_from_ll<'ttf,'r, R>(raw: *const ffi::TTF_Font, rwops: R)
-> Font<'ttf,'r>
where R: Into<Option<RWops<'r>>> {
Font { raw: raw, rwops: rwops.into(), _marker: PhantomData }
}
/// Internally used to load a font (for internal visibility).
+12 -8
View File
@@ -989,11 +989,13 @@ impl WindowRef {
}
}
pub fn set_display_mode(&mut self, display_mode: Option<DisplayMode>) -> Result<(), String> {
pub fn set_display_mode<D>(&mut self, display_mode: D) -> Result<(), String>
where D: Into<Option<DisplayMode>>
{
unsafe {
let result = ll::SDL_SetWindowDisplayMode(
self.raw(),
match display_mode {
match display_mode.into() {
Some(ref mode) => &mode.to_ll(),
None => ptr::null()
}
@@ -1243,18 +1245,20 @@ impl WindowRef {
unsafe { ll::SDL_GetWindowBrightness(self.raw()) as f64 }
}
pub fn set_gamma_ramp(&mut self, red: Option<&[u16; 256]>,
green: Option<&[u16; 256]>, blue: Option<&[u16; 256]>)
-> Result<(), String> {
let unwrapped_red = match red {
pub fn set_gamma_ramp<'a, 'b, 'c, R, G, B>(&mut self, red: R, green: G, blue: B) -> Result<(), String>
where R: Into<Option<&'a [u16; 256]>>,
G: Into<Option<&'b [u16; 256]>>,
B: Into<Option<&'c [u16; 256]>>,
{
let unwrapped_red = match red.into() {
Some(values) => values.as_ptr(),
None => ptr::null()
};
let unwrapped_green = match green {
let unwrapped_green = match green.into() {
Some(values) => values.as_ptr(),
None => ptr::null()
};
let unwrapped_blue = match blue {
let unwrapped_blue = match blue.into() {
Some(values) => values.as_ptr(),
None => ptr::null()
};