1
1
//! Framerate control
2
2
3
3
use get_error;
4
- use libc;
5
- use libc:: { c_void, size_t} ;
6
- use std:: mem;
4
+ use std:: mem:: MaybeUninit ;
7
5
use sys:: gfx;
8
6
9
7
/// Structure holding the state and timing information of the framerate controller.
8
+ #[ derive( Debug , Clone ) ]
10
9
pub 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
+ }
12
17
}
13
18
14
19
impl FPSManager {
15
20
/// Create the framerate manager.
16
21
pub fn new ( ) -> FPSManager {
17
22
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
+ }
22
28
}
23
29
}
24
30
25
31
/// Set the framerate in Hz.
26
32
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) } ;
28
34
match ret {
29
35
0 => Ok ( ( ) ) ,
30
36
_ => Err ( get_error ( ) ) ,
@@ -34,23 +40,19 @@ impl FPSManager {
34
40
/// Return the current target framerate in Hz.
35
41
pub fn get_framerate ( & self ) -> i32 {
36
42
// 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 }
38
45
}
39
46
40
47
/// Return the current framecount.
41
48
pub fn get_frame_count ( & self ) -> i32 {
42
49
// 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 }
44
52
}
45
53
46
54
/// Delay execution to maintain a constant framerate and calculate fps.
47
55
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 }
55
57
}
56
58
}
0 commit comments