From a0734fd3d8ed70bdfafb9d29338d2c23d983dd99 Mon Sep 17 00:00:00 2001 From: Matthew Collins Date: Sun, 19 Aug 2018 23:48:58 +0100 Subject: [PATCH] Fix undefined behavior with AudioStatus's FromPrimitive Transmuting from a value not in the enum is undefined, plus transmuting is generally not great to do. --- src/sdl2/audio.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/sdl2/audio.rs b/src/sdl2/audio.rs index ca020dee..6c87f0b0 100644 --- a/src/sdl2/audio.rs +++ b/src/sdl2/audio.rs @@ -60,7 +60,6 @@ use std::ops::{Deref, DerefMut}; use std::path::Path; use std::marker::PhantomData; use std::mem; -use std::mem::transmute; use std::ptr; use AudioSubsystem; @@ -209,12 +208,16 @@ pub enum AudioStatus { impl FromPrimitive for AudioStatus { fn from_i64(n: i64) -> Option { use self::AudioStatus::*; - let n = n as u32; - Some( match unsafe { transmute::(n) } { - sys::SDL_AudioStatus::SDL_AUDIO_STOPPED => Stopped, - sys::SDL_AudioStatus::SDL_AUDIO_PLAYING => Playing, - sys::SDL_AudioStatus::SDL_AUDIO_PAUSED => Paused, + const STOPPED: i64 = sys::SDL_AudioStatus::SDL_AUDIO_STOPPED as i64; + const PLAYING: i64 = sys::SDL_AudioStatus::SDL_AUDIO_PLAYING as i64; + const PAUSED: i64 = sys::SDL_AudioStatus::SDL_AUDIO_PAUSED as i64; + + Some(match n { + STOPPED => Stopped, + PLAYING => Playing, + PAUSED => Paused, + _ => return None, }) }