diff --git a/changelog.md b/changelog.md index 89a692132e0..258661b48d3 100644 --- a/changelog.md +++ b/changelog.md @@ -8,6 +8,8 @@ when upgrading from a version of rust-sdl2 to another. [PR #1378](https://github.com/Rust-SDL2/rust-sdl2/pull/1378) **BREAKING CHANGE** Change `Keycode` to be a struct rather than an enum. Fix `Keycode::from_scancode` for non-QWERTY keyboard layouts. +[PR #1390](https://github.com/Rust-SDL2/rust-sdl2/pull/1390) Apply clippy fixes, fix deprecations and other code quality improvements. + [PR #1368](https://github.com/Rust-SDL2/rust-sdl2/pull/1368) Remove unnecessary unsafe in Window interface. Make Window `Clone`. [PR #1366](https://github.com/Rust-SDL2/rust-sdl2/pull/1366) Add Primary Selection bindings. @@ -22,7 +24,7 @@ when upgrading from a version of rust-sdl2 to another. [PR #1250](https://github.com/Rust-SDL2/rust-sdl2/pull/1250) Add `lib64` to native library search path when using bundled feature -[PR #1240](https://github.com/Rust-SDL2/rust-sdl2/pull/1240) **BREAKING CHANGE** Take `PixelMasks` by refrence +[PR #1240](https://github.com/Rust-SDL2/rust-sdl2/pull/1240) **BREAKING CHANGE** Take `PixelMasks` by reference [PR #1254](https://github.com/Rust-SDL2/rust-sdl2/pull/1254) **BREAKING CHANGE** Make `SdlDrop` and `SubsystemDrop` safer; forbid external code from constructing `SdlDrop` @@ -34,8 +36,6 @@ when upgrading from a version of rust-sdl2 to another. [PR #1337](https://github.com/Rust-SDL2/rust-sdl2/pull/1337) Fix "Cannot initialize Sdl from more than one thread" for tests / CI -[PR #1337](https://github.com/Rust-SDL2/rust-sdl2/pull/1337) Fix "Cannot initialize Sdl from more than one thread" for tests / CI - [PR #1346](https://github.com/Rust-SDL2/rust-sdl2/pull/1346) Add basic Shaped Window support [PR #1314](https://github.com/Rust-SDL2/rust-sdl2/pull/1314) Add "ALWAYS ON TOP" support for X11 diff --git a/sdl2-sys/build.rs b/sdl2-sys/build.rs index aee3f1a045e..067d89f05af 100644 --- a/sdl2-sys/build.rs +++ b/sdl2-sys/build.rs @@ -36,8 +36,8 @@ macro_rules! add_msvc_includes_to_bindings { fn init_submodule(sdl_path: &Path) { if !sdl_path.join("CMakeLists.txt").exists() { Command::new("git") - .args(&["submodule", "update", "--init"]) - .current_dir(sdl_path.clone()) + .args(["submodule", "update", "--init"]) + .current_dir(sdl_path) .status() .expect("Git is needed to retrieve the SDL source files"); } @@ -436,15 +436,17 @@ fn copy_library_file(src_path: &Path, target_path: &Path) { for path in &[target_path, &deps_path] { let dst_path = path.join(src_path.file_name().expect("Path missing filename")); - fs::copy(&src_path, &dst_path).expect(&format!( - "Failed to copy SDL2 dynamic library from {} to {}", - src_path.to_string_lossy(), - dst_path.to_string_lossy() - )); + fs::copy(src_path, &dst_path).unwrap_or_else(|_| { + panic!( + "Failed to copy SDL2 dynamic library from {} to {}", + src_path.to_string_lossy(), + dst_path.to_string_lossy() + ) + }); } } -fn copy_dynamic_libraries(sdl2_compiled_path: &PathBuf, target_os: &str) { +fn copy_dynamic_libraries(sdl2_compiled_path: &Path, target_os: &str) { let target_path = find_cargo_target_dir(); // Windows binaries do not embed library search paths, so successfully @@ -651,35 +653,35 @@ fn generate_bindings(target: &str, host: &str, headers_paths: &[String]) { // Set correct target triple for bindgen when cross-compiling if target != host { bindings = bindings.clang_arg("-target"); - bindings = bindings.clang_arg(target.clone()); + bindings = bindings.clang_arg(target); if cfg!(feature = "image") { image_bindings = image_bindings.clang_arg("-target"); - image_bindings = image_bindings.clang_arg(target.clone()); + image_bindings = image_bindings.clang_arg(target); } if cfg!(feature = "ttf") { ttf_bindings = ttf_bindings.clang_arg("-target"); - ttf_bindings = ttf_bindings.clang_arg(target.clone()); + ttf_bindings = ttf_bindings.clang_arg(target); } if cfg!(feature = "mixer") { mixer_bindings = mixer_bindings.clang_arg("-target"); - mixer_bindings = mixer_bindings.clang_arg(target.clone()); + mixer_bindings = mixer_bindings.clang_arg(target); } if cfg!(feature = "gfx") { gfx_framerate_bindings = gfx_framerate_bindings.clang_arg("-target"); - gfx_framerate_bindings = gfx_framerate_bindings.clang_arg(target.clone()); + gfx_framerate_bindings = gfx_framerate_bindings.clang_arg(target); gfx_primitives_bindings = gfx_primitives_bindings.clang_arg("-target"); - gfx_primitives_bindings = gfx_primitives_bindings.clang_arg(target.clone()); + gfx_primitives_bindings = gfx_primitives_bindings.clang_arg(target); gfx_imagefilter_bindings = gfx_imagefilter_bindings.clang_arg("-target"); - gfx_imagefilter_bindings = gfx_imagefilter_bindings.clang_arg(target.clone()); + gfx_imagefilter_bindings = gfx_imagefilter_bindings.clang_arg(target); gfx_rotozoom_bindings = gfx_rotozoom_bindings.clang_arg("-target"); - gfx_rotozoom_bindings = gfx_rotozoom_bindings.clang_arg(target.clone()); + gfx_rotozoom_bindings = gfx_rotozoom_bindings.clang_arg(target); } } @@ -943,5 +945,5 @@ fn generate_bindings(target: &str, host: &str, headers_paths: &[String]) { } fn get_os_from_triple(triple: &str) -> Option<&str> { - triple.splitn(3, "-").nth(2) + triple.splitn(3, '-').nth(2) } diff --git a/src/sdl2/audio.rs b/src/sdl2/audio.rs index 7b5c9ce3040..6cda64a5305 100644 --- a/src/sdl2/audio.rs +++ b/src/sdl2/audio.rs @@ -774,10 +774,7 @@ impl<'a, Channel: AudioFormatNum> AudioQueue { let mut obtained = MaybeUninit::uninit(); unsafe { - let device = match device.into() { - Some(device) => Some(CString::new(device).unwrap()), - None => None, - }; + let device = device.into().map(|device| CString::new(device).unwrap()); // Warning: map_or consumes its argument; `device.map_or()` would therefore consume the // CString and drop it, making device_ptr a dangling pointer! To avoid that we downgrade // device to an Option<&_> first. @@ -801,7 +798,7 @@ impl<'a, Channel: AudioFormatNum> AudioQueue { Ok(AudioQueue { subsystem: a.clone(), device_id, - phantom: PhantomData::default(), + phantom: PhantomData, spec, }) } @@ -850,7 +847,7 @@ impl<'a, Channel: AudioFormatNum> AudioQueue { sys::SDL_QueueAudio( self.device_id.id(), data.as_ptr() as *const c_void, - (data.len() * mem::size_of::()) as u32, + mem::size_of_val(data) as u32, ) }; result == 0 @@ -863,7 +860,7 @@ impl<'a, Channel: AudioFormatNum> AudioQueue { sys::SDL_QueueAudio( self.device_id.id(), data.as_ptr() as *const c_void, - (data.len() * mem::size_of::()) as u32, + mem::size_of_val(data) as u32, ) }; if result == 0 { @@ -918,10 +915,7 @@ impl AudioDevice { let mut obtained = MaybeUninit::uninit(); unsafe { - let device = match device.into() { - Some(device) => Some(CString::new(device).unwrap()), - None => None, - }; + let device = device.into().map(|device| CString::new(device).unwrap()); // Warning: map_or consumes its argument; `device.map_or()` would therefore consume the // CString and drop it, making device_ptr a dangling pointer! To avoid that we downgrade // device to an Option<&_> first. diff --git a/src/sdl2/common.rs b/src/sdl2/common.rs index 9492b20595a..ff2daf8c067 100644 --- a/src/sdl2/common.rs +++ b/src/sdl2/common.rs @@ -36,13 +36,4 @@ impl fmt::Display for IntegerOrSdlError { } } -impl Error for IntegerOrSdlError { - fn description(&self) -> &str { - use self::IntegerOrSdlError::*; - - match *self { - IntegerOverflows(_, _) => "integer overflow", - SdlError(ref e) => e, - } - } -} +impl Error for IntegerOrSdlError {} diff --git a/src/sdl2/controller.rs b/src/sdl2/controller.rs index fe5969b7aa2..33c60ca94ff 100644 --- a/src/sdl2/controller.rs +++ b/src/sdl2/controller.rs @@ -41,14 +41,10 @@ impl fmt::Display for AddMappingError { } impl error::Error for AddMappingError { - fn description(&self) -> &str { - use self::AddMappingError::*; - - match *self { - InvalidMapping(_) => "invalid mapping", - InvalidFilePath(_) => "invalid file path", - ReadError(_) => "read error", - SdlError(ref e) => e, + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + match self { + Self::InvalidMapping(err) => Some(err), + Self::InvalidFilePath(_) | Self::ReadError(_) | Self::SdlError(_) => None, } } } @@ -126,9 +122,7 @@ impl GameControllerSubsystem { /// Return `true` if controller events are processed. #[doc(alias = "SDL_GameControllerEventState")] pub fn event_state(&self) -> bool { - unsafe { - sys::SDL_GameControllerEventState(sys::SDL_QUERY as i32) == sys::SDL_ENABLE as i32 - } + unsafe { sys::SDL_GameControllerEventState(sys::SDL_QUERY) == sys::SDL_ENABLE as i32 } } /// Add a new controller input mapping from a mapping string. @@ -172,7 +166,7 @@ impl GameControllerSubsystem { /// Load controller input mappings from an SDL [`RWops`] object. #[doc(alias = "SDL_GameControllerAddMappingsFromRW")] - pub fn load_mappings_from_rw<'a>(&self, rw: RWops<'a>) -> Result { + pub fn load_mappings_from_rw(&self, rw: RWops<'_>) -> Result { use self::AddMappingError::*; let result = unsafe { sys::SDL_GameControllerAddMappingsFromRW(rw.raw(), 0) }; diff --git a/src/sdl2/event.rs b/src/sdl2/event.rs index 6ad9c0fd796..6849d98883e 100644 --- a/src/sdl2/event.rs +++ b/src/sdl2/event.rs @@ -110,10 +110,7 @@ impl crate::EventSubsystem { } else { events.set_len(result as usize); - events - .into_iter() - .map(|event_raw| Event::from_ll(event_raw)) - .collect() + events.into_iter().map(Event::from_ll).collect() } } } @@ -160,7 +157,7 @@ impl crate::EventSubsystem { /// Returns an error, if no more user events can be created. pub unsafe fn register_events(&self, nr: u32) -> Result, String> { let result = sys::SDL_RegisterEvents(nr as ::libc::c_int); - const ERR_NR: u32 = ::std::u32::MAX - 1; + const ERR_NR: u32 = u32::MAX - 1; match result { ERR_NR => Err("No more user events can be created; SDL_LASTEVENT reached".to_owned()), @@ -439,8 +436,8 @@ impl DisplayEvent { } } - fn to_ll(&self) -> (u8, i32) { - match *self { + fn to_ll(self) -> (u8, i32) { + match self { DisplayEvent::None => (sys::SDL_DisplayEventID::SDL_DISPLAYEVENT_NONE as u8, 0), DisplayEvent::Orientation(orientation) => ( sys::SDL_DisplayEventID::SDL_DISPLAYEVENT_ORIENTATION as u8, @@ -457,13 +454,7 @@ impl DisplayEvent { } pub fn is_same_kind_as(&self, other: &DisplayEvent) -> bool { - match (self, other) { - (Self::None, Self::None) - | (Self::Orientation(_), Self::Orientation(_)) - | (Self::Connected, Self::Connected) - | (Self::Disconnected, Self::Disconnected) => true, - _ => false, - } + mem::discriminant(self) == mem::discriminant(other) } } @@ -518,8 +509,8 @@ impl WindowEvent { } } - fn to_ll(&self) -> (u8, i32, i32) { - match *self { + fn to_ll(self) -> (u8, i32, i32) { + match self { WindowEvent::None => (0, 0, 0), WindowEvent::Shown => (1, 0, 0), WindowEvent::Hidden => (2, 0, 0), @@ -543,28 +534,7 @@ impl WindowEvent { } pub fn is_same_kind_as(&self, other: &WindowEvent) -> bool { - match (self, other) { - (Self::None, Self::None) - | (Self::Shown, Self::Shown) - | (Self::Hidden, Self::Hidden) - | (Self::Exposed, Self::Exposed) - | (Self::Moved(_, _), Self::Moved(_, _)) - | (Self::Resized(_, _), Self::Resized(_, _)) - | (Self::SizeChanged(_, _), Self::SizeChanged(_, _)) - | (Self::Minimized, Self::Minimized) - | (Self::Maximized, Self::Maximized) - | (Self::Restored, Self::Restored) - | (Self::Enter, Self::Enter) - | (Self::Leave, Self::Leave) - | (Self::FocusGained, Self::FocusGained) - | (Self::FocusLost, Self::FocusLost) - | (Self::Close, Self::Close) - | (Self::TakeFocus, Self::TakeFocus) - | (Self::HitTest, Self::HitTest) - | (Self::ICCProfChanged, Self::ICCProfChanged) - | (Self::DisplayChanged(_), Self::DisplayChanged(_)) => true, - _ => false, - } + mem::discriminant(self) == mem::discriminant(other) } } @@ -970,7 +940,7 @@ where .into() .map(|kc| kc.into()) .unwrap_or(sys::SDL_KeyCode::SDLK_UNKNOWN as i32); - let keymod = keymod.bits() as u16; + let keymod = keymod.bits(); sys::SDL_Keysym { scancode, sym: keycode, @@ -995,10 +965,10 @@ impl Event { timestamp, } => { let event = sys::SDL_UserEvent { - type_: type_ as u32, + type_, timestamp, windowID: window_id, - code: code as i32, + code, data1, data2, }; @@ -1512,7 +1482,7 @@ impl Event { let raw_type = unsafe { raw.type_ }; // if event type has not been defined, treat it as a UserEvent - let event_type: EventType = EventType::try_from(raw_type as u32).unwrap_or(EventType::User); + let event_type: EventType = EventType::try_from(raw_type).unwrap_or(EventType::User); unsafe { match event_type { EventType::Quit => { @@ -1583,7 +1553,7 @@ impl Event { Event::KeyDown { timestamp: event.timestamp, window_id: event.windowID, - keycode: Keycode::from_i32(event.keysym.sym as i32), + keycode: Keycode::from_i32(event.keysym.sym), scancode: Scancode::from_i32(event.keysym.scancode as i32), keymod: keyboard::Mod::from_bits_truncate(event.keysym.mod_), repeat: event.repeat != 0, @@ -1595,7 +1565,7 @@ impl Event { Event::KeyUp { timestamp: event.timestamp, window_id: event.windowID, - keycode: Keycode::from_i32(event.keysym.sym as i32), + keycode: Keycode::from_i32(event.keysym.sym), scancode: Scancode::from_i32(event.keysym.scancode as i32), keymod: keyboard::Mod::from_bits_truncate(event.keysym.mod_), repeat: event.repeat != 0, @@ -1646,7 +1616,7 @@ impl Event { Event::MouseMotion { timestamp: event.timestamp, window_id: event.windowID, - which: event.which as u32, + which: event.which, mousestate: mouse::MouseState::from_sdl_state(event.state), x: event.x, y: event.y, @@ -1660,7 +1630,7 @@ impl Event { Event::MouseButtonDown { timestamp: event.timestamp, window_id: event.windowID, - which: event.which as u32, + which: event.which, mouse_btn: mouse::MouseButton::from_ll(event.button), clicks: event.clicks, x: event.x, @@ -1673,7 +1643,7 @@ impl Event { Event::MouseButtonUp { timestamp: event.timestamp, window_id: event.windowID, - which: event.which as u32, + which: event.which, mouse_btn: mouse::MouseButton::from_ll(event.button), clicks: event.clicks, x: event.x, @@ -1686,7 +1656,7 @@ impl Event { Event::MouseWheel { timestamp: event.timestamp, window_id: event.windowID, - which: event.which as u32, + which: event.which, x: event.x, y: event.y, direction: mouse::MouseWheelDirection::from_ll(event.direction), @@ -2040,10 +2010,7 @@ impl Event { } pub fn is_user_event(&self) -> bool { - match *self { - Event::User { .. } => true, - _ => false, - } + matches!(self, Event::User { .. }) } pub fn as_user_event_type(&self) -> Option { @@ -2285,17 +2252,17 @@ impl Event { /// assert!(another_ev.is_window() == false); // Not a window event! /// ``` pub fn is_window(&self) -> bool { - match self { + matches!( + self, Self::Quit { .. } - | Self::AppTerminating { .. } - | Self::AppLowMemory { .. } - | Self::AppWillEnterBackground { .. } - | Self::AppDidEnterBackground { .. } - | Self::AppWillEnterForeground { .. } - | Self::AppDidEnterForeground { .. } - | Self::Window { .. } => true, - _ => false, - } + | Self::AppTerminating { .. } + | Self::AppLowMemory { .. } + | Self::AppWillEnterBackground { .. } + | Self::AppDidEnterBackground { .. } + | Self::AppWillEnterForeground { .. } + | Self::AppDidEnterForeground { .. } + | Self::Window { .. } + ) } /// Returns `true` if this is a keyboard event. @@ -2322,10 +2289,7 @@ impl Event { /// assert!(another_ev.is_keyboard() == false); // Not a keyboard event! /// ``` pub fn is_keyboard(&self) -> bool { - match self { - Self::KeyDown { .. } | Self::KeyUp { .. } => true, - _ => false, - } + matches!(self, Self::KeyDown { .. } | Self::KeyUp { .. }) } /// Returns `true` if this is a text event. @@ -2348,10 +2312,7 @@ impl Event { /// assert!(another_ev.is_text() == false); // Not a text event! /// ``` pub fn is_text(&self) -> bool { - match self { - Self::TextEditing { .. } | Self::TextInput { .. } => true, - _ => false, - } + matches!(self, Self::TextEditing { .. } | Self::TextInput { .. }) } /// Returns `true` if this is a mouse event. @@ -2382,13 +2343,13 @@ impl Event { /// assert!(another_ev.is_mouse() == false); // Not a mouse event! /// ``` pub fn is_mouse(&self) -> bool { - match self { + matches!( + self, Self::MouseMotion { .. } - | Self::MouseButtonDown { .. } - | Self::MouseButtonUp { .. } - | Self::MouseWheel { .. } => true, - _ => false, - } + | Self::MouseButtonDown { .. } + | Self::MouseButtonUp { .. } + | Self::MouseWheel { .. } + ) } /// Returns `true` if this mouse event is coming from touch. @@ -2438,15 +2399,15 @@ impl Event { /// assert!(another_ev.is_controller() == false); // Not a controller event! /// ``` pub fn is_controller(&self) -> bool { - match self { + matches!( + self, Self::ControllerAxisMotion { .. } - | Self::ControllerButtonDown { .. } - | Self::ControllerButtonUp { .. } - | Self::ControllerDeviceAdded { .. } - | Self::ControllerDeviceRemoved { .. } - | Self::ControllerDeviceRemapped { .. } => true, - _ => false, - } + | Self::ControllerButtonDown { .. } + | Self::ControllerButtonUp { .. } + | Self::ControllerDeviceAdded { .. } + | Self::ControllerDeviceRemoved { .. } + | Self::ControllerDeviceRemapped { .. } + ) } /// Returns `true` if this is a joy event. @@ -2469,16 +2430,16 @@ impl Event { /// assert!(another_ev.is_joy() == false); // Not a joy event! /// ``` pub fn is_joy(&self) -> bool { - match self { + matches!( + self, Self::JoyAxisMotion { .. } - | Self::JoyBallMotion { .. } - | Self::JoyHatMotion { .. } - | Self::JoyButtonDown { .. } - | Self::JoyButtonUp { .. } - | Self::JoyDeviceAdded { .. } - | Self::JoyDeviceRemoved { .. } => true, - _ => false, - } + | Self::JoyBallMotion { .. } + | Self::JoyHatMotion { .. } + | Self::JoyButtonDown { .. } + | Self::JoyButtonUp { .. } + | Self::JoyDeviceAdded { .. } + | Self::JoyDeviceRemoved { .. } + ) } /// Returns `true` if this is a finger event. @@ -2506,10 +2467,10 @@ impl Event { /// assert!(another_ev.is_finger() == false); // Not a finger event! /// ``` pub fn is_finger(&self) -> bool { - match self { - Self::FingerDown { .. } | Self::FingerUp { .. } | Self::FingerMotion { .. } => true, - _ => false, - } + matches!( + self, + Self::FingerDown { .. } | Self::FingerUp { .. } | Self::FingerMotion { .. } + ) } /// Returns `true` if this is a dollar event. @@ -2536,10 +2497,7 @@ impl Event { /// assert!(another_ev.is_dollar() == false); // Not a dollar event! /// ``` pub fn is_dollar(&self) -> bool { - match self { - Self::DollarGesture { .. } | Self::DollarRecord { .. } => true, - _ => false, - } + matches!(self, Self::DollarGesture { .. } | Self::DollarRecord { .. }) } /// Returns `true` if this is a drop event. @@ -2561,13 +2519,13 @@ impl Event { /// assert!(another_ev.is_drop() == false); // Not a drop event! /// ``` pub fn is_drop(&self) -> bool { - match self { + matches!( + self, Self::DropFile { .. } - | Self::DropText { .. } - | Self::DropBegin { .. } - | Self::DropComplete { .. } => true, - _ => false, - } + | Self::DropText { .. } + | Self::DropBegin { .. } + | Self::DropComplete { .. } + ) } /// Returns `true` if this is an audio event. @@ -2590,10 +2548,10 @@ impl Event { /// assert!(another_ev.is_audio() == false); // Not an audio event! /// ``` pub fn is_audio(&self) -> bool { - match self { - Self::AudioDeviceAdded { .. } | Self::AudioDeviceRemoved { .. } => true, - _ => false, - } + matches!( + self, + Self::AudioDeviceAdded { .. } | Self::AudioDeviceRemoved { .. } + ) } /// Returns `true` if this is a render event. @@ -2614,10 +2572,10 @@ impl Event { /// assert!(another_ev.is_render() == false); // Not a render event! /// ``` pub fn is_render(&self) -> bool { - match self { - Self::RenderTargetsReset { .. } | Self::RenderDeviceReset { .. } => true, - _ => false, - } + matches!( + self, + Self::RenderTargetsReset { .. } | Self::RenderDeviceReset { .. } + ) } /// Returns `true` if this is a user event. @@ -2643,10 +2601,7 @@ impl Event { /// assert!(another_ev.is_user() == false); // Not a user event! /// ``` pub fn is_user(&self) -> bool { - match self { - Self::User { .. } => true, - _ => false, - } + matches!(self, Self::User { .. }) } /// Returns `true` if this is an unknown event. @@ -2668,10 +2623,7 @@ impl Event { /// assert!(another_ev.is_unknown() == false); // Not an unknown event! /// ``` pub fn is_unknown(&self) -> bool { - match self { - Self::Unknown { .. } => true, - _ => false, - } + matches!(self, Self::Unknown { .. }) } } @@ -2857,6 +2809,175 @@ impl<'a> Iterator for EventWaitTimeoutIterator<'a> { } } +/// A sendible type that can push events to the event queue. +pub struct EventSender { + _priv: (), +} + +impl EventSender { + /// Pushes an event to the event queue. + #[doc(alias = "SDL_PushEvent")] + pub fn push_event(&self, event: Event) -> Result<(), String> { + match event.to_ll() { + Some(mut raw_event) => { + let ok = unsafe { sys::SDL_PushEvent(&mut raw_event) == 1 }; + if ok { + Ok(()) + } else { + Err(get_error()) + } + } + None => Err("Cannot push unsupported event type to the queue".to_owned()), + } + } + + /// Push a custom event + /// + /// If the event type ``T`` was not registered using + /// [EventSubsystem::register_custom_event] + /// (../struct.EventSubsystem.html#method.register_custom_event), + /// this method will panic. + /// + /// # Example: pushing and receiving a custom event + /// ``` + /// struct SomeCustomEvent { + /// a: i32 + /// } + /// + /// let sdl = sdl2::init().unwrap(); + /// let ev = sdl.event().unwrap(); + /// let mut ep = sdl.event_pump().unwrap(); + /// + /// ev.register_custom_event::().unwrap(); + /// + /// let event = SomeCustomEvent { a: 42 }; + /// + /// ev.push_custom_event(event); + /// + /// let received = ep.poll_event().unwrap(); // or within a for event in ep.poll_iter() + /// if received.is_user_event() { + /// let e2 = received.as_user_event_type::().unwrap(); + /// assert_eq!(e2.a, 42); + /// } + /// ``` + pub fn push_custom_event(&self, event: T) -> Result<(), String> { + use std::any::TypeId; + let cet = CUSTOM_EVENT_TYPES.lock().unwrap(); + let type_id = TypeId::of::>(); + + let user_event_id = *match cet.type_id_to_sdl_id.get(&type_id) { + Some(id) => id, + None => { + return Err("Type is not registered as a custom event type!".to_owned()); + } + }; + + let event_box = Box::new(event); + let event = Event::User { + timestamp: 0, + window_id: 0, + type_: user_event_id, + code: 0, + data1: Box::into_raw(event_box) as *mut c_void, + data2: ::std::ptr::null_mut(), + }; + drop(cet); + + self.push_event(event)?; + + Ok(()) + } +} + +/// A callback trait for [`EventSubsystem::add_event_watch`]. +pub trait EventWatchCallback { + fn callback(&mut self, event: Event); +} + +/// An handler for the event watch callback. +/// One must bind this struct in a variable as long as you want to keep the callback active. +/// For further information, see [`EventSubsystem::add_event_watch`]. +pub struct EventWatch<'a, CB: EventWatchCallback + 'a> { + activated: bool, + callback: Box, + _phantom: PhantomData<&'a CB>, +} + +impl<'a, CB: EventWatchCallback + 'a> EventWatch<'a, CB> { + fn add(callback: CB) -> EventWatch<'a, CB> { + let f = Box::new(callback); + let mut watch = EventWatch { + activated: false, + callback: f, + _phantom: PhantomData, + }; + watch.activate(); + watch + } + + /// Activates the event watch. + /// Does nothing if it is already activated. + pub fn activate(&mut self) { + if !self.activated { + self.activated = true; + unsafe { sys::SDL_AddEventWatch(self.filter(), self.callback()) }; + } + } + + /// Deactivates the event watch. + /// Does nothing if it is already activated. + pub fn deactivate(&mut self) { + if self.activated { + self.activated = false; + unsafe { sys::SDL_DelEventWatch(self.filter(), self.callback()) }; + } + } + + /// Returns if the event watch is activated. + pub fn activated(&self) -> bool { + self.activated + } + + /// Set the activation state of the event watch. + pub fn set_activated(&mut self, activate: bool) { + if activate { + self.activate(); + } else { + self.deactivate(); + } + } + + fn filter(&self) -> SDL_EventFilter { + Some(event_callback_marshall:: as _) + } + + fn callback(&mut self) -> *mut c_void { + &mut *self.callback as *mut _ as *mut c_void + } +} + +impl<'a, CB: EventWatchCallback + 'a> Drop for EventWatch<'a, CB> { + fn drop(&mut self) { + self.deactivate(); + } +} + +extern "C" fn event_callback_marshall( + user_data: *mut c_void, + event: *mut sdl2_sys::SDL_Event, +) -> i32 { + let f: &mut CB = unsafe { &mut *(user_data as *mut _) }; + let event = Event::from_ll(unsafe { *event }); + f.callback(event); + 0 +} + +impl EventWatchCallback for F { + fn callback(&mut self, event: Event) { + self(event) + } +} + #[cfg(test)] mod test { use super::super::controller::{Axis, Button}; @@ -3140,172 +3261,3 @@ mod test { } } } - -/// A sendible type that can push events to the event queue. -pub struct EventSender { - _priv: (), -} - -impl EventSender { - /// Pushes an event to the event queue. - #[doc(alias = "SDL_PushEvent")] - pub fn push_event(&self, event: Event) -> Result<(), String> { - match event.to_ll() { - Some(mut raw_event) => { - let ok = unsafe { sys::SDL_PushEvent(&mut raw_event) == 1 }; - if ok { - Ok(()) - } else { - Err(get_error()) - } - } - None => Err("Cannot push unsupported event type to the queue".to_owned()), - } - } - - /// Push a custom event - /// - /// If the event type ``T`` was not registered using - /// [EventSubsystem::register_custom_event] - /// (../struct.EventSubsystem.html#method.register_custom_event), - /// this method will panic. - /// - /// # Example: pushing and receiving a custom event - /// ``` - /// struct SomeCustomEvent { - /// a: i32 - /// } - /// - /// let sdl = sdl2::init().unwrap(); - /// let ev = sdl.event().unwrap(); - /// let mut ep = sdl.event_pump().unwrap(); - /// - /// ev.register_custom_event::().unwrap(); - /// - /// let event = SomeCustomEvent { a: 42 }; - /// - /// ev.push_custom_event(event); - /// - /// let received = ep.poll_event().unwrap(); // or within a for event in ep.poll_iter() - /// if received.is_user_event() { - /// let e2 = received.as_user_event_type::().unwrap(); - /// assert_eq!(e2.a, 42); - /// } - /// ``` - pub fn push_custom_event(&self, event: T) -> Result<(), String> { - use std::any::TypeId; - let cet = CUSTOM_EVENT_TYPES.lock().unwrap(); - let type_id = TypeId::of::>(); - - let user_event_id = *match cet.type_id_to_sdl_id.get(&type_id) { - Some(id) => id, - None => { - return Err("Type is not registered as a custom event type!".to_owned()); - } - }; - - let event_box = Box::new(event); - let event = Event::User { - timestamp: 0, - window_id: 0, - type_: user_event_id, - code: 0, - data1: Box::into_raw(event_box) as *mut c_void, - data2: ::std::ptr::null_mut(), - }; - drop(cet); - - self.push_event(event)?; - - Ok(()) - } -} - -/// A callback trait for [`EventSubsystem::add_event_watch`]. -pub trait EventWatchCallback { - fn callback(&mut self, event: Event) -> (); -} - -/// An handler for the event watch callback. -/// One must bind this struct in a variable as long as you want to keep the callback active. -/// For further information, see [`EventSubsystem::add_event_watch`]. -pub struct EventWatch<'a, CB: EventWatchCallback + 'a> { - activated: bool, - callback: Box, - _phantom: PhantomData<&'a CB>, -} - -impl<'a, CB: EventWatchCallback + 'a> EventWatch<'a, CB> { - fn add(callback: CB) -> EventWatch<'a, CB> { - let f = Box::new(callback); - let mut watch = EventWatch { - activated: false, - callback: f, - _phantom: PhantomData, - }; - watch.activate(); - watch - } - - /// Activates the event watch. - /// Does nothing if it is already activated. - pub fn activate(&mut self) { - if !self.activated { - self.activated = true; - unsafe { sys::SDL_AddEventWatch(self.filter(), self.callback()) }; - } - } - - /// Deactivates the event watch. - /// Does nothing if it is already activated. - pub fn deactivate(&mut self) { - if self.activated { - self.activated = false; - unsafe { sys::SDL_DelEventWatch(self.filter(), self.callback()) }; - } - } - - /// Returns if the event watch is activated. - pub fn activated(&self) -> bool { - self.activated - } - - /// Set the activation state of the event watch. - pub fn set_activated(&mut self, activate: bool) { - if activate { - self.activate(); - } else { - self.deactivate(); - } - } - - fn filter(&self) -> SDL_EventFilter { - Some(event_callback_marshall:: as _) - } - - fn callback(&mut self) -> *mut c_void { - &mut *self.callback as *mut _ as *mut c_void - } -} - -impl<'a, CB: EventWatchCallback + 'a> Drop for EventWatch<'a, CB> { - fn drop(&mut self) { - self.deactivate(); - } -} - -extern "C" fn event_callback_marshall( - user_data: *mut c_void, - event: *mut sdl2_sys::SDL_Event, -) -> i32 { - let f: &mut CB = unsafe { &mut *(user_data as *mut _) }; - let event = Event::from_ll(unsafe { *event }); - f.callback(event); - 0 -} - -impl ()> EventWatchCallback for F { - fn callback(&mut self, event: Event) -> () { - self(event) - } -} diff --git a/src/sdl2/filesystem.rs b/src/sdl2/filesystem.rs index 598c2aa5ce6..27d46c58983 100644 --- a/src/sdl2/filesystem.rs +++ b/src/sdl2/filesystem.rs @@ -43,13 +43,11 @@ impl fmt::Display for PrefPathError { } impl error::Error for PrefPathError { - fn description(&self) -> &str { - use self::PrefPathError::*; - - match *self { - InvalidOrganizationName(_) => "invalid organization name", - InvalidApplicationName(_) => "invalid application name", - SdlError(ref e) => e, + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + match self { + Self::InvalidOrganizationName(err) => Some(err), + Self::InvalidApplicationName(err) => Some(err), + Self::SdlError(_) => None, } } } diff --git a/src/sdl2/gfx/framerate.rs b/src/sdl2/gfx/framerate.rs index b7d7d0fee21..90665864d1a 100644 --- a/src/sdl2/gfx/framerate.rs +++ b/src/sdl2/gfx/framerate.rs @@ -18,13 +18,13 @@ impl FPSManager { let size = mem::size_of::() as size_t; let raw = libc::malloc(size) as *mut gfx::framerate::FPSmanager; gfx::framerate::SDL_initFramerate(raw); - FPSManager { raw: raw } + FPSManager { raw } } } /// Set the framerate in Hz. pub fn set_framerate(&mut self, rate: u32) -> Result<(), String> { - let ret = unsafe { gfx::framerate::SDL_setFramerate(self.raw, rate as u32) }; + let ret = unsafe { gfx::framerate::SDL_setFramerate(self.raw, rate) }; match ret { 0 => Ok(()), _ => Err(get_error()), diff --git a/src/sdl2/gfx/primitives.rs b/src/sdl2/gfx/primitives.rs index b3e634a64cb..7e79a286587 100644 --- a/src/sdl2/gfx/primitives.rs +++ b/src/sdl2/gfx/primitives.rs @@ -626,5 +626,5 @@ where /// Sets current global font character rotation steps. pub fn set_font_rotation(rotation: u32) { - unsafe { primitives::gfxPrimitivesSetFontRotation(rotation as u32) } + unsafe { primitives::gfxPrimitivesSetFontRotation(rotation) } } diff --git a/src/sdl2/hint.rs b/src/sdl2/hint.rs index 58f7173b6de..bc9958e2910 100644 --- a/src/sdl2/hint.rs +++ b/src/sdl2/hint.rs @@ -68,13 +68,10 @@ pub fn set_video_minimize_on_focus_loss_with_priority(value: bool, priority: &Hi /// assert_eq!(sdl2::hint::get_video_minimize_on_focus_loss(), false); /// ``` pub fn get_video_minimize_on_focus_loss() -> bool { - match get(VIDEO_MINIMIZE_ON_FOCUS_LOSS) { - Some(value) => match &*value { - "1" => true, - _ => false, - }, - _ => true, - } + matches!( + get(VIDEO_MINIMIZE_ON_FOCUS_LOSS).as_deref(), + Some("1") | None + ) } #[doc(alias = "SDL_SetHint")] diff --git a/src/sdl2/joystick.rs b/src/sdl2/joystick.rs index 5fe317ae5e9..82e20b449ac 100644 --- a/src/sdl2/joystick.rs +++ b/src/sdl2/joystick.rs @@ -87,7 +87,7 @@ impl JoystickSubsystem { /// Return `true` if joystick events are processed. #[doc(alias = "SDL_JoystickEventState")] pub fn event_state(&self) -> bool { - unsafe { sys::SDL_JoystickEventState(sys::SDL_QUERY as i32) == sys::SDL_ENABLE as i32 } + unsafe { sys::SDL_JoystickEventState(sys::SDL_QUERY) == sys::SDL_ENABLE as i32 } } /// Force joystick update when not using the event loop diff --git a/src/sdl2/keyboard/keycode.rs b/src/sdl2/keyboard/keycode.rs index 1f6fec7b1cc..324fda01394 100644 --- a/src/sdl2/keyboard/keycode.rs +++ b/src/sdl2/keyboard/keycode.rs @@ -511,7 +511,7 @@ impl Keycode { // Knowing this, we must always return a new string. unsafe { let buf = sys::SDL_GetKeyName(self.into()); - CStr::from_ptr(buf as *const _).to_str().unwrap().to_owned() + CStr::from_ptr(buf).to_str().unwrap().to_owned() } } } diff --git a/src/sdl2/keyboard/mod.rs b/src/sdl2/keyboard/mod.rs index 5775217c3c5..b276373daa6 100644 --- a/src/sdl2/keyboard/mod.rs +++ b/src/sdl2/keyboard/mod.rs @@ -1,8 +1,12 @@ +// 0 should not be used in bitflags, but here it is. Removing it will break existing code. +#![allow(clippy::bad_bit_mask)] + use crate::rect::Rect; use crate::video::Window; use crate::EventPump; use std::fmt; +use std::iter::FilterMap; use std::mem::transmute; use crate::sys; @@ -99,9 +103,7 @@ impl<'a> KeyboardState<'a> { /// } /// ``` pub fn pressed_scancodes(&self) -> PressedScancodeIterator { - PressedScancodeIterator { - iter: self.scancodes(), - } + self.scancodes().into_pressed_scancode_iter() } } @@ -131,24 +133,15 @@ impl<'a> Iterator for ScancodeIterator<'a> { } } -pub struct PressedScancodeIterator<'a> { - iter: ScancodeIterator<'a>, -} - -impl<'a> Iterator for PressedScancodeIterator<'a> { - type Item = Scancode; - - fn next(&mut self) -> Option { - while let Some((scancode, pressed)) = self.iter.next() { - if pressed { - return Some(scancode); - } - } - - None +impl<'a> ScancodeIterator<'a> { + fn into_pressed_scancode_iter(self) -> PressedScancodeIterator<'a> { + self.filter_map(|(scancode, pressed)| pressed.then_some(scancode)) } } +pub type PressedScancodeIterator<'a> = + FilterMap, fn((Scancode, bool)) -> Option>; + impl crate::Sdl { #[inline] pub fn keyboard(&self) -> KeyboardUtil { diff --git a/src/sdl2/lib.rs b/src/sdl2/lib.rs index 800ccbd378c..20ef28b11fe 100644 --- a/src/sdl2/lib.rs +++ b/src/sdl2/lib.rs @@ -47,7 +47,6 @@ #![crate_name = "sdl2"] #![crate_type = "lib"] -#![allow(clippy::cast_lossless, clippy::transmute_ptr_to_ref)] pub extern crate libc; diff --git a/src/sdl2/log.rs b/src/sdl2/log.rs index 6e62d8de03a..a48e07bcfc0 100644 --- a/src/sdl2/log.rs +++ b/src/sdl2/log.rs @@ -83,7 +83,7 @@ unsafe extern "C" fn rust_sdl2_log_fn( let category = Category::from_ll(category as u32); let priority = Priority::from_ll(priority); let message = CStr::from_ptr(message).to_string_lossy(); - custom_log_fn(priority, category, &*message); + custom_log_fn(priority, category, &message); } #[doc(alias = "SDL_LogSetOutputFunction")] diff --git a/src/sdl2/macros.rs b/src/sdl2/macros.rs index 4041aaae68f..673ca3c1169 100644 --- a/src/sdl2/macros.rs +++ b/src/sdl2/macros.rs @@ -18,7 +18,7 @@ macro_rules! impl_raw_constructor( impl $t { #[inline] pub const unsafe fn from_ll($($r:$rt),+) -> $t { - $te { $($r: $r),+ } + $te { $($r),+ } } } )+ diff --git a/src/sdl2/messagebox.rs b/src/sdl2/messagebox.rs index 753cd1985ed..8eff0e20c7f 100644 --- a/src/sdl2/messagebox.rs +++ b/src/sdl2/messagebox.rs @@ -1,3 +1,6 @@ +// 0 should not be used in bitflags, but here it is. Removing it will break existing code. +#![allow(clippy::bad_bit_mask)] + use std::error; use std::ffi::{CString, NulError}; use std::fmt; @@ -39,11 +42,9 @@ pub struct MessageBoxColorScheme { pub button_selected: (u8, u8, u8), } -impl Into for MessageBoxColorScheme { - fn into(self) -> sys::SDL_MessageBoxColorScheme { - sys::SDL_MessageBoxColorScheme { - colors: self.into(), - } +impl From for sys::SDL_MessageBoxColorScheme { + fn from(val: MessageBoxColorScheme) -> Self { + sys::SDL_MessageBoxColorScheme { colors: val.into() } } } @@ -88,17 +89,17 @@ impl From for [sys::SDL_MessageBoxColor; 5] { } } -impl Into for [sys::SDL_MessageBoxColor; 5] { - fn into(self) -> MessageBoxColorScheme { +impl From<[sys::SDL_MessageBoxColor; 5]> for MessageBoxColorScheme { + fn from(val: [sys::SDL_MessageBoxColor; 5]) -> Self { fn from_message_box_color(prim_color: sys::SDL_MessageBoxColor) -> (u8, u8, u8) { (prim_color.r, prim_color.g, prim_color.b) } MessageBoxColorScheme { - background: from_message_box_color(self[0]), - text: from_message_box_color(self[1]), - button_border: from_message_box_color(self[2]), - button_background: from_message_box_color(self[3]), - button_selected: from_message_box_color(self[4]), + background: from_message_box_color(val[0]), + text: from_message_box_color(val[1]), + button_border: from_message_box_color(val[2]), + button_background: from_message_box_color(val[3]), + button_selected: from_message_box_color(val[4]), } } } @@ -127,14 +128,12 @@ impl fmt::Display for ShowMessageError { } impl error::Error for ShowMessageError { - fn description(&self) -> &str { - use self::ShowMessageError::*; - - match *self { - InvalidTitle(_) => "invalid title", - InvalidMessage(_) => "invalid message", - InvalidButton(..) => "invalid button", - SdlError(ref e) => e, + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + match self { + Self::InvalidTitle(err) => Some(err), + Self::InvalidMessage(err) => Some(err), + Self::InvalidButton(err, _) => Some(err), + Self::SdlError(_) => None, } } } diff --git a/src/sdl2/mixer/mod.rs b/src/sdl2/mixer/mod.rs index d3f8a443004..7a74f76dad7 100644 --- a/src/sdl2/mixer/mod.rs +++ b/src/sdl2/mixer/mod.rs @@ -156,7 +156,7 @@ pub fn init(flags: InitFlag) -> Result { } else { // Flags not matching won't always set the error message text // according to sdl docs - if get_error() == "" { + if get_error().is_empty() { let un_init_flags = return_flags ^ flags; let error_str = &("Could not init: ".to_string() + &un_init_flags.to_string()); let _ = ::set_error(error_str); @@ -274,10 +274,7 @@ impl Chunk { if raw.is_null() { Err(get_error()) } else { - Ok(Chunk { - raw: raw, - owned: true, - }) + Ok(Chunk { raw, owned: true }) } } @@ -307,10 +304,7 @@ impl<'a> LoaderRWops<'a> for RWops<'a> { if raw.is_null() { Err(get_error()) } else { - Ok(Chunk { - raw: raw, - owned: true, - }) + Ok(Chunk { raw, owned: true }) } } @@ -321,7 +315,7 @@ impl<'a> LoaderRWops<'a> for RWops<'a> { Err(get_error()) } else { Ok(Music { - raw: raw, + raw, owned: true, _marker: PhantomData, }) @@ -355,7 +349,7 @@ extern "C" fn c_channel_finished_callback(ch: c_int) { unsafe { match CHANNEL_FINISHED_CALLBACK { None => (), - Some(ref cb) => cb(Channel(ch as i32)), + Some(ref cb) => cb(Channel(ch)), } } } @@ -514,10 +508,7 @@ impl Channel { if raw.is_null() { None } else { - Some(Chunk { - raw: raw, - owned: false, - }) + Some(Chunk { raw, owned: false }) } } @@ -791,7 +782,7 @@ impl<'a> Music<'a> { Err(get_error()) } else { Ok(Music { - raw: raw, + raw, owned: true, _marker: PhantomData, }) @@ -813,7 +804,7 @@ impl<'a> Music<'a> { Err(get_error()) } else { Ok(Music { - raw: raw, + raw, owned: true, _marker: PhantomData, }) diff --git a/src/sdl2/mouse/mod.rs b/src/sdl2/mouse/mod.rs index 0249b2309fe..7328fbf0ca7 100644 --- a/src/sdl2/mouse/mod.rs +++ b/src/sdl2/mouse/mod.rs @@ -2,6 +2,7 @@ use crate::get_error; use crate::surface::SurfaceRef; use crate::video; use crate::EventPump; +use std::iter::FilterMap; use std::mem::transmute; use crate::sys; @@ -50,14 +51,8 @@ impl Cursor { hot_y: i32, ) -> Result { unsafe { - let raw = sys::SDL_CreateCursor( - data.as_ptr(), - mask.as_ptr(), - width as i32, - height as i32, - hot_x as i32, - hot_y as i32, - ); + let raw = + sys::SDL_CreateCursor(data.as_ptr(), mask.as_ptr(), width, height, hot_x, hot_y); if raw.is_null() { Err(get_error()) @@ -188,11 +183,7 @@ impl MouseState { let mut y = 0; let mouse_state: u32 = unsafe { sys::SDL_GetMouseState(&mut x, &mut y) }; - MouseState { - mouse_state, - x: x as i32, - y: y as i32, - } + MouseState { mouse_state, x, y } } pub fn from_sdl_state(state: u32) -> MouseState { @@ -312,9 +303,7 @@ impl MouseState { /// } /// ``` pub fn pressed_mouse_buttons(&self) -> PressedMouseButtonIterator { - PressedMouseButtonIterator { - iter: self.mouse_buttons(), - } + self.mouse_buttons().into_pressed_buttons_iter() } } @@ -339,23 +328,15 @@ impl<'a> Iterator for MouseButtonIterator<'a> { } } -pub struct PressedMouseButtonIterator<'a> { - iter: MouseButtonIterator<'a>, -} - -impl<'a> Iterator for PressedMouseButtonIterator<'a> { - type Item = MouseButton; - - fn next(&mut self) -> Option { - while let Some((mouse_button, pressed)) = self.iter.next() { - if pressed { - return Some(mouse_button); - } - } - None +impl<'a> MouseButtonIterator<'a> { + fn into_pressed_buttons_iter(self) -> PressedMouseButtonIterator<'a> { + self.filter_map(|(mouse_button, pressed)| pressed.then_some(mouse_button)) } } +pub type PressedMouseButtonIterator<'a> = + FilterMap, fn((MouseButton, bool)) -> Option>; + impl crate::Sdl { #[inline] pub fn mouse(&self) -> MouseUtil { diff --git a/src/sdl2/mouse/relative.rs b/src/sdl2/mouse/relative.rs index c16c49a6a5e..6eba8d81e6b 100644 --- a/src/sdl2/mouse/relative.rs +++ b/src/sdl2/mouse/relative.rs @@ -21,11 +21,7 @@ impl RelativeMouseState { sys::SDL_GetRelativeMouseState(&mut x, &mut y) }; - RelativeMouseState { - mouse_state, - x: x as i32, - y: y as i32, - } + RelativeMouseState { mouse_state, x, y } } pub fn from_sdl_state(state: u32) -> RelativeMouseState { @@ -145,8 +141,6 @@ impl RelativeMouseState { /// } /// ``` pub fn pressed_mouse_buttons(&self) -> PressedMouseButtonIterator { - PressedMouseButtonIterator { - iter: self.mouse_buttons(), - } + self.mouse_buttons().into_pressed_buttons_iter() } } diff --git a/src/sdl2/pixels.rs b/src/sdl2/pixels.rs index ee08cf20118..eb8bf8d0781 100644 --- a/src/sdl2/pixels.rs +++ b/src/sdl2/pixels.rs @@ -21,7 +21,7 @@ impl Palette { // This is kind of a hack. We have to cast twice because // ncolors is a c_int, and validate_int only takes a u32. // FIXME: Modify validate_int to make this unnecessary - let u32_max = u32::max_value() as usize; + let u32_max = u32::MAX as usize; if capacity > u32_max { capacity = u32_max; } @@ -160,9 +160,9 @@ impl Color { pub const CYAN: Color = Color::RGBA(0, 255, 255, 255); } -impl Into for Color { - fn into(self) -> sys::SDL_Color { - self.raw() +impl From for sys::SDL_Color { + fn from(val: Color) -> Self { + val.raw() } } @@ -416,11 +416,22 @@ impl PixelFormatEnum { pub fn supports_alpha(self) -> bool { use crate::pixels::PixelFormatEnum::*; - match self { - ARGB4444 | ARGB1555 | ARGB8888 | ARGB2101010 | ABGR4444 | ABGR1555 | ABGR8888 - | BGRA4444 | BGRA5551 | BGRA8888 | RGBA4444 | RGBA5551 | RGBA8888 => true, - _ => false, - } + matches!( + self, + ARGB4444 + | ARGB1555 + | ARGB8888 + | ARGB2101010 + | ABGR4444 + | ABGR1555 + | ABGR8888 + | BGRA4444 + | BGRA5551 + | BGRA8888 + | RGBA4444 + | RGBA5551 + | RGBA8888 + ) } } @@ -428,7 +439,7 @@ impl From for PixelFormatEnum { fn from(pf: PixelFormat) -> PixelFormatEnum { unsafe { let sdl_pf = *pf.raw; - match PixelFormatEnum::try_from(sdl_pf.format as u32) { + match PixelFormatEnum::try_from(sdl_pf.format) { Ok(pfe) => pfe, Err(()) => panic!("Unknown pixel format: {:?}", sdl_pf.format), } diff --git a/src/sdl2/rect.rs b/src/sdl2/rect.rs index 87428654fc3..a938e2955e4 100644 --- a/src/sdl2/rect.rs +++ b/src/sdl2/rect.rs @@ -15,7 +15,7 @@ use std::ptr; /// This value is smaller than strictly needed, but is useful in ensuring that /// rect sizes will never have to be truncated when clamping. pub fn max_int_value() -> u32 { - i32::max_value() as u32 / 2 + i32::MAX as u32 / 2 } /// The minimal integer value that can be used for rectangle positions @@ -24,7 +24,7 @@ pub fn max_int_value() -> u32 { /// This value is needed, because otherwise the width of a rectangle created /// from a point would be able to exceed the maximum width. pub fn min_int_value() -> i32 { - i32::min_value() / 2 + i32::MIN / 2 } fn clamp_size(val: u32) -> u32 { @@ -85,11 +85,12 @@ pub struct Rect { impl ::std::fmt::Debug for Rect { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { - return write!( - fmt, - "Rect {{ x: {}, y: {}, w: {}, h: {} }}", - self.raw.x, self.raw.y, self.raw.w, self.raw.h - ); + fmt.debug_struct("Rect") + .field("x", &self.raw.x) + .field("y", &self.raw.y) + .field("w", &self.raw.w) + .field("h", &self.raw.h) + .finish() } } @@ -117,7 +118,7 @@ impl Rect { /// Creates a new rectangle from the given values. /// /// The width and height are clamped to ensure that the right and bottom - /// sides of the rectangle does not exceed i32::max_value() (the value + /// sides of the rectangle does not exceed i32::MAX (the value /// 2147483647, the maximal positive size of an i32). This means that the /// rect size will behave oddly if you move it very far to the right or /// downwards on the screen. @@ -137,7 +138,7 @@ impl Rect { /// Creates a new rectangle centered on the given position. /// /// The width and height are clamped to ensure that the right and bottom - /// sides of the rectangle does not exceed i32::max_value() (the value + /// sides of the rectangle does not exceed i32::MAX (the value /// 2147483647, the maximal positive size of an i32). This means that the /// rect size will behave oddly if you move it very far to the right or /// downwards on the screen. @@ -187,19 +188,19 @@ impl Rect { } /// Sets the horizontal position of this rectangle to the given value, - /// clamped to be less than or equal to i32::max_value() / 2. + /// clamped to be less than or equal to i32::MAX / 2. pub fn set_x(&mut self, x: i32) { self.raw.x = clamp_position(x); } /// Sets the vertical position of this rectangle to the given value, - /// clamped to be less than or equal to i32::max_value() / 2. + /// clamped to be less than or equal to i32::MAX / 2. pub fn set_y(&mut self, y: i32) { self.raw.y = clamp_position(y); } /// Sets the width of this rectangle to the given value, - /// clamped to be less than or equal to i32::max_value() / 2. + /// clamped to be less than or equal to i32::MAX / 2. /// /// `Rect`s must always be non-empty, so a `width` argument of 0 will be /// replaced with 1. @@ -208,7 +209,7 @@ impl Rect { } /// Sets the height of this rectangle to the given value, - /// clamped to be less than or equal to i32::max_value() / 2. + /// clamped to be less than or equal to i32::MAX / 2. /// /// `Rect`s must always be non-empty, so a `height` argument of 0 will be /// replaced with 1. @@ -359,13 +360,13 @@ impl Rect { } /// Sets the position of the right side of this rectangle to the given - /// value, clamped to be less than or equal to i32::max_value() / 2. + /// value, clamped to be less than or equal to i32::MAX / 2. pub fn set_right(&mut self, right: i32) { self.raw.x = clamp_position(clamp_position(right) - self.raw.w); } /// Sets the position of the bottom side of this rectangle to the given - /// value, clamped to be less than or equal to i32::max_value() / 2. + /// value, clamped to be less than or equal to i32::MAX / 2. pub fn set_bottom(&mut self, bottom: i32) { self.raw.y = clamp_position(clamp_position(bottom) - self.raw.h); } @@ -401,7 +402,7 @@ impl Rect { if x >= 0 { self.raw.x = max_int_value() as i32; } else { - self.raw.x = i32::min_value(); + self.raw.x = i32::MIN; } } } @@ -411,7 +412,7 @@ impl Rect { if y >= 0 { self.raw.y = max_int_value() as i32; } else { - self.raw.y = i32::min_value(); + self.raw.y = i32::MIN; } } } @@ -509,10 +510,7 @@ impl Rect { /// If a clipping rectangle is given, only points that are within it will be /// considered. #[doc(alias = "SDL_EnclosePoints")] - pub fn from_enclose_points>>( - points: &[Point], - clipping_rect: R, - ) -> Option + pub fn from_enclose_points(points: &[Point], clipping_rect: R) -> Option where R: Into>, { @@ -685,15 +683,15 @@ impl DerefMut for Rect { } } -impl Into for Rect { - fn into(self) -> sys::SDL_Rect { - self.raw +impl From for sys::SDL_Rect { + fn from(val: Rect) -> Self { + val.raw } } -impl Into<(i32, i32, u32, u32)> for Rect { - fn into(self) -> (i32, i32, u32, u32) { - (self.raw.x, self.raw.y, self.raw.w as u32, self.raw.h as u32) +impl From for (i32, i32, u32, u32) { + fn from(val: Rect) -> Self { + (val.raw.x, val.raw.y, val.raw.w as u32, val.raw.h as u32) } } @@ -749,7 +747,10 @@ pub struct Point { impl ::std::fmt::Debug for Point { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { - return write!(fmt, "Point {{ x: {}, y: {} }}", self.raw.x, self.raw.y); + fmt.debug_struct("Point") + .field("x", &self.raw.x) + .field("y", &self.raw.y) + .finish() } } @@ -821,15 +822,15 @@ impl From<(i32, i32)> for Point { } } -impl Into for Point { - fn into(self) -> sys::SDL_Point { - self.raw +impl From for sys::SDL_Point { + fn from(val: Point) -> Self { + val.raw } } -impl Into<(i32, i32)> for Point { - fn into(self) -> (i32, i32) { - (self.x(), self.y()) +impl From for (i32, i32) { + fn from(val: Point) -> Self { + (val.x(), val.y()) } } @@ -1856,8 +1857,8 @@ mod test { )), Rect::from_enclose_points( &[ - Point::new(i32::min_value(), i32::min_value()), - Point::new(i32::max_value(), i32::max_value()) + Point::new(i32::MIN, i32::MIN), + Point::new(i32::MAX, i32::MAX) ], None ) @@ -1907,7 +1908,7 @@ mod test { fn clamp_position_min() { assert_eq!( tuple(min_int_value(), min_int_value(), 1, 1), - Rect::new(i32::min_value(), i32::min_value(), 1, 1).into() + Rect::new(i32::MIN, i32::MIN, 1, 1).into() ); } @@ -1923,7 +1924,7 @@ mod test { fn clamp_i32_max() { assert_eq!( tuple(0, 0, max_int_value(), max_int_value()), - Rect::new(0, 0, i32::max_value() as u32, i32::max_value() as u32).into() + Rect::new(0, 0, i32::MAX as u32, i32::MAX as u32).into() ) } diff --git a/src/sdl2/render.rs b/src/sdl2/render.rs index ab54da0e205..e18e9a06b65 100644 --- a/src/sdl2/render.rs +++ b/src/sdl2/render.rs @@ -70,17 +70,11 @@ pub enum TargetRenderError { impl fmt::Display for SdlError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let &SdlError(ref e) = self; - write!(f, "SDL error: {}", e) + write!(f, "SDL error: {}", self.0) } } -impl Error for SdlError { - fn description(&self) -> &str { - let &SdlError(ref e) = self; - e - } -} +impl Error for SdlError {} impl fmt::Display for TargetRenderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -93,11 +87,10 @@ impl fmt::Display for TargetRenderError { } impl Error for TargetRenderError { - fn description(&self) -> &str { - use self::TargetRenderError::*; - match *self { - SdlError(self::SdlError(ref e)) => e.as_str(), - NotSupported => "The renderer does not support the use of render targets", + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::SdlError(err) => Some(err), + Self::NotSupported => None, } } } @@ -187,9 +180,7 @@ impl RendererInfo { let texture_formats: Vec = info.texture_formats [0..(info.num_texture_formats as usize)] .iter() - .map(|&format| { - PixelFormatEnum::try_from(format as u32).unwrap_or(PixelFormatEnum::Unknown) - }) + .map(|&format| PixelFormatEnum::try_from(format).unwrap_or(PixelFormatEnum::Unknown)) .collect(); // The driver name is always a static string, compiled into SDL2. @@ -613,7 +604,7 @@ impl Canvas { { if self.render_target_supported() { let target = unsafe { self.get_raw_target() }; - for &(ref texture, ref user_context) in textures { + for (texture, user_context) in textures { unsafe { self.set_raw_target(texture.raw) }.map_err(TargetRenderError::SdlError)?; f(self, user_context); } @@ -780,18 +771,7 @@ impl fmt::Display for TextureValueError { } } -impl Error for TextureValueError { - fn description(&self) -> &str { - use self::TextureValueError::*; - - match *self { - WidthOverflows(_) => "texture width overflow", - HeightOverflows(_) => "texture height overflow", - WidthMustBeMultipleOfTwoForFormat(..) => "texture width must be multiple of two", - SdlError(ref e) => e, - } - } -} +impl Error for TextureValueError {} #[doc(alias = "SDL_CreateTexture")] fn ll_create_texture( @@ -2005,21 +1985,7 @@ impl fmt::Display for UpdateTextureError { } } -impl Error for UpdateTextureError { - fn description(&self) -> &str { - use self::UpdateTextureError::*; - - match *self { - PitchOverflows(_) => "pitch overflow", - PitchMustBeMultipleOfTwoForFormat(..) => "pitch must be multiple of two", - XMustBeMultipleOfTwoForFormat(..) => "x must be multiple of two", - YMustBeMultipleOfTwoForFormat(..) => "y must be multiple of two", - WidthMustBeMultipleOfTwoForFormat(..) => "width must be multiple of two", - HeightMustBeMultipleOfTwoForFormat(..) => "height must be multiple of two", - SdlError(ref e) => e, - } - } -} +impl Error for UpdateTextureError {} #[derive(Debug, Clone)] pub enum UpdateTextureYUVError { @@ -2079,22 +2045,7 @@ impl fmt::Display for UpdateTextureYUVError { } } -impl Error for UpdateTextureYUVError { - fn description(&self) -> &str { - use self::UpdateTextureYUVError::*; - - match *self { - PitchOverflows { .. } => "pitch overflow", - InvalidPlaneLength { .. } => "invalid plane length", - XMustBeMultipleOfTwoForFormat(_) => "x must be multiple of two", - YMustBeMultipleOfTwoForFormat(_) => "y must be multiple of two", - WidthMustBeMultipleOfTwoForFormat(_) => "width must be multiple of two", - HeightMustBeMultipleOfTwoForFormat(_) => "height must be multiple of two", - RectNotInsideTexture(_) => "rect must be inside texture", - SdlError(ref e) => e, - } - } -} +impl Error for UpdateTextureYUVError {} struct InternalTexture { raw: *mut sys::SDL_Texture, @@ -2116,7 +2067,7 @@ impl InternalTexture { panic!("{}", get_error()) } else { TextureQuery { - format: PixelFormatEnum::try_from(format as u32).unwrap(), + format: PixelFormatEnum::try_from(format).unwrap(), access: TextureAccess::try_from(access as u32).unwrap(), width: width as u32, height: height as u32, diff --git a/src/sdl2/sdl.rs b/src/sdl2/sdl.rs index 33726ff72bd..663c2a7c4ab 100644 --- a/src/sdl2/sdl.rs +++ b/src/sdl2/sdl.rs @@ -33,19 +33,7 @@ impl fmt::Display for Error { } } -impl error::Error for Error { - fn description(&self) -> &str { - use self::Error::*; - - match *self { - NoMemError => "out of memory", - ReadError => "error reading from datastream", - WriteError => "error writing to datastream", - SeekError => "error seeking in datastream", - UnsupportedError => "unknown SDL error", - } - } -} +impl error::Error for Error {} /// True if the main thread has been declared. The main thread is declared when /// SDL is first initialized. @@ -56,7 +44,7 @@ static SDL_COUNT: AtomicU32 = AtomicU32::new(0); thread_local! { /// True if the current thread is the main thread. - static IS_MAIN_THREAD: Cell = Cell::new(false); + static IS_MAIN_THREAD: Cell = const { Cell::new(false) }; } /// The SDL context type. Initialize with `sdl2::init()`. diff --git a/src/sdl2/surface.rs b/src/sdl2/surface.rs index 9fe7d022e41..efe167ee12e 100644 --- a/src/sdl2/surface.rs +++ b/src/sdl2/surface.rs @@ -74,28 +74,28 @@ impl<'a> Deref for Surface<'a> { #[inline] fn deref(&self) -> &SurfaceRef { - unsafe { mem::transmute(self.context.raw) } + self.as_ref() } } impl<'a> DerefMut for Surface<'a> { #[inline] fn deref_mut(&mut self) -> &mut SurfaceRef { - unsafe { mem::transmute(self.context.raw) } + self.as_mut() } } impl<'a> AsRef for Surface<'a> { #[inline] fn as_ref(&self) -> &SurfaceRef { - unsafe { mem::transmute(self.context.raw) } + unsafe { &*(self.context.raw as *const SurfaceRef) } } } impl<'a> AsMut for Surface<'a> { #[inline] fn as_mut(&mut self) -> &mut SurfaceRef { - unsafe { mem::transmute(self.context.raw) } + unsafe { &mut *(self.context.raw as *mut SurfaceRef) } } } @@ -565,9 +565,7 @@ impl SurfaceRef { #[allow(clippy::clone_on_copy)] pub fn fill_rects(&mut self, rects: &[Rect], color: pixels::Color) -> Result<(), String> { for rect in rects.iter() { - if let Err(e) = self.fill_rect(rect.clone(), color) { - return Err(e); - } + self.fill_rect(rect.clone(), color)? } Ok(()) diff --git a/src/sdl2/timer.rs b/src/sdl2/timer.rs index 678f36518cf..2281dba6e09 100644 --- a/src/sdl2/timer.rs +++ b/src/sdl2/timer.rs @@ -189,7 +189,7 @@ mod test { ::std::thread::sleep(Duration::from_millis(50)); let flag = local_flag.lock().unwrap(); - assert_eq!(*flag, true); + assert!(*flag); } fn test_timer_can_be_recreated() { diff --git a/src/sdl2/ttf/context.rs b/src/sdl2/ttf/context.rs index c3e7a0b731d..8d967606ea4 100644 --- a/src/sdl2/ttf/context.rs +++ b/src/sdl2/ttf/context.rs @@ -27,22 +27,22 @@ impl Drop for Sdl2TtfContext { impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. - pub fn load_font<'ttf, P: AsRef>( - &'ttf self, + pub fn load_font>( + &self, path: P, point_size: u16, - ) -> Result, String> { + ) -> Result, String> { internal_load_font(path, point_size) } /// Loads the font at the given index of the file, with the given /// size in points. - pub fn load_font_at_index<'ttf, P: AsRef>( - &'ttf self, + pub fn load_font_at_index>( + &self, path: P, index: u32, point_size: u16, - ) -> Result, String> { + ) -> Result, String> { internal_load_font_at_index(path, index, point_size) } @@ -94,14 +94,7 @@ pub enum InitError { } impl error::Error for InitError { - fn description(&self) -> &str { - match *self { - InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", - InitError::InitializationError(ref error) => error.description(), - } - } - - fn cause(&self) -> Option<&dyn error::Error> { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { InitError::AlreadyInitializedError => None, InitError::InitializationError(ref error) => Some(error), @@ -110,8 +103,13 @@ impl error::Error for InitError { } impl fmt::Display for InitError { - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { - formatter.write_str("SDL2_TTF has already been initialized") + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AlreadyInitializedError => { + write!(f, "SDL2_TTF has already been initialized") + } + Self::InitializationError(error) => write!(f, "SDL2_TTF initialization error: {error}"), + } } } diff --git a/src/sdl2/ttf/font.rs b/src/sdl2/ttf/font.rs index 9f000752ba8..3a2fa2c34aa 100644 --- a/src/sdl2/ttf/font.rs +++ b/src/sdl2/ttf/font.rs @@ -1,8 +1,10 @@ +// 0 should not be used in bitflags, but here it is. Removing it will break existing code. +#![allow(clippy::bad_bit_mask)] + use get_error; use pixels::Color; use rwops::RWops; use std::error; -use std::error::Error; use std::ffi::NulError; use std::ffi::{CStr, CString}; use std::fmt; @@ -58,14 +60,7 @@ pub enum FontError { } impl error::Error for FontError { - fn description(&self) -> &str { - match *self { - FontError::InvalidLatin1Text(ref error) => error.description(), - FontError::SdlError(ref message) => message, - } - } - - fn cause(&self) -> Option<&dyn error::Error> { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { FontError::InvalidLatin1Text(ref error) => Some(error), FontError::SdlError(_) => None, @@ -77,7 +72,7 @@ impl fmt::Display for FontError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { FontError::InvalidLatin1Text(ref err) => { - write!(f, "Invalid Latin-1 bytes: {}", err.description()) + write!(f, "Invalid Latin-1 bytes: {}", err) } FontError::SdlError(ref msg) => { write!(f, "SDL2 error: {}", msg) @@ -90,18 +85,19 @@ impl fmt::Display for FontError { enum RenderableText<'a> { Utf8(&'a str), Latin1(&'a [u8]), - Char(String), + Char(char), } impl<'a> RenderableText<'a> { /// Converts the given text to a c-style string if possible. fn convert(&self) -> FontResult { match *self { RenderableText::Utf8(text) => Ok(CString::new(text).unwrap()), - RenderableText::Latin1(bytes) => match CString::new(bytes) { - Err(err) => Err(FontError::InvalidLatin1Text(err)), - Ok(cstring) => Ok(cstring), - }, - RenderableText::Char(ref string) => Ok(CString::new(string.as_bytes()).unwrap()), + RenderableText::Latin1(bytes) => { + CString::new(bytes).map_err(FontError::InvalidLatin1Text) + } + RenderableText::Char(ch) => { + Ok(CString::new(ch.encode_utf8(&mut [0; 4]).as_bytes()).unwrap()) + } } } } @@ -266,7 +262,7 @@ pub fn internal_load_font<'ttf, P: AsRef>( Err(get_error()) } else { Ok(Font { - raw: raw, + raw, rwops: None, _marker: PhantomData, }) @@ -280,7 +276,7 @@ where R: Into>>, { Font { - raw: raw, + raw, rwops: rwops.into(), _marker: PhantomData, } @@ -299,7 +295,7 @@ pub fn internal_load_font_at_index<'ttf, P: AsRef>( Err(get_error()) } else { Ok(Font { - raw: raw, + raw, rwops: None, _marker: PhantomData, }) @@ -333,11 +329,9 @@ impl<'ttf, 'r> Font<'ttf, 'r> { } /// Starts specifying a rendering of the given UTF-8-encoded character. - pub fn render_char<'a>(&'a self, ch: char) -> PartialRendering<'a, 'static> { - let mut s = String::new(); - s.push(ch); + pub fn render_char(&self, ch: char) -> PartialRendering<'_, 'static> { PartialRendering { - text: RenderableText::Char(s), + text: RenderableText::Char(ch), font: self, } } @@ -379,9 +373,7 @@ impl<'ttf, 'r> Font<'ttf, 'r> { /// Returns the width and height of the given text when rendered using this /// font. pub fn size_of_char(&self, ch: char) -> FontResult<(u32, u32)> { - let mut s = String::new(); - s.push(ch); - self.size_of(&s) + self.size_of(ch.encode_utf8(&mut [0; 4])) } /// Returns the font's style flags. @@ -465,31 +457,43 @@ impl<'ttf, 'r> Font<'ttf, 'r> { unsafe { ttf::TTF_FontFaceIsFixedWidth(self.raw) != 0 } } - /// Returns the family name of the current font face. - pub fn face_family_name(&self) -> Option { + /// Returns the family name of the current font face without doing any heap allocations. + pub fn face_family_name_borrowed(&self) -> Option<&'ttf CStr> { unsafe { // not owns buffer let cname = ttf::TTF_FontFaceFamilyName(self.raw); if cname.is_null() { None } else { - Some(String::from_utf8_lossy(CStr::from_ptr(cname).to_bytes()).to_string()) + Some(CStr::from_ptr(cname)) } } } - /// Returns the name of the current font face. - pub fn face_style_name(&self) -> Option { + /// Returns the family name of the current font face. + pub fn face_family_name(&self) -> Option { + self.face_family_name_borrowed() + .map(|cstr| String::from_utf8_lossy(cstr.to_bytes()).into_owned()) + } + + /// Returns the name of the current font face without doing any heap allocations. + pub fn face_style_name_borrowed(&self) -> Option<&'ttf CStr> { unsafe { let cname = ttf::TTF_FontFaceStyleName(self.raw); if cname.is_null() { None } else { - Some(String::from_utf8_lossy(CStr::from_ptr(cname).to_bytes()).to_string()) + Some(CStr::from_ptr(cname)) } } } + /// Returns the name of the current font face. + pub fn face_style_name(&self) -> Option { + self.face_style_name_borrowed() + .map(|cstr| String::from_utf8_lossy(cstr.to_bytes()).into_owned()) + } + /// Returns the index of the given character in this font face. pub fn find_glyph(&self, ch: char) -> Option { unsafe { @@ -523,11 +527,11 @@ impl<'ttf, 'r> Font<'ttf, 'r> { }; if ret == 0 { Some(GlyphMetrics { - minx: minx as i32, - maxx: maxx as i32, - miny: miny as i32, - maxy: maxy as i32, - advance: advance as i32, + minx, + maxx, + miny, + maxy, + advance, }) } else { None diff --git a/src/sdl2/url.rs b/src/sdl2/url.rs index 4e6cb332f28..8a662937e78 100644 --- a/src/sdl2/url.rs +++ b/src/sdl2/url.rs @@ -26,12 +26,10 @@ impl fmt::Display for OpenUrlError { } impl error::Error for OpenUrlError { - fn description(&self) -> &str { - use self::OpenUrlError::*; - - match *self { - InvalidUrl(_) => "invalid URL", - SdlError(ref e) => e, + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + match self { + Self::InvalidUrl(err) => Some(err), + Self::SdlError(_) => None, } } } diff --git a/src/sdl2/video.rs b/src/sdl2/video.rs index f6996262bd3..a47ff20c596 100644 --- a/src/sdl2/video.rs +++ b/src/sdl2/video.rs @@ -34,7 +34,7 @@ impl<'a> Deref for WindowSurfaceRef<'a> { impl<'a> DerefMut for WindowSurfaceRef<'a> { #[inline] fn deref_mut(&mut self) -> &mut SurfaceRef { - &mut self.0 + self.0 } } @@ -463,10 +463,10 @@ impl DisplayMode { pub fn from_ll(raw: &sys::SDL_DisplayMode) -> DisplayMode { DisplayMode::new( - PixelFormatEnum::try_from(raw.format as u32).unwrap_or(PixelFormatEnum::Unknown), - raw.w as i32, - raw.h as i32, - raw.refresh_rate as i32, + PixelFormatEnum::try_from(raw.format).unwrap_or(PixelFormatEnum::Unknown), + raw.w, + raw.h, + raw.refresh_rate, ) } @@ -565,7 +565,9 @@ impl Drop for WindowContext { impl WindowContext { #[inline] - /// Unsafe if the `*mut SDL_Window` is used after the `WindowContext` is dropped + /// # Safety + /// + /// Unsound if the `*mut SDL_Window` is used after the `WindowContext` is dropped pub unsafe fn from_ll( subsystem: VideoSubsystem, raw: *mut sys::SDL_Window, @@ -1089,14 +1091,10 @@ impl fmt::Display for WindowBuildError { } impl Error for WindowBuildError { - fn description(&self) -> &str { - use self::WindowBuildError::*; - - match *self { - HeightOverflows(_) => "window height overflow", - WidthOverflows(_) => "window width overflow", - InvalidTitle(_) => "invalid window title", - SdlError(ref e) => e, + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::InvalidTitle(err) => Some(err), + Self::HeightOverflows(_) | Self::WidthOverflows(_) | Self::SdlError(_) => None, } } }