11//! Framerate control
22
33use get_error;
4- use libc;
5- use libc:: { c_void, size_t} ;
6- use std:: mem;
4+ use std:: mem:: MaybeUninit ;
75use sys:: gfx;
86
97/// Structure holding the state and timing information of the framerate controller.
8+ #[ derive( Debug , Clone ) ]
109pub struct FPSManager {
11- raw : * mut gfx:: framerate:: FPSmanager ,
10+ raw : gfx:: framerate:: FPSmanager ,
11+ }
12+
13+ impl Default for FPSManager {
14+ fn default ( ) -> Self {
15+ Self :: new ( )
16+ }
1217}
1318
1419impl FPSManager {
1520 /// Create the framerate manager.
1621 pub fn new ( ) -> FPSManager {
1722 unsafe {
18- let size = mem:: size_of :: < gfx:: framerate:: FPSmanager > ( ) as size_t ;
19- let raw = libc:: malloc ( size) as * mut gfx:: framerate:: FPSmanager ;
20- gfx:: framerate:: SDL_initFramerate ( raw) ;
21- FPSManager { raw }
23+ let mut raw = MaybeUninit :: uninit ( ) ;
24+ gfx:: framerate:: SDL_initFramerate ( raw. as_mut_ptr ( ) ) ;
25+ FPSManager {
26+ raw : raw. assume_init ( ) ,
27+ }
2228 }
2329 }
2430
2531 /// Set the framerate in Hz.
2632 pub fn set_framerate ( & mut self , rate : u32 ) -> Result < ( ) , String > {
27- let ret = unsafe { gfx:: framerate:: SDL_setFramerate ( self . raw , rate) } ;
33+ let ret = unsafe { gfx:: framerate:: SDL_setFramerate ( & mut self . raw , rate) } ;
2834 match ret {
2935 0 => Ok ( ( ) ) ,
3036 _ => Err ( get_error ( ) ) ,
@@ -34,23 +40,19 @@ impl FPSManager {
3440 /// Return the current target framerate in Hz.
3541 pub fn get_framerate ( & self ) -> i32 {
3642 // will not get an error
37- unsafe { gfx:: framerate:: SDL_getFramerate ( self . raw ) as i32 }
43+ // SAFETY: SDL_getFramerate will not mutate self.raw, even though it accepts *mut FPSmanager.
44+ unsafe { gfx:: framerate:: SDL_getFramerate ( & self . raw as * const _ as * mut _ ) as i32 }
3845 }
3946
4047 /// Return the current framecount.
4148 pub fn get_frame_count ( & self ) -> i32 {
4249 // will not get an error
43- unsafe { gfx:: framerate:: SDL_getFramecount ( self . raw ) as i32 }
50+ // SAFETY: SDL_getFramecount will not mutate self.raw, even though it accepts *mut FPSmanager.
51+ unsafe { gfx:: framerate:: SDL_getFramecount ( & self . raw as * const _ as * mut _ ) as i32 }
4452 }
4553
4654 /// Delay execution to maintain a constant framerate and calculate fps.
4755 pub fn delay ( & mut self ) -> u32 {
48- unsafe { gfx:: framerate:: SDL_framerateDelay ( self . raw ) as u32 }
49- }
50- }
51-
52- impl Drop for FPSManager {
53- fn drop ( & mut self ) {
54- unsafe { libc:: free ( self . raw as * mut c_void ) }
56+ unsafe { gfx:: framerate:: SDL_framerateDelay ( & mut self . raw ) as u32 }
5557 }
5658}
0 commit comments