1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate lazy_static;
mod error;
use std::ffi::CString;
use std::fmt;
use std::fs;
use std::io;
use std::os::raw::c_char;
use error::{Error, ErrorKind};
use std::sync::Mutex;
lazy_static! {
pub static ref PROFILER: Mutex<Profiler> = Mutex::new(Profiler {
state: ProfilerState::Stopped,
});
}
#[link(name = "profiler")]
#[allow(non_snake_case)]
extern "C" {
fn ProfilerStart(fname: *const c_char) -> i32;
fn ProfilerStop();
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProfilerState {
Started,
Stopped,
}
impl fmt::Display for ProfilerState {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ProfilerState::Started => write!(f, "Started"),
ProfilerState::Stopped => write!(f, "Stopped"),
}
}
}
#[derive(Debug)]
pub struct Profiler {
state: ProfilerState,
}
impl Profiler {
pub fn start<T: Into<Vec<u8>>>(&mut self, fname: T) -> Result<(), Error> {
if self.state == ProfilerState::Stopped {
let c_fname = try!(CString::new(fname));
let metadata = try!(fs::metadata(try!(c_fname.to_str())));
if !metadata.is_file() {
Err(io::Error::new(io::ErrorKind::NotFound, "Invalid file for profile").into())
} else if metadata.permissions().readonly() {
Err(io::Error::new(io::ErrorKind::PermissionDenied, "File is readonly").into())
} else {
unsafe {
let res = ProfilerStart(c_fname.as_ptr());
if res == 0 {
Err(ErrorKind::InternalError.into())
} else {
self.state = ProfilerState::Started;
Ok(())
}
}
}
} else {
Err(ErrorKind::InvalidState(self.state).into())
}
}
pub fn stop(&mut self) -> Result<(), Error> {
if self.state == ProfilerState::Started {
unsafe {
ProfilerStop();
}
self.state = ProfilerState::Stopped;
Ok(())
} else {
Err(ErrorKind::InvalidState(self.state).into())
}
}
}